MerchantRepository.php 43 KB

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