MerchantRepository.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. <?php
  2. /**
  3. * @package merchant
  4. *
  5. * @author xaboy
  6. * @day 2020-04-16
  7. *
  8. *
  9. */
  10. namespace app\common\repositories\system\merchant;
  11. use app\common\dao\system\merchant\MerchantDao;
  12. use app\common\enum\CommonEnum;
  13. use app\common\model\store\product\ProductReply;
  14. use app\common\repositories\BaseRepository;
  15. use app\common\repositories\shared\SharedProsperityRecommendConfigRepository;
  16. use app\common\repositories\store\product\ProductCopyRepository;
  17. use app\common\repositories\store\product\ProductRepository;
  18. use app\common\repositories\store\shipping\ShippingTemplateRepository;
  19. use app\common\repositories\store\StoreCategoryRepository;
  20. use app\common\repositories\system\attachment\AttachmentRepository;
  21. use app\common\repositories\user\UserRelationRepository;
  22. use app\common\repositories\user\UserVisitRepository;
  23. use app\common\repositories\wechat\RoutineQrcodeRepository;
  24. use app\controller\admin\system\merchant\MerchantIntention;
  25. use app\controller\merchant\gong\Goods;
  26. use app\entity\data\merchant\MerchantEntity;
  27. use app\traits\HaikeApiRequest;
  28. use crmeb\services\QrcodeService;
  29. use crmeb\services\UploadService;
  30. use FormBuilder\Exception\FormBuilderException;
  31. use FormBuilder\Factory\Elm;
  32. use FormBuilder\Form;
  33. use think\db\exception\DataNotFoundException;
  34. use think\db\exception\DbException;
  35. use think\db\exception\ModelNotFoundException;
  36. use think\Exception;
  37. use think\exception\ValidateException;
  38. use think\facade\Db;
  39. use think\facade\Log;
  40. use think\facade\Route;
  41. /**
  42. * Class MerchantRepository
  43. * @package app\common\repositories\system\merchant
  44. * @mixin MerchantDao
  45. * @author xaboy
  46. * @day 2020-04-16
  47. */
  48. class MerchantRepository extends BaseRepository
  49. {
  50. use HaikeApiRequest;
  51. /**
  52. * MerchantRepository constructor.
  53. * @param MerchantDao $dao
  54. */
  55. public function __construct(MerchantDao $dao)
  56. {
  57. $this->dao = $dao;
  58. }
  59. /**
  60. * @param array $where
  61. * @param $page
  62. * @param $limit
  63. * @return array
  64. * @throws DataNotFoundException
  65. * @throws DbException
  66. * @throws ModelNotFoundException
  67. * @author xaboy
  68. * @day 2020-04-16
  69. */
  70. public function lst(array $where, $page, $limit)
  71. {
  72. if (!empty($where["city"])){
  73. $city_id=Db::name("user_city")->where("city_name",$where["city"])->value("city_id");
  74. $where['city_id'] = $city_id;
  75. unset($where["city"]);
  76. }
  77. $query = $this->dao->search($where);
  78. $query = $query->with(['merchantCategory','spread']);
  79. $count = $query->count($this->dao->getPk());
  80. $list = $query->page($page, $limit)
  81. ->setOption('field', [])
  82. ->field('mer_id,merch_no, mer_name, real_name,name, mer_phone, mer_address, mark, status, create_time,is_best,recommender,category_id,type,withdrawal_setting,dc_id,merchant_level')
  83. ->select();
  84. foreach ($list as &$item) {
  85. if (!$item->withdrawal_setting && $item->merch_no != '') {
  86. try {
  87. $response = $this->merchantInfo(['merch_no' => $item->merch_no]);
  88. $item->withdrawal_setting = $response['pay_product_info']['settlement_cycle'];
  89. $item->save();
  90. } catch (\Throwable $e) {
  91. }
  92. }
  93. if($item['dc_id'] == 0){
  94. $item['dc'] = '无';
  95. }else{
  96. $item['dc'] = Db::name('big_warehouse') -> where('id',$item['dc_id']) -> value('warehouse_name');
  97. }
  98. $item['category_id']=(int)$item['category_id'];
  99. $item['status']=(int)$item['status'];
  100. $item['is_best']=(int)$item['is_best'];
  101. }
  102. unset($item);
  103. $merdata= [
  104. ['className'=> 'el-icon-s-order', 'count'=>$count, 'field'=> '个', 'name'=> '商户总数']
  105. ];
  106. return compact('count', 'list','merdata');
  107. }
  108. /**
  109. * @param array $where
  110. * @param $page
  111. * @param $limit
  112. * @return array
  113. * @throws DataNotFoundException
  114. * @throws DbException
  115. * @throws ModelNotFoundException
  116. */
  117. public function lstLeft(array $where, $page, $limit)
  118. {
  119. if (!empty($where["city"])){
  120. $city_id=Db::name("user_city")->where("city_name",$where["city"])->value("city_id");
  121. $where['city_id'] = $city_id;
  122. unset($where["city"]);
  123. }
  124. $query = $this->dao->searchLeft($where);
  125. $query = $query->with(['merchantCategory','spread']);
  126. $query = $query->withJoin(['MerchantIntention']);
  127. // $count = $query->count($this->dao->getPk());
  128. $count = $query->count('merchant.mer_id');
  129. $list = $query->page($page, $limit)
  130. ->setOption('field', [])
  131. ->field('merchant.mer_id,merchant.merch_no, merchant.mer_name, merchant.real_name,merchant.name, merchant.mer_phone, merchant.mer_address, merchant.mark, merchant.status, merchant.create_time,merchant.is_best,merchant.recommender,merchant.category_id,merchant.type,merchant.withdrawal_setting,merchant.dc_id,merchant.merchant_level')
  132. ->select();
  133. foreach ($list as &$item) {
  134. if (!$item->withdrawal_setting && $item->merch_no != '') {
  135. try {
  136. $response = $this->merchantInfo(['merch_no' => $item->merch_no]);
  137. $item->withdrawal_setting = $response['pay_product_info']['settlement_cycle'];
  138. $item->save();
  139. } catch (\Throwable $e) {
  140. }
  141. }
  142. if($item['dc_id'] == 0){
  143. $item['dc'] = '无';
  144. }else{
  145. $item['dc'] = Db::name('big_warehouse') -> where('id',$item['dc_id']) -> value('warehouse_name');
  146. }
  147. $item['category_id']=(int)$item['category_id'];
  148. $item['status']=(int)$item['status'];
  149. $item['is_best']=(int)$item['is_best'];
  150. }
  151. unset($item);
  152. $merdata= [
  153. ['className'=> 'el-icon-s-order', 'count'=>$count, 'field'=> '个', 'name'=> '商户总数']
  154. ];
  155. return compact('count', 'list','merdata');
  156. }
  157. /**
  158. * @param int|null $id
  159. * @param array $formData
  160. * @return Form
  161. * @throws FormBuilderException
  162. * @author xaboy
  163. * @day 2020-04-16
  164. */
  165. public function form(?int $id = null, array $formData = [])
  166. {
  167. $form = Elm::createForm(is_null($id) ? Route::buildUrl('systemMerchantCreate')->build() : Route::buildUrl('systemMerchantUpdate_1', ['id' => $id])->build());
  168. /** @var MerchantCategoryRepository $make */
  169. $make = app()->make(MerchantCategoryRepository::class);
  170. // $config = systemConfig(['broadcast_room_type', 'broadcast_goods_type']);
  171. $formData['category_id']=(int)$formData['category_id'];
  172. $formData['status']=(int)$formData['status'];
  173. $formData['is_audit']=(int)$formData['is_audit'];
  174. $formData['is_best']=(int)$formData['is_best'];
  175. $rule = [
  176. Elm::input('mer_name', '商户名称')->required(),
  177. // Elm::select('mer_type', '一壶茶会员专区商户')->options(function () {
  178. // return array(
  179. // array('value'=>'0','label'=>'普通商户'),
  180. // array('value'=>'1','label'=>'一壶茶会员专区商户'),
  181. // );
  182. // })->required(),
  183. Elm::select('category_id', '商户分类')->options(function () use ($make) {
  184. $data = $make->allOptions();
  185. $options = [];
  186. foreach ($data as $value => $label) {
  187. $options[] = compact('value', 'label');
  188. }
  189. return $options;
  190. })->requiredNum(),
  191. Elm::input('mer_account', '商户账号')->required()->disabled(!is_null($id))->required(!is_null($id)),
  192. Elm::password('mer_password', '登录密码')->required()->disabled(!is_null($id))->required(!is_null($id)),
  193. Elm::input('real_name', '商户姓名'),
  194. Elm::input('mer_phone', '商户手机号')->col(12),
  195. // Elm::number('commission_rate', '手续费(%)')->col(12),
  196. Elm::input('mer_keyword', '商户关键字')->col(12),
  197. Elm::input('mer_address', '商户地址'),
  198. Elm::input('lng', '经度')->col(12),
  199. Elm::input('lat', '纬度')->col(12),
  200. Elm::textarea('mark', '备注'),
  201. Elm::number('sort', '排序', 0),
  202. Elm::switches('status', '是否开启', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  203. //Elm::switches('is_bro_room', '直播间审核', $config['broadcast_room_type'] == 1 ? 0 : 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  204. Elm::switches('is_audit', '产品审核', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  205. //Elm::switches('is_bro_goods', '直播间商品审核', $config['broadcast_goods_type'] == 1 ? 0 : 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  206. Elm::switches('is_best', '是否推荐')->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启'),
  207. Elm::switches('is_show_alibaba', '阿里巴巴')->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启'),
  208. ];
  209. $form->setRule($rule);
  210. return $form->setTitle(is_null($id) ? '添加商户' : '编辑商户')->formData($formData);
  211. }
  212. /**
  213. * @param array $formData
  214. * @return Form
  215. * @throws FormBuilderException
  216. * @author xaboy
  217. * @day 2020/6/25
  218. */
  219. public function merchantForm(array $formData = [])
  220. {
  221. if(isset($formData['mer_state'])){$formData['mer_state']=(int)$formData['mer_state'];}
  222. $form = Elm::createForm(Route::buildUrl('merchantUpdate')->build());
  223. $rule = [
  224. Elm::input('mer_phone', '手机号')->readonly(true),
  225. Elm::input('email', '邮箱')->readonly(true),
  226. Elm::input('product_score', '商品描述评分')->readonly(true),
  227. Elm::input('service_score', '服务评分')->readonly(true),
  228. Elm::input('postage_score', '物流评分')->readonly(true),
  229. Elm::input('care_count', '关注总数')->readonly(true),
  230. Elm::input('bank_location', '开户所在地')->readonly(true),
  231. Elm::input('bank_deposit', '开户行')->readonly(true),
  232. Elm::input('bank_branch', '开户支行')->readonly(true),
  233. Elm::input('bank_account', '开户账号')->readonly(true),
  234. Elm::input('open_account', '开户许可证')->readonly(true),
  235. // Elm::input('district_addr', '商圈')->required(),
  236. Elm::textarea('mer_info', '店铺简介')->required(),
  237. Elm::input('service_phone', '服务电话')->required(),
  238. Elm::frameImage('mer_banner', '店铺 banner', '/' . config('admin.merchant_prefix') . '/setting/uploadPicture?field=mer_banner&type=1')->modal(['modal' => false])->width('896px')->height('480px')->props(['footer' => false]),
  239. Elm::frameImage('mer_avatar', '店铺头像', '/' . config('admin.merchant_prefix') . '/setting/uploadPicture?field=mer_avatar&type=1')->modal(['modal' => false])->width('896px')->height('480px')->props(['footer' => false]),
  240. Elm::switches('mer_state', '是否开启', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  241. ];
  242. $form->setRule($rule);
  243. return $form->setTitle('编辑店铺信息')->formData($formData);
  244. }
  245. /**
  246. * @param $id
  247. * @return Form
  248. * @throws FormBuilderException
  249. * @throws DataNotFoundException
  250. * @throws DbException
  251. * @throws ModelNotFoundException
  252. * @author xaboy
  253. * @day 2020-04-16
  254. */
  255. public function updateForm($id)
  256. {
  257. $data = $this->dao->get($id)->toArray();
  258. /** @var MerchantAdminRepository $make */
  259. $make = app()->make(MerchantAdminRepository::class);
  260. $data['mer_account'] = $make->merIdByAccount($id);
  261. $data['mer_password'] = '***********';
  262. return $this->form($id, $data);
  263. }
  264. /**
  265. * @param array $data
  266. * @author xaboy
  267. * @day 2020-04-17
  268. */
  269. public function createMerchant(array $data)
  270. {
  271. /** @var MerchantAdminRepository $make */
  272. $make = app()->make(MerchantAdminRepository::class);
  273. Db::transaction(function () use ($data, $make) {
  274. $account = $data['mer_account'];
  275. $password = $data['mer_password'];
  276. unset($data['mer_account'], $data['mer_password']);
  277. $merchant = $this->dao->create($data);
  278. $make->createMerchantAccount($merchant, $account, $password);
  279. app()->make(ShippingTemplateRepository::class)->createDefault($merchant->mer_id);
  280. app()->make(ProductCopyRepository::class)->defaulCopyNum($merchant->mer_id);
  281. });
  282. }
  283. /**
  284. * @Author:Qinii
  285. * @Date: 2020/5/30
  286. * @param $where
  287. * @param $page
  288. * @param $limit
  289. * @return array
  290. */
  291. public function getList($where, $page, $limit, $userInfo)
  292. {
  293. $where['status'] = 1;
  294. $where['mer_state'] = 1;
  295. if ($userInfo && $where['keyword'] !== '')
  296. app()->make(UserVisitRepository::class)->searchMerchant($userInfo['uid'], $where['keyword']);
  297. if($where['category_id'] == 0) {
  298. unset($where['category_id']);
  299. $query = $this->dao->search($where)->with(['showProduct']);
  300. $query = $query->order("create_time desc")->limit("10");
  301. }else{
  302. $query = $this->dao->search($where)->with(['showProduct']);
  303. }
  304. $count = $query->count($this->dao->getPk());
  305. $list = $query->page($page, $limit)->setOption('field', [])
  306. ->field('lat,lng,addr,mer_id,mer_banner,mer_name, mark,mer_avatar,product_score,service_score,postage_score,sales,status,create_time,category_id')
  307. ->select()
  308. ->each(function ($item) {
  309. $data = $item->showProduct->toArray();
  310. unset($item->showProduct);
  311. $recommend = array_slice($data, 0, 3);
  312. return $item['recommend'] = $recommend;
  313. });
  314. return compact('count', 'list');
  315. }
  316. /**
  317. * @Author:Qinii
  318. * @Date: 2020/5/30
  319. * @param int $id
  320. * @return array|\think\Model|null
  321. */
  322. public function merExists(int $id)
  323. {
  324. return ($this->dao->get($id));
  325. }
  326. /**
  327. * @Author:Qinii
  328. * @Date: 2020/5/30
  329. * @param $id
  330. * @param $userInfo
  331. * @return array|\think\Model|null
  332. */
  333. public function detail($id, $userInfo, $lat='', $lng='')
  334. {
  335. $merchant = $this->dao->apiGetOne($id)->hidden(["real_name", "mer_phone", "reg_admin_id", "sort", "is_del", "is_audit", "is_best", "mer_state", "bank", "bank_number", "bank_name", 'update_time']);
  336. $merchant['care'] = false;
  337. $merchant['like']=false;
  338. $merchant['topping']=false;
  339. if ($userInfo){
  340. $like=Db::name('store_fabulous')->where(['uid'=>$userInfo->uid,'mer_id'=>$id])->value('status');
  341. if($like==1){
  342. $like=true;
  343. }else{
  344. $like=false;
  345. }
  346. if($userInfo->mer_topping==$id){
  347. $topping=true;
  348. }else{
  349. $topping=false;
  350. }
  351. $merchant['care'] = $this->getCareByUser($id, $userInfo->uid);
  352. $merchant['like']=$like;
  353. $merchant['topping']=$topping;
  354. }
  355. // Db::name("merchant")->where("mer_id",$cartInfo['mer_id'])->inc('renqizhi', 1)
  356. $this->dao->addrenqi($id);
  357. if($merchant['content_pic']){
  358. $merchant['content_pic'] = explode(',',$merchant['content_pic']);
  359. }
  360. $lat=empty($lat)?"34.73841":$lat;
  361. $lng=empty($lng)?"113.643636":$lng;
  362. $field = 'ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 )
  363. * COS((lat * 3.1415) / 180 ) *COS(('.$lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance';
  364. $distance =Db::name("merchant")
  365. ->where("mer_id",$id)
  366. ->field($field)
  367. ->find();
  368. $merchant['distance'] =sprintf("%.2f",$distance['distance']);
  369. return $merchant;
  370. }
  371. /**
  372. * @Author:Qinii
  373. * @Date: 2020/5/30
  374. * @param int $merId
  375. * @param int $userId
  376. * @return bool
  377. */
  378. public function getCareByUser(int $merId, int $userId)
  379. {
  380. if (app()->make(UserRelationRepository::class)->getWhere(['type' => 10, 'type_id' => $merId, 'uid' => $userId]))
  381. return true;
  382. return false;
  383. }
  384. /**
  385. * @Author:Qinii
  386. * @Date: 2020/5/30
  387. * @param $merId
  388. * @param $where
  389. * @param $page
  390. * @param $limit
  391. * @param $userInfo
  392. * @return mixed
  393. */
  394. public function productList($merId, $where, $page, $limit, $userInfo,$type439=false,$is_commercetrade = 0)
  395. {
  396. // log::info("========j进入prodctList");
  397. // log::info($merId);
  398. // log::info( $where);
  399. // log::info($userInfo);
  400. // log::info($type439);
  401. $list=app()->make(ProductRepository::class)->getApiSearch($merId, $where, $page, $limit, $userInfo,$type439);
  402. $arr=[];
  403. foreach ($list["list"] as $v){
  404. $k= app()->make(ProductRepository::class)->pvParm($v['product_id']);
  405. $productMerId = $v['mer_id'] ?? 0;
  406. // $v['special_merchant']= merchantConfig($v['mer_id'], 'special_merchant');
  407. // log::info("==========yang= {$k['yanglao']} ");
  408. $v['yanglao']='';
  409. $v['pv']='';
  410. $v['jifen']='';
  411. $v['gongxian']='';
  412. $v['jfduihuan']='';
  413. $v['jdduihuan']='';
  414. //会员专区中VR或者现金和VR+现金形式
  415. //支付组合
  416. $v['fzone_paytype'] = '';
  417. //$v['vr'] = 0;
  418. $num_yl = 0;
  419. if($v['price'] == '1180'){
  420. $num_yl = 1000;
  421. }else if($v['price'] == '10620'){
  422. $num_yl = 9000;
  423. }else if($v['price'] == '11800'){
  424. $num_yl = 10000;
  425. }else if($v['price'] == '2360'){
  426. $num_yl = 2000;
  427. }else if($v['price'] == '9440'){
  428. $num_yl = 8000;
  429. }else if($v['price'] == '5900'){
  430. $num_yl = 5000;
  431. }
  432. if($productMerId == 496){
  433. $v['yanglao'] = bcmul($num_yl, 0.035, 2);
  434. $v['pv'] = bcmul($num_yl, 0.7, 2);
  435. //$v['vr']=$v['price'];
  436. //1:为会员专区,
  437. $v['fzone_paytype']= [
  438. 1=>[
  439. 1=>$v['price'],//VR
  440. 2=>$v['price']//现金
  441. ]
  442. ];
  443. }else if($productMerId == 439 || $is_commercetrade){
  444. //精彩生活和商贸区
  445. $jf = $v['price'] - bcmul($v['concession_pri'],0.3, 2) . ' + ' . bcmul($v['concession_pri'],0.3, 2);
  446. $jd = $v['price'] - bcmul($v['concession_pri'],0.35, 2) . ' + ' . bcmul($v['concession_pri'],0.35, 2);
  447. if($v['concession_pri'] !=null || $v['concession_pri'] !=0){
  448. $v['yanglao'] = bcmul($v['concession_pri'],0.3, 2);
  449. $v['pv'] = bcmul($v['concession_pri'],0.35, 2);
  450. $v['jfduihuan'] =$jf;
  451. $v['jdduihuan'] = $jd;
  452. $v['jifen'] = bcmul($v['concession_pri'], 0.35, 2);
  453. $v['gongxian'] = bcmul($v['concession_pri'], 0.35, 2);
  454. }
  455. }else if($productMerId == 491){
  456. // 获取商品sku
  457. $productSku = Db::name('store_product_attr_value')->where('product_id', $v['product_id'])->order('price asc')->find();
  458. $pv = $productSku['plate_mer_profit']??0.00;
  459. // $num_yl = $v['price'];
  460. // $pv= $num_yl * 0.3;
  461. $yanglao = bcmul($pv, 0.5, 2);
  462. $v['pv'] = $pv;
  463. $v['yanglao'] = $yanglao;
  464. $v['fzone_paytype']= [
  465. 1=>[
  466. 1=>$v['price'],//VR
  467. 2=>$v['price'],//现金
  468. 3=>$v['price']//复购金
  469. ]
  470. ];
  471. }else if ($productMerId == 3447) {
  472. $yanglao = bcmul($v['price'], CommonEnum::ORDER_EARNING_ALLOCATION['SharedProsperity']['Self']['YangLaoJin']['Ratio']['code'], 2);
  473. $v['yanglao'] = $yanglao;
  474. // 计算共富区PV
  475. /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
  476. $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
  477. $sharedProsperityRecommendConfigEntityByMaxRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxRewardRatio();
  478. // 利润 减去 顶格的直推奖,剩下的是PV值
  479. $pvProportion = bcsub('1', bcdiv($sharedProsperityRecommendConfigEntityByMaxRewardRatio->getRewardRatio(), '100', 4), 2);
  480. // 获取利润
  481. $productSku = Db::name('store_product_attr_value')->where('product_id', $v['product_id'])->order('price asc')->find();
  482. // 计算pv
  483. $pv = bcmul($productSku['plate_mer_profit'], $pvProportion, CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
  484. $v['pv'] = $pv;
  485. }
  486. if ($v['pension_is'] != 0) {
  487. $v['yanglao'] = $v['pension'];
  488. }
  489. // $v=($v,$k);
  490. // array_push($v,$k);
  491. $arr[]=$v;
  492. }
  493. $list["merId"]=$merId;
  494. $list["list"]=$arr;
  495. return $list;
  496. }
  497. public function productList_yhc($merId, $where, $page, $limit, $userInfo)
  498. {
  499. unset($where['order']);
  500. if (isset($where['price_on']) && $where['price_on'] != '')$where['price'] = [$where['price_asc'], $where['price_desc']];
  501. if (isset($where['brand_id']) && $where['brand_id'] != '') $where['brand_id'] = explode(',', $where['brand_id']);
  502. unset($where['price_on'], $where['price_off']);
  503. //搜索记录
  504. if ($userInfo && isset($where['keyword']) && !empty($where['keyword']))
  505. app()->make(UserVisitRepository::class)->searchProduct($userInfo['uid'], $where['keyword']);
  506. $query = Db::name('store_product')->where('product_id','>',0)->where('mer_id', $merId)->where('type', 17);
  507. $keyArray = $whereArr = [];
  508. unset($where['type']);
  509. foreach ($where as $key => $item) {
  510. if ($item !== '' && $key != 'soft') {
  511. $keyArray[] = $key;
  512. $whereArr[$key] = $item;
  513. }
  514. }
  515. unset($whereArr['order']);
  516. $query->withSearch($keyArray, $whereArr)->where('is_show',1)->where('status',1);
  517. $query->when(isset($where['keyword']) && $where['keyword'] != '', function ($query) use ($where) {
  518. $query->whereLike('store_name', "%{$where['keyword']}%");
  519. unset($where['keyword']);
  520. });
  521. $query->order('sort DESC ,create_time DESC');
  522. $query->with(['merchant'])->with(['issetCoupon']);
  523. $count = $query->count();
  524. // echo DB::getlastsql();die;
  525. $filed = 'product_id,mer_id,brand_id,unit_name,rate,reply_count,store_info,cate_id,ficti,image,slider_image,store_name,keyword,sort,is_show,sales,price,refusal,cost,ot_price,stock,is_gift_bag,care_count,status,is_used,create_time,seckill,plate_mer_profit,type';
  526. $list = $query->page($page, $limit)->setOption('field', [])->field($filed)->select();
  527. $ProductRepository=app()->make(ProductRepository::class);
  528. $list->each(function ($item) use ($ProductRepository) {
  529. $item['sales'] = $item['sales'] + $item['ficti'];
  530. unset($item['ficti']);
  531. $item['yanglao'] = $ProductRepository->yanglaojin($item['product_id']);
  532. return $item;
  533. });
  534. // if ($this->getUserIsPromoter($userInfo)) $list = $list->each(function ($item) {
  535. // return $item['max_extension'] = $item->max_extension;
  536. // });
  537. $list= compact('count', 'list');
  538. $arr=[];
  539. foreach ($list["list"] as $v){
  540. $v['yanglao']= app()->make(ProductRepository::class)->yanglaojin($v['product_id']);
  541. $v['special_merchant']= merchantConfig($v['mer_id'], 'special_merchant');
  542. $arr[]=$v;
  543. }
  544. $list["list"]=$arr;
  545. return $list;
  546. }
  547. /**
  548. * @Author:Qinii
  549. * @Date: 2020/5/30
  550. * @param int $id
  551. * @return mixed
  552. */
  553. public function categoryList(int $id)
  554. {
  555. return app()->make(StoreCategoryRepository::class)->getApiFormatList($id, 1);
  556. }
  557. public function offlineUserQrcode($merId, $userId,$queryString = '/h5payment/index.html', $imgName = '_store_user_offline_wap.jpg')
  558. {
  559. $siteUrl = systemConfig('site_url');
  560. $name = $merId . $userId . $imgName;
  561. $attachmentRepository = app()->make(AttachmentRepository::class);
  562. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  563. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  564. $imageInfo->delete();
  565. $imageInfo = null;
  566. }
  567. if (!$imageInfo) {
  568. $codeUrl = set_http_type(rtrim($siteUrl, '/') . $queryString.'?id=' . $merId . '&user_id=' . $userId, request()->isSsl() ? 0 : 1);//二维码链接
  569. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
  570. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  571. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  572. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  573. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -2, $merId, [
  574. 'attachment_category_id' => 0,
  575. 'attachment_name' => $imageInfo['name'],
  576. 'attachment_src' => $imageInfo['dir']
  577. ]);
  578. $urlCode = $imageInfo['dir'];
  579. } else $urlCode = $imageInfo['attachment_src'];
  580. return $urlCode;
  581. }
  582. public function wxQrcode($merId, $queryString = '/pages/store/home/index', $imgName = '_store_wap.jpg', $avatar = '')
  583. {
  584. $siteUrl = systemConfig('site_url');
  585. $name = $merId . $imgName;
  586. $attachmentRepository = app()->make(AttachmentRepository::class);
  587. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  588. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  589. $imageInfo->delete();
  590. $imageInfo = null;
  591. }
  592. if (!$imageInfo) {
  593. $codeUrl = set_http_type(rtrim($siteUrl, '/') . $queryString.'?id=' . $merId, request()->isSsl() ? 0 : 1);//二维码链接
  594. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name, $avatar);
  595. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  596. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  597. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  598. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -2, $merId, [
  599. 'attachment_category_id' => 0,
  600. 'attachment_name' => $imageInfo['name'],
  601. 'attachment_src' => $imageInfo['dir']
  602. ]);
  603. $urlCode = $imageInfo['dir'];
  604. } else $urlCode = $imageInfo['attachment_src'];
  605. return $urlCode;
  606. }
  607. public function routineQrcode($merId, $queryString = '/pages/store/home/index', $imgName = '_store_routine.jpg')
  608. {
  609. $name = $merId . $imgName;
  610. $attachmentRepository = app()->make(AttachmentRepository::class);
  611. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  612. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  613. $imageInfo->delete();
  614. $imageInfo = null;
  615. }
  616. if (!$imageInfo) {
  617. $uploadType = (int)systemConfig('upload_type') ?: 1;
  618. $routineQrcodeRepository = app()->make(RoutineQrcodeRepository::class);
  619. $res = $routineQrcodeRepository->getShareCode($merId, 'store', $queryString.'?id=' . $merId, '');
  620. if (!$res) throw new ValidateException('二维码生成失败');
  621. $upload = UploadService::create($uploadType);
  622. $uploadRes = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
  623. if ($uploadRes === false) {
  624. throw new ValidateException($upload->getError());
  625. }
  626. $imageInfo = $upload->getUploadInfo();
  627. $imageInfo['image_type'] = $uploadType;
  628. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  629. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  630. $attachmentRepository->create($uploadType, -2, $merId, [
  631. 'attachment_category_id' => 0,
  632. 'attachment_name' => $imageInfo['name'],
  633. 'attachment_src' => $imageInfo['dir']
  634. ]);
  635. $routineQrcodeRepository->setRoutineQrcodeFind($res['id'], ['status' => 1, 'url_time' => date('Y-m-d H:i:s'), 'qrcode_url' => $imageInfo['dir']]);
  636. $urlCode = $imageInfo['dir'];
  637. } else $urlCode = $imageInfo['attachment_src'];
  638. return $urlCode;
  639. }
  640. public function copyForm(int $id)
  641. {
  642. $form = Elm::createForm(Route::buildUrl('systemMerchantChangeCopy', ['id' => $id])->build());
  643. $form->setRule([
  644. Elm::radio('type', '修改类型', 1)
  645. ->setOptions([
  646. ['value' => 1, 'label' => '增加'],
  647. ['value' => 2, 'label' => '减少'],
  648. ]),
  649. Elm::number('num', '修改数量', $this->dao->getCopyNum($id))->required()
  650. ]);
  651. return $form->setTitle('修改复制商品次数');
  652. }
  653. /**
  654. * @Author:Qinii
  655. * @Date: 2020/10/10
  656. * @param $where
  657. * @param $page
  658. * @param $limit
  659. * @return array
  660. */
  661. public function getLists($data, $page, $limit, $type=1,$where=[])
  662. {
  663. $where['status'] = 1;
  664. $where['mer_state'] = 1;
  665. $field = 'ACOS(SIN(('.$data["lat"].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$data["lat"].' * 3.1415) / 180 )
  666. * COS((lat * 3.1415) / 180 ) *COS(('.$data["lng"].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance';
  667. $fields =$field.',mer_id,mer_name,mark,mer_avatar,status,create_time,category_id,district_addr,care_count,renqizhi,sales';
  668. if (!empty($data["city_name"])){
  669. $city_id=Db::name("user_city")->where("city_name",$data["city_name"])->value("city_id");
  670. $where['city_id'] = $city_id;
  671. }
  672. if ($type==1) {
  673. if ( empty($where['category_id'])){
  674. $order = "mer_id desc";
  675. }else{
  676. $where['is_best'] = 1;
  677. $order = "mer_id desc,distance asc";
  678. }
  679. }else if($type==2){
  680. if ($data["order"]==1){
  681. $order = "distance asc";
  682. }else{
  683. $order = ['care_count'=>'desc'];
  684. }
  685. }
  686. $query = $this->dao->search($where);
  687. $count = $query->count($this->dao->getPk());
  688. $list =Db::name("merchant")
  689. ->where($where)
  690. ->page($page, $limit)
  691. ->field($fields)
  692. // ->having('distance <= '.'10000')
  693. ->order($order)
  694. ->select()
  695. ->each(function ($item) {
  696. $item['label'] ="人气";
  697. // $item['sales'] =$item["renqizhi"];
  698. $item['distance'] =sprintf("%.2f",$item['distance']);
  699. $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
  700. // var_dump(merchantConfig($item['mer_id'], 'printing_client_id'));exit();
  701. // $yanglao=merchantConfig($item['mer_id'], 'printing_client_id')/100;
  702. $base_commission=merchantConfig($item['mer_id'], 'base_commission');
  703. if($base_commission <= 0){
  704. $base_commission= systemConfig("extension_one_rate");
  705. }
  706. //商户养老金比例
  707. $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
  708. if(!$yanglao){
  709. //若商户养老金比例不存在 则使用平台配置
  710. $yanglao = systemConfig('yanglaojin_admin');
  711. }
  712. $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
  713. return $item;
  714. })->toArray();
  715. $counts=count($list);
  716. if( $counts<10 && $type==1){
  717. $ids=[];
  718. foreach($list as $v){
  719. $ids[]=$v["mer_id"];
  720. }
  721. $city_id=$where["city_id"];
  722. unset($where["city_id"]);
  723. $lists =Db::name("merchant")
  724. ->where($where)
  725. ->where("city_id","<>",$city_id)
  726. ->where("mer_id","<>",implode(",",$ids))
  727. ->page(1, 10-$counts)
  728. ->field($fields)
  729. ->order("distance asc")
  730. ->select()
  731. ->each(function ($item) {
  732. $item['label'] ="人气";
  733. // $item['sales'] =$item["renqizhi"];
  734. $item['distance'] =sprintf("%.2f",$item['distance']);
  735. $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
  736. $base_commission=merchantConfig($item['mer_id'], 'base_commission');
  737. if($base_commission <= 0){
  738. $base_commission= systemConfig("extension_one_rate");
  739. }
  740. //商户养老金比例
  741. $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
  742. if(!$yanglao){
  743. //若商户养老金比例不存在 则使用平台配置
  744. $yanglao = systemConfig('yanglaojin_admin');
  745. }
  746. $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
  747. return $item;
  748. })->toArray();
  749. $list=array_merge($list,$lists);
  750. }
  751. return compact('count', 'list','where');
  752. }
  753. /**
  754. * @Date: 2020/10/31
  755. * @param $where
  756. * @param $page
  757. * @param $limit
  758. * @return array
  759. * @author cabbage
  760. */
  761. public function getLst($data, $page, $limit,$where=[])
  762. {
  763. //下过单的店铺
  764. $mer_ids="";
  765. if (!empty($data["user_id"])){
  766. $mer_ids=Db::name('store_order')->where("uid",$data["user_id"])->order("order_id desc")->column("mer_id");
  767. if ($mer_ids){
  768. $mer_ids=array_unique($mer_ids);
  769. }
  770. }
  771. $where['status'] = 1;
  772. $where['mer_state'] = 1;
  773. $where['sxy_submerchant_id'] = 1;
  774. $field = '';
  775. if(!empty($data['lat']) && !empty($data['lng'])){
  776. $field = 'ACOS(SIN(('.$data["lat"].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$data["lat"].' * 3.1415) / 180 )
  777. * COS((lat * 3.1415) / 180 ) *COS(('.$data["lng"].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance,';
  778. }else{
  779. $field = "mer_id as distance";
  780. }
  781. $fields =$field.'mer_id,mer_name,mark,mer_avatar,sales,status,create_time,category_id,care_count,sales,district_addr,renqizhi';
  782. if ($mer_ids){
  783. $order = [
  784. "FIELD (id,{$mer_ids})"=>'desc',
  785. 'sales'=>'desc', //销量
  786. 'care_count'=>'desc', //关注
  787. 'distance'=>"asc"//距离
  788. ];
  789. }else{
  790. $order = [
  791. 'distance'=>"asc",//距离
  792. 'sales'=>'desc', //销量
  793. 'care_count'=>'desc', //关注
  794. ];
  795. }
  796. if($data["order"]==1){
  797. $order = [
  798. 'distance'=>"asc",//距离
  799. 'sales'=>'asc',
  800. 'care_count'=>'asc',
  801. ];
  802. }
  803. $data['distance'] = ($data['distance']&&$data['distance']!=50)?$data['distance']:8000;
  804. $query = $this->dao->search_mer($where);
  805. $count = $query->count($this->dao->getPk());
  806. $list = $query
  807. ->page($page, $limit)
  808. ->setOption('field', [])
  809. ->field($fields)
  810. ->having('distance <= '.$data['distance'])
  811. ->order($order)
  812. ->select()
  813. ->each(function ($item) {
  814. $item['popularity'] =$item["renqizhi"];
  815. $item['sales'] =$item["sales"];
  816. $item['distance'] =sprintf("%.2f",$item['distance']);
  817. if ( $item['distance']<=10){
  818. $item['label'] ="附近";
  819. }else{
  820. $item['label'] ="附近";
  821. }
  822. $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
  823. $base_commission=merchantConfig($item['mer_id'], 'base_commission');
  824. if($base_commission <= 0){
  825. $base_commission= systemConfig("extension_one_rate");
  826. }
  827. //商户养老金比例
  828. $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
  829. if(!$yanglao){
  830. //若商户养老金比例不存在 则使用平台配置
  831. $yanglao = systemConfig('yanglaojin_admin');
  832. }
  833. $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
  834. return $item;
  835. });
  836. return compact('count', 'list','order','where');
  837. }
  838. /**
  839. *
  840. * @param $page
  841. * @param $limit
  842. * @return array
  843. */
  844. public function merchantcategory()
  845. {
  846. return Db::name('merchant_category')->where("status",1)->order("order_sort desc,merchant_category_id desc")->select()->toArray();
  847. }
  848. /*商家分类列表*/
  849. public function mercat($page, $limit)
  850. {
  851. $count= Db::name('merchant_category')->count();
  852. $list= Db::name('merchant_category')->where("status",1)->order("order_sort desc,merchant_category_id desc")->select()->toArray();
  853. return compact('count', 'list');
  854. }
  855. /**
  856. * @param $id
  857. * @return Form
  858. * @throws FormBuilderException
  859. * @author xaboy
  860. * @day 2020-05-07
  861. */
  862. public function changeProForm($id)
  863. {
  864. return Elm::createForm(Route::buildUrl('systemMerchantChangePro', compact('id'))->build(), [
  865. Elm::input('spread_account', '推荐人')->required()->value("请填写推荐人手机号")
  866. ])->setTitle('修改商户推荐人');
  867. }
  868. /*
  869. * 修改商户推广人id
  870. *@author cabbage
  871. *@date 2020-10-31
  872. * */
  873. public function update_spread($id,$spread_account){
  874. //推荐人信息
  875. $spread = Db::name("user")->where('account',$spread_account)->value("uid");
  876. $mer_uid = Db::name("merchant")->where(['mer_id'=>$id])->value("uid");
  877. if($spread && $mer_uid){
  878. try{
  879. Db::name("user")->where(["uid"=>$mer_uid])->update(['spread_uid'=>$spread]);
  880. Db::name("merchant")->where(["mer_id"=>$id])->update(['recommender'=>$spread]);
  881. return true;
  882. }catch (Exception $e) {
  883. Db::rollback();
  884. }
  885. }else{
  886. return false;
  887. }
  888. }
  889. /*下架商品*/
  890. public function MerUpdate($where,$data)
  891. {
  892. return Db::name("store_product")->where($where)->update($data);
  893. }
  894. /*推荐商品*/
  895. public function getProductGoodList($id){
  896. $where['is_gift_bag'] = 0;
  897. $where['is_used'] = 1;
  898. $where['product_type'] = 0;
  899. $where['mer_id'] = $id;
  900. $where['is_good'] = 1;
  901. return Db::name("store_product")->where($where)->field("image,product_id,store_name as title,price,ot_price")->select();
  902. }
  903. /*收款二维码*/
  904. public function getQrCode($mer){
  905. $res = Db::name("MerchantQrcode")
  906. -> where("mer_id",$mer -> mer_id)
  907. -> field("qrcode_src as url,show_src")
  908. -> find();
  909. if(!$res || $res['url'] == '' || $res['show_src'] == ''){
  910. Db::name("MerchantQrcode") -> where("mer_id",$mer -> mer_id) -> delete();
  911. $attachmentRepository = app()->make(AttachmentRepository::class);
  912. $siteUrl = systemConfig('site_url');
  913. $merchantIntertion = app() -> make(MerchantIntention::class);
  914. $id = $merchantIntertion -> getNewQrcodeId();
  915. $name = "offlinepay_".$id.".jpg";
  916. $codeUrl = set_http_type(rtrim($siteUrl, '/') .'/offlinepay/index.html?id=' . $id, request()->isSsl() ? 0 : 1);//二维码链接
  917. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
  918. if (!is_string($imageInfo)){
  919. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  920. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  921. $attachmentRepository->create(systemConfig('upload_type') ?: 1, 0, 0, [
  922. 'attachment_category_id' => 0,
  923. 'attachment_name' => $imageInfo['name'],
  924. 'attachment_src' => $imageInfo['dir']
  925. ]);
  926. $show_src = $merchantIntertion -> show_src($imageInfo['dir'],$id);
  927. $codeInsert = [
  928. 'uid'=>$mer -> uid,
  929. 'mer_id' =>$mer -> mer_id,
  930. 'code_id'=>$id,
  931. 'qrcode_src' => $imageInfo['dir'],
  932. 'show_src' => $show_src,
  933. ];
  934. Db::name('MerchantQrcode') -> insert($codeInsert);
  935. return ['url'=>$imageInfo['dir'],'show_src'=>$show_src];
  936. }
  937. throw new ValidateException('收款码生成失败');
  938. }
  939. return $res;
  940. }
  941. /**
  942. * 根据 商户ID 获取 未删除的 商户信息
  943. * @param int $merchantId
  944. * @return MerchantEntity
  945. */
  946. public function getMerchantEntityByMerchantId(int $merchantId): MerchantEntity
  947. {
  948. $entityList = $this->getMerchantEntityListByMerchantIdList([$merchantId]);
  949. $entity = array_shift($entityList);
  950. if ($entity instanceof MerchantEntity) {
  951. return $entity;
  952. } else {
  953. /** @var MerchantEntity */
  954. return MerchantEntity::newInstance();
  955. }
  956. }
  957. /**
  958. * @param array $idList
  959. * @return MerchantEntity[]
  960. */
  961. public function getMerchantEntityListByMerchantIdList(array $idList): array
  962. {
  963. return $this->dao->getMerchantEntityListByMerchantIdList($idList);
  964. }
  965. }