MerchantRepository.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\repositories\system\merchant;
  12. use app\common\dao\system\merchant\MerchantDao;
  13. use app\common\model\store\product\ProductReply;
  14. use app\common\repositories\BaseRepository;
  15. use app\common\repositories\store\product\ProductCopyRepository;
  16. use app\common\repositories\store\product\ProductRepository;
  17. use app\common\repositories\store\product\SpuRepository;
  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 crmeb\services\QrcodeService;
  25. use crmeb\services\UploadService;
  26. use FormBuilder\Exception\FormBuilderException;
  27. use FormBuilder\Factory\Elm;
  28. use FormBuilder\Form;
  29. use think\db\exception\DataNotFoundException;
  30. use think\db\exception\DbException;
  31. use think\db\exception\ModelNotFoundException;
  32. use think\exception\ValidateException;
  33. use think\facade\Db;
  34. use think\facade\Route;
  35. use think\Model;
  36. /**
  37. * Class MerchantRepository
  38. * @package app\common\repositories\system\merchant
  39. * @mixin MerchantDao
  40. * @author xaboy
  41. * @day 2020-04-16
  42. */
  43. class MerchantRepository extends BaseRepository
  44. {
  45. /**
  46. * MerchantRepository constructor.
  47. * @param MerchantDao $dao
  48. */
  49. public function __construct(MerchantDao $dao)
  50. {
  51. $this->dao = $dao;
  52. }
  53. /**
  54. * @param array $where
  55. * @param $page
  56. * @param $limit
  57. * @return array
  58. * @throws DataNotFoundException
  59. * @throws DbException
  60. * @throws ModelNotFoundException
  61. * @author xaboy
  62. * @day 2020-04-16
  63. */
  64. public function lst(array $where, $page, $limit)
  65. {
  66. $query = $this->dao->search($where);
  67. $count = $query->count($this->dao->getPk());
  68. $list = $query->page($page, $limit)->setOption('field', [])->with(['admin' => function ($query) {
  69. $query->field('mer_id,account');
  70. }])
  71. ->field('sort, mer_id, mer_name, real_name, mer_phone, mer_address, mark, status, create_time,is_best,is_trader')->select();
  72. return compact('count', 'list');
  73. }
  74. public function count()
  75. {
  76. $valid = $this->dao->search(['status' => 1])->count();
  77. $invalid = $this->dao->search(['status' => 0])->count();
  78. return compact('valid', 'invalid');
  79. }
  80. /**
  81. * @param int|null $id
  82. * @param array $formData
  83. * @return Form
  84. * @throws FormBuilderException
  85. * @author xaboy
  86. * @day 2020-04-16
  87. */
  88. public function form(?int $id = null, array $formData = [])
  89. {
  90. $form = Elm::createForm(is_null($id) ? Route::buildUrl('systemMerchantCreate')->build() : Route::buildUrl('systemMerchantUpdate', ['id' => $id])->build());
  91. /** @var MerchantCategoryRepository $make */
  92. $make = app()->make(MerchantCategoryRepository::class);
  93. $config = systemConfig(['broadcast_room_type', 'broadcast_goods_type']);
  94. $rule = [
  95. Elm::input('mer_name', '商户名称')->required(),
  96. Elm::select('category_id', '商户分类')->options(function () use ($make) {
  97. $data = $make->allOptions();
  98. $options = [];
  99. foreach ($data as $value => $label) {
  100. $options[] = compact('value', 'label');
  101. }
  102. return $options;
  103. })->requiredNum(),
  104. Elm::input('mer_account', '商户账号')->required()->disabled(!is_null($id))->required(!is_null($id)),
  105. Elm::password('mer_password', '登录密码')->required()->disabled(!is_null($id))->required(!is_null($id)),
  106. Elm::input('real_name', '商户姓名'),
  107. Elm::input('mer_phone', '商户手机号')->col(12)->required(),
  108. Elm::number('commission_rate', '手续费(%)')->col(12),
  109. Elm::input('mer_keyword', '商户关键字')->col(12),
  110. Elm::input('mer_address', '商户地址'),
  111. Elm::textarea('mark', '备注'),
  112. Elm::number('sort', '排序', 0),
  113. $id ? Elm::hidden('status', 1) : Elm::switches('status', '是否开启', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  114. Elm::switches('is_bro_room', '直播间审核', $config['broadcast_room_type'] == 1 ? 0 : 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  115. Elm::switches('is_audit', '产品审核', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  116. Elm::switches('is_bro_goods', '直播间商品审核', $config['broadcast_goods_type'] == 1 ? 0 : 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  117. Elm::switches('is_best', '是否推荐')->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  118. Elm::switches('is_trader', '是否自营')->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  119. ];
  120. $form->setRule($rule);
  121. return $form->setTitle(is_null($id) ? '添加商户' : '编辑商户')->formData($formData);
  122. }
  123. /**
  124. * @param array $formData
  125. * @return Form
  126. * @throws FormBuilderException
  127. * @author xaboy
  128. * @day 2020/6/25
  129. */
  130. public function merchantForm(array $formData = [])
  131. {
  132. $form = Elm::createForm(Route::buildUrl('merchantUpdate')->build());
  133. $rule = [
  134. Elm::textarea('mer_info', '店铺简介')->required(),
  135. Elm::input('service_phone', '服务电话')->required(),
  136. Elm::frameImage('mer_banner', '店铺Banner(710*200px)', '/' . config('admin.merchant_prefix') . '/setting/uploadPicture?field=mer_banner&type=1')->modal(['modal' => false])->width('896px')->height('480px')->props(['footer' => false]),
  137. Elm::frameImage('mer_avatar', '店铺头像(120*120px)', '/' . config('admin.merchant_prefix') . '/setting/uploadPicture?field=mer_avatar&type=1')->modal(['modal' => false])->width('896px')->height('480px')->props(['footer' => false]),
  138. Elm::switches('mer_state', '是否开启', 1)->activeValue(1)->inactiveValue(0)->inactiveText('关闭')->activeText('开启')->col(12),
  139. ];
  140. $form->setRule($rule);
  141. return $form->setTitle('编辑店铺信息')->formData($formData);
  142. }
  143. /**
  144. * @param $id
  145. * @return Form
  146. * @throws FormBuilderException
  147. * @throws DataNotFoundException
  148. * @throws DbException
  149. * @throws ModelNotFoundException
  150. * @author xaboy
  151. * @day 2020-04-16
  152. */
  153. public function updateForm($id)
  154. {
  155. $data = $this->dao->get($id)->toArray();
  156. /** @var MerchantAdminRepository $make */
  157. $make = app()->make(MerchantAdminRepository::class);
  158. $data['mer_account'] = $make->merIdByAccount($id);
  159. $data['mer_password'] = '***********';
  160. return $this->form($id, $data);
  161. }
  162. /**
  163. * @param array $data
  164. * @author xaboy
  165. * @day 2020-04-17
  166. */
  167. public function createMerchant(array $data)
  168. {
  169. if ($this->fieldExists('mer_name', $data['mer_name']))
  170. throw new ValidateException('商户名已存在');
  171. if ($data['mer_phone'] && isPhone($data['mer_phone']))
  172. throw new ValidateException('请输入正确的手机号');
  173. $merchantCategoryRepository = app()->make(MerchantCategoryRepository::class);
  174. $adminRepository = app()->make(MerchantAdminRepository::class);
  175. if (!$data['category_id'] || !$merchantCategoryRepository->exists($data['category_id']))
  176. throw new ValidateException('商户分类不存在');
  177. if ($adminRepository->fieldExists('account', $data['mer_account']))
  178. throw new ValidateException('账号已存在');
  179. /** @var MerchantAdminRepository $make */
  180. $make = app()->make(MerchantAdminRepository::class);
  181. return Db::transaction(function () use ($data, $make) {
  182. $account = $data['mer_account'];
  183. $password = $data['mer_password'];
  184. unset($data['mer_account'], $data['mer_password']);
  185. $merchant = $this->dao->create($data);
  186. $make->createMerchantAccount($merchant, $account, $password);
  187. app()->make(ShippingTemplateRepository::class)->createDefault($merchant->mer_id);
  188. app()->make(ProductCopyRepository::class)->defaulCopyNum($merchant->mer_id);
  189. return $merchant;
  190. });
  191. }
  192. /**
  193. * @Author:Qinii
  194. * @Date: 2020/5/30
  195. * @param $where
  196. * @param $page
  197. * @param $limit
  198. * @return array
  199. */
  200. public function getList($where, $page, $limit, $userInfo)
  201. {
  202. $where['status'] = 1;
  203. $where['mer_state'] = 1;
  204. $where['is_del'] = 0;
  205. if (isset($where['location'])) {
  206. $data = @explode(',', (string)$where['location']);
  207. if (2 != count(array_filter($data ?: []))) {
  208. unset($where['location']);
  209. } else {
  210. $where['location'] = [
  211. 'lat' => (float)$data[0],
  212. 'long' => (float)$data[1],
  213. ];
  214. }
  215. }
  216. if ($userInfo && $where['keyword'] !== '') app()->make(UserVisitRepository::class)->searchMerchant($userInfo['uid'], $where['keyword']);
  217. $query = $this->dao->search($where)->with(['showProduct']);
  218. $count = $query->count($this->dao->getPk());
  219. $status = systemConfig('mer_location');
  220. $list = $query->page($page, $limit)->setOption('field', [])->field('care_count,is_trader,mer_id,mer_banner,mini_banner,mer_name, mark,mer_avatar,product_score,service_score,postage_score,sales,status,is_best,create_time,long,lat')->select()->each(function ($item) use ($status, $where) {
  221. $data = $item->showProduct->toArray();
  222. unset($item->showProduct);
  223. $recommend = array_slice($data, 0, 3);
  224. if ($status && $item['lat'] && $item['long'] && isset($where['location']['lat'], $where['location']['long'])) {
  225. $distance = getDistance($where['location']['lat'], $where['location']['long'], $item['lat'], $item['long']);
  226. if ($distance < 0.9) {
  227. $distance = max(bcmul($distance, 1000, 0), 1) . 'm';
  228. } else {
  229. $distance .= 'km';
  230. }
  231. $item['distance'] = $distance;
  232. }
  233. return $item['recommend'] = $recommend;
  234. });
  235. return compact('count', 'list');
  236. }
  237. /**
  238. * @Author:Qinii
  239. * @Date: 2020/5/30
  240. * @param int $id
  241. * @return array|Model|null
  242. */
  243. public function merExists(int $id)
  244. {
  245. return ($this->dao->get($id));
  246. }
  247. /**
  248. * @Author:Qinii
  249. * @Date: 2020/5/30
  250. * @param $id
  251. * @param $userInfo
  252. * @return array|Model|null
  253. */
  254. public function detail($id, $userInfo)
  255. {
  256. $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']);
  257. $merchant['care'] = false;
  258. if ($userInfo)
  259. $merchant['care'] = $this->getCareByUser($id, $userInfo->uid);
  260. return $merchant;
  261. }
  262. /**
  263. * @Author:Qinii
  264. * @Date: 2020/5/30
  265. * @param int $merId
  266. * @param int $userId
  267. * @return bool
  268. */
  269. public function getCareByUser(int $merId, int $userId)
  270. {
  271. if (app()->make(UserRelationRepository::class)->getWhere(['type' => 10, 'type_id' => $merId, 'uid' => $userId]))
  272. return true;
  273. return false;
  274. }
  275. /**
  276. * @Author:Qinii
  277. * @Date: 2020/5/30
  278. * @param $merId
  279. * @param $where
  280. * @param $page
  281. * @param $limit
  282. * @param $userInfo
  283. * @return mixed
  284. */
  285. public function productList($merId, $where, $page, $limit, $userInfo)
  286. {
  287. return app()->make(ProductRepository::class)->getApiSearch($merId, $where, $page, $limit, $userInfo);
  288. }
  289. /**
  290. * @Author:Qinii
  291. * @Date: 2020/5/30
  292. * @param int $id
  293. * @return mixed
  294. */
  295. public function categoryList(int $id)
  296. {
  297. return app()->make(StoreCategoryRepository::class)->getApiFormatList($id, 1);
  298. }
  299. public function wxQrcode($merId)
  300. {
  301. $siteUrl = systemConfig('site_url');
  302. $name = md5('mwx' . $merId . date('Ymd')) . '.jpg';
  303. $attachmentRepository = app()->make(AttachmentRepository::class);
  304. $imageInfo = $attachmentRepository->getWhere(['attachment_name' => $name]);
  305. if (isset($imageInfo['attachment_src']) && strstr($imageInfo['attachment_src'], 'http') !== false && curl_file_exist($imageInfo['attachment_src']) === false) {
  306. $imageInfo->delete();
  307. $imageInfo = null;
  308. }
  309. if (!$imageInfo) {
  310. $codeUrl = rtrim($siteUrl, '/') . '/pages/store/home/index?id=' . $merId;//二维码链接
  311. $imageInfo = app()->make(QrcodeService::class)->getQRCodePath($codeUrl, $name);
  312. if (is_string($imageInfo)) throw new ValidateException('二维码生成失败');
  313. $imageInfo['dir'] = tidy_url($imageInfo['dir'], null, $siteUrl);
  314. $attachmentRepository->create(systemConfig('upload_type') ?: 1, -2, $merId, [
  315. 'attachment_category_id' => 0,
  316. 'attachment_name' => $imageInfo['name'],
  317. 'attachment_src' => $imageInfo['dir']
  318. ]);
  319. $urlCode = $imageInfo['dir'];
  320. } else $urlCode = $imageInfo['attachment_src'];
  321. return $urlCode;
  322. }
  323. public function routineQrcode($merId)
  324. {
  325. $name = md5('smrt' . $merId . date('Ymd')) . '.jpg';
  326. return tidy_url(app()->make(QrcodeService::class)->getRoutineQrcodePath($name, 'pages/store/home/index', 'id=' . $merId), 0);
  327. }
  328. public function copyForm(int $id)
  329. {
  330. $form = Elm::createForm(Route::buildUrl('systemMerchantChangeCopy', ['id' => $id])->build());
  331. $form->setRule([
  332. Elm::input('copy_num', '复制次数', $this->dao->getCopyNum($id))->disabled(true)->readonly(true),
  333. Elm::radio('type', '修改类型', 1)
  334. ->setOptions([
  335. ['value' => 1, 'label' => '增加'],
  336. ['value' => 2, 'label' => '减少'],
  337. ]),
  338. Elm::number('num', '修改数量', 0)->required()
  339. ]);
  340. return $form->setTitle('修改复制商品次数');
  341. }
  342. public function delete($id)
  343. {
  344. Db::transaction(function () use ($id) {
  345. $this->dao->update($id, ['is_del' => 1]);
  346. app()->make(MerchantAdminRepository::class)->deleteMer($id);
  347. });
  348. }
  349. }