MerchantRepository.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. // 共富配置---获取最大推荐奖
  478. $sharedProsperityRecommendConfigEntityByMaxRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxRewardRatio();
  479. // 共富配置--获取最大的分享奖比例
  480. $sharedProsperityRecommendConfigEntityByMaxShareRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxShareRatio();
  481. // 利润 减去 顶格的直推奖,剩下的是PV值
  482. $sharPveRate = bcadd($sharedProsperityRecommendConfigEntityByMaxRewardRatio->getRewardRatio(),$sharedProsperityRecommendConfigEntityByMaxShareRewardRatio->getShareRatio(), CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
  483. $pvProportion = bcsub('1', bcdiv($sharPveRate, '100', 4), 2);
  484. // 获取利润
  485. $productSku = Db::name('store_product_attr_value')->where('product_id', $v['product_id'])->order('price asc')->find();
  486. // 计算pv
  487. $pv = bcmul($productSku['plate_mer_profit'], $pvProportion, CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
  488. $v['pv'] = $pv;
  489. }
  490. if ($v['pension_is'] != 0) {
  491. $v['yanglao'] = $v['pension'];
  492. }
  493. // $v=($v,$k);
  494. // array_push($v,$k);
  495. $arr[]=$v;
  496. }
  497. $list["merId"]=$merId;
  498. $list["list"]=$arr;
  499. return $list;
  500. }
  501. public function productList_yhc($merId, $where, $page, $limit, $userInfo)
  502. {
  503. unset($where['order']);
  504. if (isset($where['price_on']) && $where['price_on'] != '')$where['price'] = [$where['price_asc'], $where['price_desc']];
  505. if (isset($where['brand_id']) && $where['brand_id'] != '') $where['brand_id'] = explode(',', $where['brand_id']);
  506. unset($where['price_on'], $where['price_off']);
  507. //搜索记录
  508. if ($userInfo && isset($where['keyword']) && !empty($where['keyword']))
  509. app()->make(UserVisitRepository::class)->searchProduct($userInfo['uid'], $where['keyword']);
  510. $query = Db::name('store_product')->where('product_id','>',0)->where('mer_id', $merId)->where('type', 17);
  511. $keyArray = $whereArr = [];
  512. unset($where['type']);
  513. foreach ($where as $key => $item) {
  514. if ($item !== '' && $key != 'soft') {
  515. $keyArray[] = $key;
  516. $whereArr[$key] = $item;
  517. }
  518. }
  519. unset($whereArr['order']);
  520. $query->withSearch($keyArray, $whereArr)->where('is_show',1)->where('status',1);
  521. $query->when(isset($where['keyword']) && $where['keyword'] != '', function ($query) use ($where) {
  522. $query->whereLike('store_name', "%{$where['keyword']}%");
  523. unset($where['keyword']);
  524. });
  525. $query->order('sort DESC ,create_time DESC');
  526. $query->with(['merchant'])->with(['issetCoupon']);
  527. $count = $query->count();
  528. // echo DB::getlastsql();die;
  529. $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';
  530. $list = $query->page($page, $limit)->setOption('field', [])->field($filed)->select();
  531. $ProductRepository=app()->make(ProductRepository::class);
  532. $list->each(function ($item) use ($ProductRepository) {
  533. $item['sales'] = $item['sales'] + $item['ficti'];
  534. unset($item['ficti']);
  535. $item['yanglao'] = $ProductRepository->yanglaojin($item['product_id']);
  536. return $item;
  537. });
  538. // if ($this->getUserIsPromoter($userInfo)) $list = $list->each(function ($item) {
  539. // return $item['max_extension'] = $item->max_extension;
  540. // });
  541. $list= compact('count', 'list');
  542. $arr=[];
  543. foreach ($list["list"] as $v){
  544. $v['yanglao']= app()->make(ProductRepository::class)->yanglaojin($v['product_id']);
  545. $v['special_merchant']= merchantConfig($v['mer_id'], 'special_merchant');
  546. $arr[]=$v;
  547. }
  548. $list["list"]=$arr;
  549. return $list;
  550. }
  551. /**
  552. * @Author:Qinii
  553. * @Date: 2020/5/30
  554. * @param int $id
  555. * @return mixed
  556. */
  557. public function categoryList(int $id)
  558. {
  559. return app()->make(StoreCategoryRepository::class)->getApiFormatList($id, 1);
  560. }
  561. public function offlineUserQrcode($merId, $userId,$queryString = '/h5payment/index.html', $imgName = '_store_user_offline_wap.jpg')
  562. {
  563. $siteUrl = systemConfig('site_url');
  564. $name = $merId . $userId . $imgName;
  565. $attachmentRepository = app()->make(AttachmentRepository::class);
  566. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  567. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  568. $imageInfo->delete();
  569. $imageInfo = null;
  570. }
  571. if (!$imageInfo) {
  572. $codeUrl = set_http_type(rtrim($siteUrl, '/') . $queryString.'?id=' . $merId . '&user_id=' . $userId, request()->isSsl() ? 0 : 1);//二维码链接
  573. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
  574. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  575. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  576. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  577. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -2, $merId, [
  578. 'attachment_category_id' => 0,
  579. 'attachment_name' => $imageInfo['name'],
  580. 'attachment_src' => $imageInfo['dir']
  581. ]);
  582. $urlCode = $imageInfo['dir'];
  583. } else $urlCode = $imageInfo['attachment_src'];
  584. return $urlCode;
  585. }
  586. public function wxQrcode($merId, $queryString = '/pages/store/home/index', $imgName = '_store_wap.jpg', $avatar = '')
  587. {
  588. $siteUrl = systemConfig('site_url');
  589. $name = $merId . $imgName;
  590. $attachmentRepository = app()->make(AttachmentRepository::class);
  591. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  592. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  593. $imageInfo->delete();
  594. $imageInfo = null;
  595. }
  596. if (!$imageInfo) {
  597. $codeUrl = set_http_type(rtrim($siteUrl, '/') . $queryString.'?id=' . $merId, request()->isSsl() ? 0 : 1);//二维码链接
  598. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name, $avatar);
  599. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  600. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  601. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  602. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -2, $merId, [
  603. 'attachment_category_id' => 0,
  604. 'attachment_name' => $imageInfo['name'],
  605. 'attachment_src' => $imageInfo['dir']
  606. ]);
  607. $urlCode = $imageInfo['dir'];
  608. } else $urlCode = $imageInfo['attachment_src'];
  609. return $urlCode;
  610. }
  611. public function routineQrcode($merId, $queryString = '/pages/store/home/index', $imgName = '_store_routine.jpg')
  612. {
  613. $name = $merId . $imgName;
  614. $attachmentRepository = app()->make(AttachmentRepository::class);
  615. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  616. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  617. $imageInfo->delete();
  618. $imageInfo = null;
  619. }
  620. if (!$imageInfo) {
  621. $uploadType = (int)systemConfig('upload_type') ?: 1;
  622. $routineQrcodeRepository = app()->make(RoutineQrcodeRepository::class);
  623. $res = $routineQrcodeRepository->getShareCode($merId, 'store', $queryString.'?id=' . $merId, '');
  624. if (!$res) throw new ValidateException('二维码生成失败');
  625. $upload = UploadService::create($uploadType);
  626. $uploadRes = $upload->to('routine/spread/code')->validate()->stream($res['res'], $name);
  627. if ($uploadRes === false) {
  628. throw new ValidateException($upload->getError());
  629. }
  630. $imageInfo = $upload->getUploadInfo();
  631. $imageInfo['image_type'] = $uploadType;
  632. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  633. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  634. $attachmentRepository->create($uploadType, -2, $merId, [
  635. 'attachment_category_id' => 0,
  636. 'attachment_name' => $imageInfo['name'],
  637. 'attachment_src' => $imageInfo['dir']
  638. ]);
  639. $routineQrcodeRepository->setRoutineQrcodeFind($res['id'], ['status' => 1, 'url_time' => date('Y-m-d H:i:s'), 'qrcode_url' => $imageInfo['dir']]);
  640. $urlCode = $imageInfo['dir'];
  641. } else $urlCode = $imageInfo['attachment_src'];
  642. return $urlCode;
  643. }
  644. public function copyForm(int $id)
  645. {
  646. $form = Elm::createForm(Route::buildUrl('systemMerchantChangeCopy', ['id' => $id])->build());
  647. $form->setRule([
  648. Elm::radio('type', '修改类型', 1)
  649. ->setOptions([
  650. ['value' => 1, 'label' => '增加'],
  651. ['value' => 2, 'label' => '减少'],
  652. ]),
  653. Elm::number('num', '修改数量', $this->dao->getCopyNum($id))->required()
  654. ]);
  655. return $form->setTitle('修改复制商品次数');
  656. }
  657. /**
  658. * @Author:Qinii
  659. * @Date: 2020/10/10
  660. * @param $where
  661. * @param $page
  662. * @param $limit
  663. * @return array
  664. */
  665. public function getLists($data, $page, $limit, $type=1,$where=[])
  666. {
  667. $where['status'] = 1;
  668. $where['mer_state'] = 1;
  669. $field = 'ACOS(SIN(('.$data["lat"].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$data["lat"].' * 3.1415) / 180 )
  670. * COS((lat * 3.1415) / 180 ) *COS(('.$data["lng"].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance';
  671. $fields =$field.',mer_id,mer_name,mark,mer_avatar,status,create_time,category_id,district_addr,care_count,renqizhi,sales';
  672. if (!empty($data["city_name"])){
  673. $city_id=Db::name("user_city")->where("city_name",$data["city_name"])->value("city_id");
  674. $where['city_id'] = $city_id;
  675. }
  676. if ($type==1) {
  677. if ( empty($where['category_id'])){
  678. $order = "mer_id desc";
  679. }else{
  680. $where['is_best'] = 1;
  681. $order = "mer_id desc,distance asc";
  682. }
  683. }else if($type==2){
  684. if ($data["order"]==1){
  685. $order = "distance asc";
  686. }else{
  687. $order = ['care_count'=>'desc'];
  688. }
  689. }
  690. $query = $this->dao->search($where);
  691. $count = $query->count($this->dao->getPk());
  692. $list =Db::name("merchant")
  693. ->where($where)
  694. ->page($page, $limit)
  695. ->field($fields)
  696. // ->having('distance <= '.'10000')
  697. ->order($order)
  698. ->select()
  699. ->each(function ($item) {
  700. $item['label'] ="人气";
  701. // $item['sales'] =$item["renqizhi"];
  702. $item['distance'] =sprintf("%.2f",$item['distance']);
  703. $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
  704. // var_dump(merchantConfig($item['mer_id'], 'printing_client_id'));exit();
  705. // $yanglao=merchantConfig($item['mer_id'], 'printing_client_id')/100;
  706. $base_commission=merchantConfig($item['mer_id'], 'base_commission');
  707. if($base_commission <= 0){
  708. $base_commission= systemConfig("extension_one_rate");
  709. }
  710. //商户养老金比例
  711. $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
  712. if(!$yanglao){
  713. //若商户养老金比例不存在 则使用平台配置
  714. $yanglao = systemConfig('yanglaojin_admin');
  715. }
  716. $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
  717. return $item;
  718. })->toArray();
  719. $counts=count($list);
  720. if( $counts<10 && $type==1){
  721. $ids=[];
  722. foreach($list as $v){
  723. $ids[]=$v["mer_id"];
  724. }
  725. $city_id=$where["city_id"];
  726. unset($where["city_id"]);
  727. $lists =Db::name("merchant")
  728. ->where($where)
  729. ->where("city_id","<>",$city_id)
  730. ->where("mer_id","<>",implode(",",$ids))
  731. ->page(1, 10-$counts)
  732. ->field($fields)
  733. ->order("distance asc")
  734. ->select()
  735. ->each(function ($item) {
  736. $item['label'] ="人气";
  737. // $item['sales'] =$item["renqizhi"];
  738. $item['distance'] =sprintf("%.2f",$item['distance']);
  739. $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
  740. $base_commission=merchantConfig($item['mer_id'], 'base_commission');
  741. if($base_commission <= 0){
  742. $base_commission= systemConfig("extension_one_rate");
  743. }
  744. //商户养老金比例
  745. $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
  746. if(!$yanglao){
  747. //若商户养老金比例不存在 则使用平台配置
  748. $yanglao = systemConfig('yanglaojin_admin');
  749. }
  750. $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
  751. return $item;
  752. })->toArray();
  753. $list=array_merge($list,$lists);
  754. }
  755. return compact('count', 'list','where');
  756. }
  757. /**
  758. * @Date: 2020/10/31
  759. * @param $where
  760. * @param $page
  761. * @param $limit
  762. * @return array
  763. * @author cabbage
  764. */
  765. public function getLst($data, $page, $limit,$where=[])
  766. {
  767. //下过单的店铺
  768. $mer_ids="";
  769. if (!empty($data["user_id"])){
  770. $mer_ids=Db::name('store_order')->where("uid",$data["user_id"])->order("order_id desc")->column("mer_id");
  771. if ($mer_ids){
  772. $mer_ids=array_unique($mer_ids);
  773. }
  774. }
  775. $where['status'] = 1;
  776. $where['mer_state'] = 1;
  777. $where['sxy_submerchant_id'] = 1;
  778. $field = '';
  779. if(!empty($data['lat']) && !empty($data['lng'])){
  780. $field = 'ACOS(SIN(('.$data["lat"].' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$data["lat"].' * 3.1415) / 180 )
  781. * COS((lat * 3.1415) / 180 ) *COS(('.$data["lng"].' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 as distance,';
  782. }else{
  783. $field = "mer_id as distance";
  784. }
  785. $fields =$field.'mer_id,mer_name,mark,mer_avatar,sales,status,create_time,category_id,care_count,sales,district_addr,renqizhi';
  786. if ($mer_ids){
  787. $order = [
  788. "FIELD (id,{$mer_ids})"=>'desc',
  789. 'sales'=>'desc', //销量
  790. 'care_count'=>'desc', //关注
  791. 'distance'=>"asc"//距离
  792. ];
  793. }else{
  794. $order = [
  795. 'distance'=>"asc",//距离
  796. 'sales'=>'desc', //销量
  797. 'care_count'=>'desc', //关注
  798. ];
  799. }
  800. if($data["order"]==1){
  801. $order = [
  802. 'distance'=>"asc",//距离
  803. 'sales'=>'asc',
  804. 'care_count'=>'asc',
  805. ];
  806. }
  807. $data['distance'] = ($data['distance']&&$data['distance']!=50)?$data['distance']:8000;
  808. $query = $this->dao->search_mer($where);
  809. $count = $query->count($this->dao->getPk());
  810. $list = $query
  811. ->page($page, $limit)
  812. ->setOption('field', [])
  813. ->field($fields)
  814. ->having('distance <= '.$data['distance'])
  815. ->order($order)
  816. ->select()
  817. ->each(function ($item) {
  818. $item['popularity'] =$item["renqizhi"];
  819. $item['sales'] =$item["sales"];
  820. $item['distance'] =sprintf("%.2f",$item['distance']);
  821. if ( $item['distance']<=10){
  822. $item['label'] ="附近";
  823. }else{
  824. $item['label'] ="附近";
  825. }
  826. $item['classify'] =Db::name('merchant_category')->where("merchant_category_id",$item["category_id"])->value("category_name");
  827. $base_commission=merchantConfig($item['mer_id'], 'base_commission');
  828. if($base_commission <= 0){
  829. $base_commission= systemConfig("extension_one_rate");
  830. }
  831. //商户养老金比例
  832. $yanglao= floatval(merchantConfig($item['mer_id'], 'yanglaojin'));
  833. if(!$yanglao){
  834. //若商户养老金比例不存在 则使用平台配置
  835. $yanglao = systemConfig('yanglaojin_admin');
  836. }
  837. $item['yanglao'] = bcmul($base_commission, $yanglao ,2) * 0.01;
  838. return $item;
  839. });
  840. return compact('count', 'list','order','where');
  841. }
  842. /**
  843. *
  844. * @param $page
  845. * @param $limit
  846. * @return array
  847. */
  848. public function merchantcategory()
  849. {
  850. return Db::name('merchant_category')->where("status",1)->order("order_sort desc,merchant_category_id desc")->select()->toArray();
  851. }
  852. /*商家分类列表*/
  853. public function mercat($page, $limit)
  854. {
  855. $count= Db::name('merchant_category')->count();
  856. $list= Db::name('merchant_category')->where("status",1)->order("order_sort desc,merchant_category_id desc")->select()->toArray();
  857. return compact('count', 'list');
  858. }
  859. /**
  860. * @param $id
  861. * @return Form
  862. * @throws FormBuilderException
  863. * @author xaboy
  864. * @day 2020-05-07
  865. */
  866. public function changeProForm($id)
  867. {
  868. return Elm::createForm(Route::buildUrl('systemMerchantChangePro', compact('id'))->build(), [
  869. Elm::input('spread_account', '推荐人')->required()->value("请填写推荐人手机号")
  870. ])->setTitle('修改商户推荐人');
  871. }
  872. /*
  873. * 修改商户推广人id
  874. *@author cabbage
  875. *@date 2020-10-31
  876. * */
  877. public function update_spread($id,$spread_account){
  878. //推荐人信息
  879. $spread = Db::name("user")->where('account',$spread_account)->value("uid");
  880. $mer_uid = Db::name("merchant")->where(['mer_id'=>$id])->value("uid");
  881. if($spread && $mer_uid){
  882. try{
  883. Db::name("user")->where(["uid"=>$mer_uid])->update(['spread_uid'=>$spread]);
  884. Db::name("merchant")->where(["mer_id"=>$id])->update(['recommender'=>$spread]);
  885. return true;
  886. }catch (Exception $e) {
  887. Db::rollback();
  888. }
  889. }else{
  890. return false;
  891. }
  892. }
  893. /*下架商品*/
  894. public function MerUpdate($where,$data)
  895. {
  896. return Db::name("store_product")->where($where)->update($data);
  897. }
  898. /*推荐商品*/
  899. public function getProductGoodList($id){
  900. $where['is_gift_bag'] = 0;
  901. $where['is_used'] = 1;
  902. $where['product_type'] = 0;
  903. $where['mer_id'] = $id;
  904. $where['is_good'] = 1;
  905. return Db::name("store_product")->where($where)->field("image,product_id,store_name as title,price,ot_price")->select();
  906. }
  907. /*收款二维码*/
  908. public function getQrCode($mer){
  909. $res = Db::name("MerchantQrcode")
  910. -> where("mer_id",$mer -> mer_id)
  911. -> field("qrcode_src as url,show_src")
  912. -> find();
  913. if(!$res || $res['url'] == '' || $res['show_src'] == ''){
  914. Db::name("MerchantQrcode") -> where("mer_id",$mer -> mer_id) -> delete();
  915. $attachmentRepository = app()->make(AttachmentRepository::class);
  916. $siteUrl = systemConfig('site_url');
  917. $merchantIntertion = app() -> make(MerchantIntention::class);
  918. $id = $merchantIntertion -> getNewQrcodeId();
  919. $name = "offlinepay_".$id.".jpg";
  920. $codeUrl = set_http_type(rtrim($siteUrl, '/') .'/offlinepay/index.html?id=' . $id, request()->isSsl() ? 0 : 1);//二维码链接
  921. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
  922. if (!is_string($imageInfo)){
  923. $imageInfo['dir'] = path_to_url($imageInfo['dir']);
  924. if (strpos($imageInfo['dir'], 'http') === false) $imageInfo['dir'] = request()->domain() . $imageInfo['dir'];
  925. $attachmentRepository->create(systemConfig('upload_type') ?: 1, 0, 0, [
  926. 'attachment_category_id' => 0,
  927. 'attachment_name' => $imageInfo['name'],
  928. 'attachment_src' => $imageInfo['dir']
  929. ]);
  930. $show_src = $merchantIntertion -> show_src($imageInfo['dir'],$id);
  931. $codeInsert = [
  932. 'uid'=>$mer -> uid,
  933. 'mer_id' =>$mer -> mer_id,
  934. 'code_id'=>$id,
  935. 'qrcode_src' => $imageInfo['dir'],
  936. 'show_src' => $show_src,
  937. ];
  938. Db::name('MerchantQrcode') -> insert($codeInsert);
  939. return ['url'=>$imageInfo['dir'],'show_src'=>$show_src];
  940. }
  941. throw new ValidateException('收款码生成失败');
  942. }
  943. return $res;
  944. }
  945. /**
  946. * 根据 商户ID 获取 未删除的 商户信息
  947. * @param int $merchantId
  948. * @return MerchantEntity
  949. */
  950. public function getMerchantEntityByMerchantId(int $merchantId): MerchantEntity
  951. {
  952. $entityList = $this->getMerchantEntityListByMerchantIdList([$merchantId]);
  953. $entity = array_shift($entityList);
  954. if ($entity instanceof MerchantEntity) {
  955. return $entity;
  956. } else {
  957. /** @var MerchantEntity */
  958. return MerchantEntity::newInstance();
  959. }
  960. }
  961. /**
  962. * @param array $idList
  963. * @return MerchantEntity[]
  964. */
  965. public function getMerchantEntityListByMerchantIdList(array $idList): array
  966. {
  967. return $this->dao->getMerchantEntityListByMerchantIdList($idList);
  968. }
  969. }