StoreBargainServices.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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. declare (strict_types=1);
  12. namespace app\services\activity;
  13. use app\dao\activity\StoreBargainDao;
  14. use app\jobs\ProductLogJob;
  15. use app\Request;
  16. use app\services\BaseServices;
  17. use app\services\order\StoreOrderServices;
  18. use app\services\product\product\StoreCategoryServices;
  19. use app\services\product\product\StoreDescriptionServices;
  20. use app\services\product\product\StoreProductServices;
  21. use app\services\product\sku\StoreProductAttrResultServices;
  22. use app\services\product\sku\StoreProductAttrServices;
  23. use app\services\product\sku\StoreProductAttrValueServices;
  24. use app\services\system\attachment\SystemAttachmentServices;
  25. use app\services\user\UserServices;
  26. use app\services\wechat\WechatServices;
  27. use crmeb\exceptions\AdminException;
  28. use crmeb\services\CacheService;
  29. use crmeb\services\MiniProgramService;
  30. use crmeb\services\UploadService;
  31. use crmeb\services\UtilService;
  32. use Guzzle\Http\EntityBody;
  33. use think\exception\ValidateException;
  34. /**
  35. *
  36. * Class StoreBargainServices
  37. * @package app\services\activity
  38. * @method get(int $id, array $field) 获取一条数据
  39. * @method getBargainIdsArray(array $ids, array $field)
  40. * @method sum(array $where, string $field)
  41. * @method update(int $id, array $data)
  42. * @method addBargain(int $id, string $field)
  43. * @method value(array $where, string $field)
  44. * @method validWhere()
  45. * @method getList(array $where, int $page = 0, int $limit = 0) 获取砍价列表
  46. */
  47. class StoreBargainServices extends BaseServices
  48. {
  49. /**
  50. * StoreCombinationServices constructor.
  51. * @param StoreBargainDao $dao
  52. */
  53. public function __construct(StoreBargainDao $dao)
  54. {
  55. $this->dao = $dao;
  56. }
  57. /**
  58. * 判断砍价商品是否开启
  59. * @param int $bargainId
  60. * @return int|string
  61. */
  62. public function validBargain($bargainId = 0)
  63. {
  64. $where = [];
  65. $time = time();
  66. $where[] = ['is_del', '=', 0];
  67. $where[] = ['status', '=', 1];
  68. $where[] = ['start_time', '<', $time];
  69. $where[] = ['stop_time', '>', $time - 85400];
  70. if ($bargainId) $where[] = ['id', '=', $bargainId];
  71. return $this->dao->getCount($where);
  72. }
  73. /**
  74. * 获取后台列表
  75. * @param array $where
  76. * @return array
  77. */
  78. public function getStoreBargainList(array $where)
  79. {
  80. [$page, $limit] = $this->getPageValue();
  81. $list = $this->dao->getList($where, $page, $limit);
  82. $count = $this->dao->count($where);
  83. /** @var StoreBargainUserServices $storeBargainUserServices */
  84. $storeBargainUserServices = app()->make(StoreBargainUserServices::class);
  85. $ids = array_column($list, 'id');
  86. $countAll = $storeBargainUserServices->getAllCount([['bargain_id', 'in', $ids]]);
  87. $countSuccess = $storeBargainUserServices->getAllCount([
  88. ['status', '=', 3],
  89. ['bargain_id', 'in', $ids]
  90. ]);
  91. /** @var StoreBargainUserHelpServices $storeBargainUserHelpServices */
  92. $storeBargainUserHelpServices = app()->make(StoreBargainUserHelpServices::class);
  93. $countHelpAll = $storeBargainUserHelpServices->getHelpAllCount([['bargain_id', 'in', $ids]]);
  94. foreach ($list as &$item) {
  95. $item['count_people_all'] = $countAll[$item['id']] ?? 0;//参与人数
  96. $item['count_people_help'] = $countHelpAll[$item['id']] ?? 0;//帮忙砍价人数
  97. $item['count_people_success'] = $countSuccess[$item['id']] ?? 0;//砍价成功人数
  98. $item['stop_status'] = $item['stop_time'] < time() ? 1 : 0;
  99. if ($item['status']) {
  100. if ($item['start_time'] > time())
  101. $item['start_name'] = '未开始';
  102. else if ($item['stop_time'] < time())
  103. $item['start_name'] = '已结束';
  104. else if ($item['stop_time'] > time() && $item['start_time'] < time()) {
  105. $item['start_name'] = '进行中';
  106. }
  107. } else $item['start_name'] = '已结束';
  108. }
  109. return compact('list', 'count');
  110. }
  111. /**
  112. * 保存数据
  113. * @param int $id
  114. * @param array $data
  115. */
  116. public function saveData(int $id, array $data)
  117. {
  118. $description = $data['description'];
  119. $detail = $data['attrs'];
  120. $items = $data['items'];
  121. $data['start_time'] = strtotime($data['section_time'][0]);
  122. $data['stop_time'] = strtotime($data['section_time'][1]);
  123. $data['images'] = json_encode($data['images']);
  124. $data['stock'] = $detail[0]['stock'];
  125. $data['quota'] = $detail[0]['quota'];
  126. $data['quota_show'] = $detail[0]['quota'];
  127. $data['price'] = $detail[0]['price'];
  128. $data['min_price'] = $detail[0]['min_price'];
  129. //按照能砍掉的金额计算最大设置人数,并判断填写的砍价人数是否大于最大设置人数
  130. $bNum = bcmul(bcsub((string)$data['price'], (string)$data['min_price'], 2), '100');
  131. if ($data['people_num'] > $bNum) throw new ValidateException('砍价人数不能大于' . $bNum . '人');
  132. if ($detail[0]['min_price'] < 0 || $detail[0]['price'] <= 0 || $detail[0]['min_price'] === '' || $detail[0]['price'] === '') throw new ValidateException('金额不能小于0');
  133. if ($detail[0]['min_price'] >= $detail[0]['price']) throw new ValidateException('砍价最低价不能大于或等于起始金额');
  134. if ($detail[0]['quota'] > $detail[0]['stock']) throw new ValidateException('限量不能超过商品库存');
  135. unset($data['section_time'], $data['description'], $data['attrs'], $data['items'], $detail[0]['min_price'], $detail[0]['_index'], $detail[0]['_rowKey']);
  136. /** @var StoreDescriptionServices $storeDescriptionServices */
  137. $storeDescriptionServices = app()->make(StoreDescriptionServices::class);
  138. /** @var StoreProductAttrServices $storeProductAttrServices */
  139. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  140. /** @var StoreProductServices $storeProductServices */
  141. $storeProductServices = app()->make(StoreProductServices::class);
  142. $this->transaction(function () use ($id, $data, $description, $detail, $items, $storeDescriptionServices, $storeProductAttrServices, $storeProductServices) {
  143. if ($id) {
  144. $res = $this->dao->update($id, $data);
  145. $storeDescriptionServices->saveDescription((int)$id, $description, 2);
  146. $skuList = $storeProductServices->validateProductAttr($items, $detail, (int)$id, 2);
  147. $valueGroup = $storeProductAttrServices->saveProductAttr($skuList, (int)$id, 2);
  148. if (!$res) throw new AdminException('修改失败');
  149. } else {
  150. if (!$storeProductServices->getOne(['is_show' => 1, 'is_del' => 0, 'id' => $data['product_id']])) {
  151. throw new AdminException('原商品已下架或移入回收站');
  152. }
  153. $data['add_time'] = time();
  154. $res = $this->dao->save($data);
  155. $storeDescriptionServices->saveDescription((int)$res->id, $description, 2);
  156. $skuList = $storeProductServices->validateProductAttr($items, $detail, (int)$res->id, 2);
  157. $valueGroup = $storeProductAttrServices->saveProductAttr($skuList, (int)$res->id, 2);
  158. if (!$res) throw new AdminException('添加失败');
  159. }
  160. $res = true;
  161. foreach ($valueGroup->toArray() as $item) {
  162. $res = $res && CacheService::setStock($item['unique'], (int)$item['quota_show'], 2);
  163. }
  164. if (!$res) {
  165. throw new AdminException('占用库存失败');
  166. }
  167. });
  168. }
  169. /**
  170. * 获取砍价详情
  171. * @param int $id
  172. * @return array|\think\Model|null
  173. */
  174. public function getInfo(int $id)
  175. {
  176. $info = $this->dao->get($id);
  177. if ($info) {
  178. if ($info['start_time'])
  179. $start_time = date('Y-m-d H:i:s', $info['start_time']);
  180. if ($info['stop_time'])
  181. $stop_time = date('Y-m-d H:i:s', $info['stop_time']);
  182. if (isset($start_time) && isset($stop_time))
  183. $info['section_time'] = [$start_time, $stop_time];
  184. else
  185. $info['section_time'] = [];
  186. unset($info['start_time'], $info['stop_time']);
  187. }
  188. $info['give_integral'] = intval($info['give_integral']);
  189. $info['price'] = floatval($info['price']);
  190. $info['postage'] = floatval($info['postage']);
  191. $info['cost'] = floatval($info['cost']);
  192. $info['bargain_max_price'] = floatval($info['bargain_max_price']);
  193. $info['bargain_min_price'] = floatval($info['bargain_min_price']);
  194. $info['min_price'] = floatval($info['min_price']);
  195. $info['weight'] = floatval($info['weight']);
  196. $info['volume'] = floatval($info['volume']);
  197. /** @var StoreDescriptionServices $storeDescriptionServices */
  198. $storeDescriptionServices = app()->make(StoreDescriptionServices::class);
  199. $info['description'] = $storeDescriptionServices->getDescription(['product_id' => $id, 'type' => 2]);
  200. $info['attrs'] = $this->attrList($id, $info['product_id']);
  201. return $info;
  202. }
  203. /**
  204. * 获取规格
  205. * @param int $id
  206. * @param int $pid
  207. * @return mixed
  208. */
  209. public function attrList(int $id, int $pid)
  210. {
  211. /** @var StoreProductAttrResultServices $storeProductAttrResultServices */
  212. $storeProductAttrResultServices = app()->make(StoreProductAttrResultServices::class);
  213. $bargainResult = $storeProductAttrResultServices->value(['product_id' => $id, 'type' => 2], 'result');
  214. $items = json_decode($bargainResult, true)['attr'];
  215. $productAttr = $this->getattr($items, $pid, 0);
  216. $bargainAttr = $this->getattr($items, $id, 2);
  217. foreach ($productAttr as $pk => $pv) {
  218. foreach ($bargainAttr as &$sv) {
  219. if ($pv['detail'] == $sv['detail']) {
  220. $productAttr[$pk] = $sv;
  221. }
  222. }
  223. $productAttr[$pk]['detail'] = json_decode($productAttr[$pk]['detail']);
  224. }
  225. $attrs['items'] = $items;
  226. $attrs['value'] = $productAttr;
  227. foreach ($items as $key => $item) {
  228. $header[] = ['title' => $item['value'], 'key' => 'value' . ($key + 1), 'align' => 'center', 'minWidth' => 80];
  229. }
  230. $header[] = ['title' => '图片', 'slot' => 'pic', 'align' => 'center', 'minWidth' => 120];
  231. $header[] = ['title' => '砍价起始金额', 'slot' => 'price', 'align' => 'center', 'minWidth' => 80];
  232. $header[] = ['title' => '砍价最低价', 'slot' => 'min_price', 'align' => 'center', 'minWidth' => 80];
  233. $header[] = ['title' => '成本价', 'key' => 'cost', 'align' => 'center', 'minWidth' => 80];
  234. $header[] = ['title' => '原价', 'key' => 'ot_price', 'align' => 'center', 'minWidth' => 80];
  235. $header[] = ['title' => '库存', 'key' => 'stock', 'align' => 'center', 'minWidth' => 80];
  236. $header[] = ['title' => '限量', 'slot' => 'quota', 'align' => 'center', 'minWidth' => 80];
  237. $header[] = ['title' => '重量(KG)', 'key' => 'weight', 'align' => 'center', 'minWidth' => 80];
  238. $header[] = ['title' => '体积(m³)', 'key' => 'volume', 'align' => 'center', 'minWidth' => 80];
  239. $header[] = ['title' => '商品编号', 'key' => 'bar_code', 'align' => 'center', 'minWidth' => 80];
  240. $attrs['header'] = $header;
  241. return $attrs;
  242. }
  243. /**
  244. * 获取规格
  245. * @param $attr
  246. * @param $id
  247. * @param $type
  248. * @return array
  249. */
  250. public function getattr($attr, $id, $type)
  251. {
  252. /** @var StoreProductAttrValueServices $storeProductAttrValueServices */
  253. $storeProductAttrValueServices = app()->make(StoreProductAttrValueServices::class);
  254. $value = attr_format($attr)[1];
  255. $valueNew = [];
  256. $count = 0;
  257. if ($type == 2) {
  258. $min_price = $this->dao->value(['id' => $id], 'min_price');
  259. } else {
  260. $min_price = 0;
  261. }
  262. foreach ($value as $key => $item) {
  263. $detail = $item['detail'];
  264. // sort($item['detail'], SORT_STRING);
  265. $suk = implode(',', $item['detail']);
  266. $sukValue = $storeProductAttrValueServices->getColumn(['product_id' => $id, 'type' => $type, 'suk' => $suk], 'bar_code,cost,price,ot_price,stock,image as pic,weight,volume,brokerage,brokerage_two,quota', 'suk');
  267. if (count($sukValue)) {
  268. foreach (array_values($detail) as $k => $v) {
  269. $valueNew[$count]['value' . ($k + 1)] = $v;
  270. }
  271. $valueNew[$count]['detail'] = json_encode($detail);
  272. $valueNew[$count]['pic'] = $sukValue[$suk]['pic'] ?? '';
  273. $valueNew[$count]['price'] = $sukValue[$suk]['price'] ? floatval($sukValue[$suk]['price']) : 0;
  274. $valueNew[$count]['min_price'] = $min_price ? floatval($min_price) : 0;
  275. $valueNew[$count]['cost'] = $sukValue[$suk]['cost'] ? floatval($sukValue[$suk]['cost']) : 0;
  276. $valueNew[$count]['ot_price'] = isset($sukValue[$suk]['ot_price']) ? floatval($sukValue[$suk]['ot_price']) : 0;
  277. $valueNew[$count]['stock'] = $sukValue[$suk]['stock'] ? intval($sukValue[$suk]['stock']) : 0;
  278. $valueNew[$count]['quota'] = $sukValue[$suk]['quota'] ? intval($sukValue[$suk]['quota']) : 0;
  279. $valueNew[$count]['bar_code'] = $sukValue[$suk]['bar_code'] ?? '';
  280. $valueNew[$count]['weight'] = $sukValue[$suk]['weight'] ? floatval($sukValue[$suk]['weight']) : 0;
  281. $valueNew[$count]['volume'] = $sukValue[$suk]['volume'] ? floatval($sukValue[$suk]['volume']) : 0;
  282. $valueNew[$count]['brokerage'] = $sukValue[$suk]['brokerage'] ? floatval($sukValue[$suk]['brokerage']) : 0;
  283. $valueNew[$count]['brokerage_two'] = $sukValue[$suk]['brokerage_two'] ? floatval($sukValue[$suk]['brokerage_two']) : 0;
  284. $valueNew[$count]['opt'] = $type != 0 ? true : false;
  285. $count++;
  286. }
  287. }
  288. return $valueNew;
  289. }
  290. /**
  291. * TODO 获取砍价表ID
  292. * @param int $bargainId $bargainId 砍价商品
  293. * @param int $bargainUserUid $bargainUserUid 开启砍价用户编号
  294. * @param int $status $status 砍价状态 1参与中 2 活动结束参与失败 3活动结束参与成功
  295. * @return mixed
  296. */
  297. public function getBargainUserTableId($bargainId = 0, $bargainUserUid = 0)
  298. {
  299. return $this->dao->value(['bargain_id' => $bargainId, 'uid' => $bargainUserUid, 'is_del' => 0], 'id');
  300. }
  301. /**
  302. * TODO 获取用户可以砍掉的价格
  303. * @param $id $id 用户参与砍价表编号
  304. * @return float
  305. * @throws \think\db\exception\DataNotFoundException
  306. * @throws \think\db\exception\ModelNotFoundException
  307. * @throws \think\exception\DbException
  308. */
  309. public function getBargainUserDiffPriceFloat($id)
  310. {
  311. $price = $this->dao->get($id, ['bargain_price,bargain_price_min']);
  312. return (float)bcsub($price['bargain_price'], $price['bargain_price_min'], 2);
  313. }
  314. /**
  315. * TODO 获取用户砍掉的价格
  316. * @param int $id $id 用户参与砍价表编号
  317. * @return float
  318. */
  319. public function getBargainUserPrice($id = 0)
  320. {
  321. return (float)$this->dao->value(['id' => $id], 'price');
  322. }
  323. /**
  324. * 获取一条砍价商品
  325. * @param int $bargainId
  326. * @param string $field
  327. * @return array
  328. */
  329. public function getBargainOne($bargainId = 0, $field = 'id,product_id,title,price,min_price,image')
  330. {
  331. if (!$bargainId) return [];
  332. $bargain = $this->dao->getOne(['id' => $bargainId], $field);
  333. if ($bargain) return $bargain->toArray();
  334. else return [];
  335. }
  336. /**
  337. * 砍价列表
  338. * @return array
  339. */
  340. public function getBargainList()
  341. {
  342. /** @var StoreBargainUserServices $bargainUserService */
  343. $bargainUserService = app()->make(StoreBargainUserServices::class);
  344. [$page, $limit] = $this->getPageValue();
  345. $list = $this->dao->BargainList($page, $limit);
  346. foreach ($list as &$item) {
  347. $item['people'] = $bargainUserService->getUserIdList($item['id']);
  348. $item['price'] = floatval($item['price']);
  349. }
  350. return $list;
  351. }
  352. /**
  353. * 后台页面设计获取砍价列表
  354. * @param $where
  355. * @return array
  356. * @throws \think\db\exception\DataNotFoundException
  357. * @throws \think\db\exception\DbException
  358. * @throws \think\db\exception\ModelNotFoundException
  359. */
  360. public function getDiyBargainList($where)
  361. {
  362. $where['status'] = 1;
  363. unset($where['is_show']);
  364. [$page, $limit] = $this->getPageValue();
  365. $list = $this->dao->DiyBargainList($where, $page, $limit);
  366. $count = $this->dao->getCount($where);
  367. $cateIds = implode(',', array_column($list, 'cate_id'));
  368. /** @var StoreCategoryServices $storeCategoryServices */
  369. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  370. $cateList = $storeCategoryServices->getCateArray($cateIds);
  371. foreach ($list as &$item) {
  372. $cateName = array_filter($cateList, function ($val) use ($item) {
  373. if (in_array($val['id'], explode(',', $item['cate_id']))) {
  374. return $val;
  375. }
  376. });
  377. $item['cate_name'] = implode(',', array_column($cateName, 'cate_name'));
  378. $item['store_name'] = $item['title'];
  379. $item['price'] = floatval($item['price']);
  380. $item['is_product_type'] = 1;
  381. }
  382. return compact('count', 'list');
  383. }
  384. /**
  385. * 首页砍价商品
  386. * @param $where
  387. * @return array
  388. */
  389. public function getHomeList($where)
  390. {
  391. [$page, $limit] = $this->getPageValue();
  392. $where['is_del'] = 0;
  393. $where['is_show'] = 1;
  394. $data = [];
  395. $list = $this->dao->getHomeList($where, $page, $limit);
  396. foreach ($list as &$item) {
  397. $item['price'] = floatval($item['price']);
  398. }
  399. $data['list'] = $list;
  400. return $data;
  401. }
  402. /**获取单条砍价
  403. * @param Request $request
  404. * @param int $id
  405. * @return mixed
  406. * @throws \think\db\exception\DataNotFoundException
  407. * @throws \think\db\exception\DbException
  408. * @throws \think\db\exception\ModelNotFoundException
  409. */
  410. public function getBargain(Request $request, int $id)
  411. {
  412. $bargain = $this->dao->getOne(['id' => $id], '*', ['description']);
  413. if (!$bargain) throw new ValidateException('砍价商品不存在');
  414. $this->dao->addBargain($id, 'look');
  415. $bargain['time'] = time();
  416. if ($bargain['stop_time'] < time()) throw new ValidateException('砍价已结束');
  417. $user = $request->user();
  418. $data['userInfo']['uid'] = $user['uid'];
  419. $data['userInfo']['nickname'] = $user['nickname'];
  420. $data['userInfo']['avatar'] = $user['avatar'];
  421. /** @var StoreProductAttrServices $storeProductAttrServices */
  422. $storeProductAttrServices = app()->make(StoreProductAttrServices::class);
  423. list($productAttr, $productValue) = $storeProductAttrServices->getProductAttrDetail($id, $user->uid, 0, 2, $bargain['product_id']);
  424. foreach ($productValue as $v) {
  425. $bargain['attr'] = $v;
  426. }
  427. $data['bargain'] = get_thumb_water($bargain);
  428. $bargainNew = get_thumb_water($bargain, 'small');
  429. $data['bargain']['small_image'] = $bargainNew['image'];
  430. /** @var StoreOrderServices $orderService */
  431. $orderService = app()->make(StoreOrderServices::class);
  432. $data['bargainSumCount'] = $orderService->count(['bargain_id' => $id, 'uid' => $user['uid']]);
  433. /** @var StoreBargainUserServices $bargainUserService */
  434. $bargainUserService = app()->make(StoreBargainUserServices::class);
  435. $data['userBargainStatus'] = $bargainUserService->count(['bargain_id' => $id, 'uid' => $user->uid, 'is_del' => 0]);
  436. //用户访问事件
  437. event('user.userVisit', [$user['uid'], $id, 'bargain', $bargain['product_id'], 'view']);
  438. //浏览记录
  439. ProductLogJob::dispatch(['visit', ['uid' => $user['uid'], 'product_id' => $bargain['product_id']]]);
  440. return $data;
  441. }
  442. /**
  443. * 验证砍价是否能支付
  444. * @param int $bargainId
  445. * @param int $uid
  446. */
  447. public function checkBargainUser(int $bargainId, int $uid)
  448. {
  449. /** @var StoreBargainUserServices $bargainUserServices */
  450. $bargainUserServices = app()->make(StoreBargainUserServices::class);
  451. $bargainUserInfo = $bargainUserServices->getOne(['uid' => $uid, 'bargain_id' => $bargainId, 'status' => 1, 'is_del' => 0]);
  452. if (!$bargainUserInfo)
  453. throw new ValidateException('砍价失败');
  454. $bargainUserTableId = $bargainUserInfo['id'];
  455. if ($bargainUserInfo['bargain_price_min'] < bcsub((string)$bargainUserInfo['bargain_price'], (string)$bargainUserInfo['price'], 2)) {
  456. throw new ValidateException('砍价未成功');
  457. }
  458. if ($bargainUserInfo['status'] == 3)
  459. throw new ValidateException('砍价已支付');
  460. /** @var StoreBargainServices $bargainService */
  461. $bargainService = app()->make(StoreBargainServices::class);
  462. /** @var StoreProductAttrValueServices $attrValueServices */
  463. $attrValueServices = app()->make(StoreProductAttrValueServices::class);
  464. $res = $attrValueServices->getOne(['product_id' => $bargainId, 'type' => 2]);
  465. if (!$bargainService->validBargain($bargainId) || !$res) {
  466. throw new ValidateException('该商品已下架或删除');
  467. }
  468. $StoreBargainInfo = $bargainService->get($bargainId);
  469. if (1 > $res['quota']) {
  470. throw new ValidateException('该商品库存不足');
  471. }
  472. $product_stock = $attrValueServices->value(['product_id' => $StoreBargainInfo['product_id'], 'suk' => $res['suk'], 'type' => 0], 'stock');
  473. if ($product_stock < 1) {
  474. throw new ValidateException('该商品库存不足');
  475. }
  476. //修改砍价状态
  477. $this->setBargainUserStatus($bargainId, $uid, $bargainUserTableId);
  478. return true;
  479. }
  480. /**
  481. * 修改砍价状态
  482. * @param int $bargainId
  483. * @param int $uid
  484. * @param int $bargainUserTableId
  485. * @return bool|\crmeb\basic\BaseModel
  486. */
  487. public function setBargainUserStatus(int $bargainId, int $uid, int $bargainUserTableId)
  488. {
  489. if (!$bargainId || !$uid) return false;
  490. if (!$bargainUserTableId) return false;
  491. /** @var StoreBargainUserServices $bargainUserServices */
  492. $bargainUserServices = app()->make(StoreBargainUserServices::class);
  493. $count = $bargainUserServices->count(['id' => $bargainUserTableId, 'uid' => $uid, 'bargain_id' => $bargainId, 'status' => 1]);
  494. if (!$count) return false;
  495. $userPrice = $bargainUserServices->value(['id' => $bargainUserTableId, 'uid' => $uid, 'bargain_id' => $bargainId, 'status' => 1], 'price');
  496. $price = $bargainUserServices->get($bargainUserTableId, ['bargain_price', 'bargain_price_min']);
  497. $price = bcsub($price['bargain_price'], $price['bargain_price_min'], 2);
  498. if (bcsub($price, $userPrice, 2) > 0) {
  499. return false;
  500. }
  501. return $bargainUserServices->updateBargainStatus($bargainUserTableId);
  502. }
  503. /**
  504. * 参与砍价
  505. * @param int $uid
  506. * @param int $bargainId
  507. * @return string
  508. * @throws \think\db\exception\DataNotFoundException
  509. * @throws \think\db\exception\DbException
  510. * @throws \think\db\exception\ModelNotFoundException
  511. */
  512. public function setBargain(int $uid, int $bargainId)
  513. {
  514. if (!$bargainId) throw new ValidateException('参数错误');
  515. $bargainInfo = $this->dao->getOne([
  516. ['is_del', '=', 0],
  517. ['status', '=', 1],
  518. ['start_time', '<', time()],
  519. ['stop_time', '>', time()],
  520. ['id', '=', $bargainId],
  521. ]);
  522. if (!$bargainInfo) throw new ValidateException('砍价已结束');
  523. $bargainInfo = $bargainInfo->toArray();
  524. /** @var StoreBargainUserServices $bargainUserService */
  525. $bargainUserService = app()->make(StoreBargainUserServices::class);
  526. $count = $bargainUserService->count(['bargain_id' => $bargainId, 'uid' => $uid, 'is_del' => 0, 'status' => 1]);
  527. if ((int)sys_config('bargain_subscribe')) {
  528. /** @var WechatServices $wechat */
  529. $wechat = app()->make(WechatServices::class);
  530. $subscribe = $wechat->get(['uid' => $uid, 'subscribe' => 1]);
  531. if (!$subscribe) return 'subscribe';
  532. }
  533. if ($count === false) {
  534. throw new ValidateException('参数错误');
  535. } elseif ($count) {
  536. return 'SUCCESSFUL';
  537. } else {
  538. $count = $bargainUserService->count(['uid' => $uid, 'bargain_id' => $bargainId, 'type' => 1]);
  539. if ($count >= $bargainInfo['num']) throw new ValidateException('您不能再发起此件商品砍价');
  540. $res = $bargainUserService->setBargain($bargainId, $uid, $bargainInfo);
  541. }
  542. if (!$res) {
  543. throw new ValidateException('参与失败');
  544. } else {
  545. return 'SUCCESS';
  546. }
  547. }
  548. /**
  549. * @param Request $request
  550. * @param int $bargainId
  551. * @param int $bargainUserUid
  552. * @return string
  553. * @throws \think\Exception
  554. * @throws \think\db\exception\DataNotFoundException
  555. * @throws \think\db\exception\ModelNotFoundException
  556. */
  557. public function setHelpBargain(int $uid, int $bargainId, int $bargainUserUid)
  558. {
  559. if (!$bargainId || !$bargainUserUid) throw new ValidateException('参数错误');
  560. $bargainInfo = $this->dao->getOne([
  561. ['is_del', '=', 0],
  562. ['status', '=', 1],
  563. ['start_time', '<', time()],
  564. ['stop_time', '>', time()],
  565. ['id', '=', $bargainId],
  566. ]);
  567. if (!$bargainInfo) throw new ValidateException('砍价已结束');
  568. if ((int)sys_config('bargain_subscribe')) {
  569. /** @var WechatServices $wechat */
  570. $wechat = app()->make(WechatServices::class);
  571. $subscribe = $wechat->get(['uid' => $uid, 'subscribe' => 1]);
  572. if (!$subscribe) return 'subscribe';
  573. }
  574. /** @var StoreBargainUserHelpServices $userHelpService */
  575. $userHelpService = app()->make(StoreBargainUserHelpServices::class);
  576. /** @var StoreBargainUserServices $bargainUserService */
  577. $bargainUserService = app()->make(StoreBargainUserServices::class);
  578. $bargainUserTableId = $bargainUserService->getBargainUserTableId($bargainId, $bargainUserUid);
  579. if (!$bargainUserTableId) throw new ValidateException('该分享未开启砍价');
  580. $count = $userHelpService->isBargainUserHelpCount($bargainId, $bargainUserTableId, $uid);
  581. if (!$count) return 'SUCCESSFUL';
  582. $res = $userHelpService->setBargainUserHelp($bargainId, $bargainUserTableId, $uid);
  583. if ($res) {
  584. if (!$bargainUserService->getSurplusPrice($bargainUserTableId, 1)) {
  585. $bargainInfo = $this->dao->get($bargainId);//TODO 获取砍价商品信息
  586. $bargainUserInfo = $bargainUserService->get($bargainUserTableId);// TODO 获取用户参与砍价信息
  587. //用户发送消息
  588. event('notice.notice', [['uid' => $bargainUserUid, 'bargainInfo' => $bargainInfo, 'bargainUserInfo' => $bargainUserInfo,], 'bargain_success']);
  589. }
  590. return 'SUCCESS';
  591. } else throw new ValidateException('砍价失败');
  592. }
  593. /**
  594. * 减库存加销量
  595. * @param int $num
  596. * @param int $bargainId
  597. * @param string $unique
  598. * @return bool
  599. */
  600. public function decBargainStock(int $num, int $bargainId, string $unique)
  601. {
  602. $product_id = $this->dao->value(['id' => $bargainId], 'product_id');
  603. if ($unique) {
  604. /** @var StoreProductAttrValueServices $skuValueServices */
  605. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  606. //减去砍价商品sku的库存增加销量
  607. $res = false !== $skuValueServices->decProductAttrStock($bargainId, $unique, $num, 2);
  608. //减去砍价商品的库存和销量
  609. $res = $res && $this->dao->decStockIncSales(['id' => $bargainId, 'type' => 2], $num);
  610. //减掉普通商品sku的库存加销量
  611. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $bargainId], 'suk');
  612. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id, 'type' => 0], 'unique');
  613. if ($productUnique) {
  614. $res = $res && $skuValueServices->decProductAttrStock($product_id, $productUnique, $num);
  615. }
  616. } else {
  617. //减去砍价商品的库存和销量
  618. $res = false !== $this->dao->decStockIncSales(['id' => $bargainId, 'type' => 2], $num);
  619. }
  620. /** @var StoreProductServices $services */
  621. $services = app()->make(StoreProductServices::class);
  622. //减掉普通商品的库存加销量
  623. $res = $res && $services->decProductStock($num, $product_id);
  624. return $res;
  625. }
  626. /**
  627. * 减销量加库存
  628. * @param int $num
  629. * @param int $bargainId
  630. * @param string $unique
  631. * @return bool
  632. */
  633. public function incBargainStock(int $num, int $bargainId, string $unique)
  634. {
  635. $product_id = $this->dao->value(['id' => $bargainId], 'product_id');
  636. if ($unique) {
  637. /** @var StoreProductAttrValueServices $skuValueServices */
  638. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  639. //减去砍价商品sku的销量,增加库存和限购数量
  640. $res = false !== $skuValueServices->incProductAttrStock($bargainId, $unique, $num, 2);
  641. //减去砍价商品的销量,增加库存
  642. $res = $res && $this->dao->incStockDecSales(['id' => $bargainId, 'type' => 2], $num);
  643. //减掉普通商品sku的销量,增加库存
  644. $suk = $skuValueServices->value(['unique' => $unique, 'product_id' => $bargainId], 'suk');
  645. $productUnique = $skuValueServices->value(['suk' => $suk, 'product_id' => $product_id], 'unique');
  646. if ($productUnique) {
  647. $res = $res && $skuValueServices->incProductAttrStock($product_id, $productUnique, $num);
  648. }
  649. } else {
  650. //减去砍价商品的销量,增加库存
  651. $res = false !== $this->dao->incStockDecSales(['id' => $bargainId, 'type' => 2], $num);
  652. }
  653. /** @var StoreProductServices $services */
  654. $services = app()->make(StoreProductServices::class);
  655. //减掉普通商品的库存加销量
  656. $res = $res && $services->incProductStock($num, $product_id);
  657. return $res;
  658. }
  659. /**
  660. * @param $bargainId
  661. * @param $user
  662. * @return bool|string
  663. * @throws \think\db\exception\DataNotFoundException
  664. * @throws \think\db\exception\DbException
  665. * @throws \think\db\exception\ModelNotFoundException
  666. */
  667. public function poster($bargainId, $user, $from)
  668. {
  669. $storeBargainInfo = $this->dao->get($bargainId, ['title', 'image', 'price']);
  670. if (!$storeBargainInfo) {
  671. throw new ValidateException('砍价信息没有查到');
  672. }
  673. /** @var StoreBargainUserServices $services */
  674. $services = app()->make(StoreBargainUserServices::class);
  675. $bargainUser = $services->get(['bargain_id' => $bargainId, 'uid' => $user['uid']], ['price', 'bargain_price_min']);
  676. if (!$bargainUser) {
  677. throw new ValidateException('用户砍价信息未查到');
  678. }
  679. try {
  680. $siteUrl = sys_config('site_url');
  681. $data['title'] = $storeBargainInfo['title'];
  682. $data['image'] = $storeBargainInfo['image'];
  683. $data['price'] = bcsub($storeBargainInfo['price'], $bargainUser['price'], 2);
  684. $data['label'] = '已砍至';
  685. $price = bcsub($storeBargainInfo['price'], $bargainUser['price'], 2);
  686. $data['msg'] = '还差' . (bcsub($price, $bargainUser['bargain_price_min'], 2)) . '元即可砍价成功';
  687. /** @var SystemAttachmentServices $systemAttachmentServices */
  688. $systemAttachmentServices = app()->make(SystemAttachmentServices::class);
  689. if ($from == 'wechat') {
  690. $name = $bargainId . '_' . $user['uid'] . '_' . $user['is_promoter'] . '_bargain_share_wap.jpg';
  691. //公众号
  692. $imageInfo = $systemAttachmentServices->getInfo(['name' => $name]);
  693. if (!$imageInfo) {
  694. $codeUrl = set_http_type($siteUrl . '/pages/activity/goods_bargain_details/index?id=' . $bargainId . '&bargain=' . $user['uid'] . '&spread=' . $user['uid'], 1);//二维码链接
  695. $imageInfo = UtilService::getQRCodePath($codeUrl, $name);
  696. if (is_string($imageInfo)) {
  697. throw new ValidateException('二维码生成失败');
  698. }
  699. $systemAttachmentServices->save([
  700. 'name' => $imageInfo['name'],
  701. 'att_dir' => $imageInfo['dir'],
  702. 'satt_dir' => $imageInfo['thumb_path'],
  703. 'att_size' => $imageInfo['size'],
  704. 'att_type' => $imageInfo['type'],
  705. 'image_type' => $imageInfo['image_type'],
  706. 'module_type' => 2,
  707. 'time' => $imageInfo['time'],
  708. 'pid' => 1,
  709. 'type' => 1
  710. ]);
  711. $url = $imageInfo['dir'];
  712. } else $url = $imageInfo['att_dir'];
  713. $data['url'] = $url;
  714. if ($imageInfo['image_type'] == 1) $data['url'] = $siteUrl . $url;
  715. $posterImage = UtilService::setShareMarketingPoster($data, 'wap/activity/bargain/poster');
  716. if (!is_array($posterImage)) {
  717. throw new ValidateException('海报生成失败');
  718. }
  719. $systemAttachmentServices->save([
  720. 'name' => $posterImage['name'],
  721. 'att_dir' => $posterImage['dir'],
  722. 'satt_dir' => $posterImage['thumb_path'],
  723. 'att_size' => $posterImage['size'],
  724. 'att_type' => $posterImage['type'],
  725. 'image_type' => $posterImage['image_type'],
  726. 'module_type' => 2,
  727. 'time' => $posterImage['time'],
  728. 'pid' => 1,
  729. 'type' => 1
  730. ]);
  731. if ($posterImage['image_type'] == 1) $posterImage['dir'] = $siteUrl . $posterImage['dir'];
  732. $wapPosterImage = set_http_type($posterImage['dir'], 1);//公众号推广海报
  733. return $wapPosterImage;
  734. } else {
  735. //小程序
  736. $name = $bargainId . '_' . $user['uid'] . '_' . $user['is_promoter'] . '_bargain_share_routine.jpg';
  737. $imageInfo = $systemAttachmentServices->getInfo(['name' => $name]);
  738. if (!$imageInfo) {
  739. $valueData = 'id=' . $bargainId . '&bargain=' . $user['uid'];
  740. /** @var UserServices $userServices */
  741. $userServices = app()->make(UserServices::class);
  742. if ($userServices->checkUserPromoter((int)$user['uid'], $user)) {
  743. $valueData .= '&spread=' . $user['uid'];
  744. }
  745. $res = MiniProgramService::qrcodeService()->appCodeUnlimit($valueData, 'pages/activity/goods_bargain_details/index', 280);
  746. if (!$res) throw new ValidateException('二维码生成失败');
  747. $uploadType = (int)sys_config('upload_type', 1);
  748. $upload = UploadService::init();
  749. $res = (string)EntityBody::factory($res);
  750. $res = $upload->to('routine/activity/bargain/code')->validate()->stream($res, $name);
  751. if ($res === false) {
  752. throw new ValidateException($upload->getError());
  753. }
  754. $imageInfo = $upload->getUploadInfo();
  755. $imageInfo['image_type'] = $uploadType;
  756. if ($imageInfo['image_type'] == 1) $remoteImage = UtilService::remoteImage($siteUrl . $imageInfo['dir']);
  757. else $remoteImage = UtilService::remoteImage($imageInfo['dir']);
  758. if (!$remoteImage['status']) throw new ValidateException($remoteImage['msg']);
  759. $systemAttachmentServices->save([
  760. 'name' => $imageInfo['name'],
  761. 'att_dir' => $imageInfo['dir'],
  762. 'satt_dir' => $imageInfo['thumb_path'],
  763. 'att_size' => $imageInfo['size'],
  764. 'att_type' => $imageInfo['type'],
  765. 'image_type' => $imageInfo['image_type'],
  766. 'module_type' => 2,
  767. 'time' => time(),
  768. 'pid' => 1,
  769. 'type' => 1
  770. ]);
  771. $url = $imageInfo['dir'];
  772. } else $url = $imageInfo['att_dir'];
  773. $data['url'] = $url;
  774. if ($imageInfo['image_type'] == 1)
  775. $data['url'] = $siteUrl . $url;
  776. $posterImage = UtilService::setShareMarketingPoster($data, 'routine/activity/bargain/poster');
  777. if (!is_array($posterImage)) throw new ValidateException('海报生成失败');
  778. $systemAttachmentServices->save([
  779. 'name' => $posterImage['name'],
  780. 'att_dir' => $posterImage['dir'],
  781. 'satt_dir' => $posterImage['thumb_path'],
  782. 'att_size' => $posterImage['size'],
  783. 'att_type' => $posterImage['type'],
  784. 'image_type' => $posterImage['image_type'],
  785. 'module_type' => 2,
  786. 'time' => $posterImage['time'],
  787. 'pid' => 1,
  788. 'type' => 1
  789. ]);
  790. if ($posterImage['image_type'] == 1) $posterImage['dir'] = $siteUrl . $posterImage['dir'];
  791. $routinePosterImage = set_http_type($posterImage['dir'], 0);//小程序推广海报
  792. return $routinePosterImage;
  793. }
  794. } catch (\Exception $e) {
  795. return false;
  796. }
  797. }
  798. /**
  799. * 获取砍价海报信息
  800. * @param int $bargainId
  801. * @param $user
  802. * @throws \think\db\exception\DataNotFoundException
  803. * @throws \think\db\exception\DbException
  804. * @throws \think\db\exception\ModelNotFoundException
  805. */
  806. public function posterInfo(int $bargainId, $user)
  807. {
  808. $storeBargainInfo = $this->dao->get($bargainId, ['title', 'image', 'price']);
  809. if (!$storeBargainInfo) {
  810. throw new ValidateException('砍价信息没有查到');
  811. }
  812. /** @var StoreBargainUserServices $services */
  813. $services = app()->make(StoreBargainUserServices::class);
  814. $bargainUser = $services->get(['bargain_id' => $bargainId, 'uid' => $user['uid']], ['price', 'bargain_price_min']);
  815. if (!$bargainUser) {
  816. throw new ValidateException('用户砍价信息未查到');
  817. }
  818. $data['url'] = '';
  819. $data['title'] = $storeBargainInfo['title'];
  820. $data['image'] = $storeBargainInfo['image'];
  821. $data['price'] = bcsub($storeBargainInfo['price'], $bargainUser['price'], 2);
  822. $data['label'] = '已砍至';
  823. $price = bcsub($storeBargainInfo['price'], $bargainUser['price'], 2);
  824. $data['msg'] = '还差' . (bcsub($price, $bargainUser['bargain_price_min'], 2)) . '元即可砍价成功';
  825. //只有在小程序端,才会生成二维码
  826. if (\request()->isRoutine()) {
  827. try {
  828. /** @var SystemAttachmentServices $systemAttachmentServices */
  829. $systemAttachmentServices = app()->make(SystemAttachmentServices::class);
  830. //小程序
  831. $name = $bargainId . '_' . $user['uid'] . '_' . $user['is_promoter'] . '_bargain_share_routine.jpg';
  832. $siteUrl = sys_config('site_url');
  833. $imageInfo = $systemAttachmentServices->getInfo(['name' => $name]);
  834. if (!$imageInfo) {
  835. $valueData = 'id=' . $bargainId . '&bargain=' . $user['uid'];
  836. /** @var UserServices $userServices */
  837. $userServices = app()->make(UserServices::class);
  838. if ($userServices->checkUserPromoter((int)$user['uid'], $user)) {
  839. $valueData .= '&spread=' . $user['uid'];
  840. }
  841. $res = MiniProgramService::qrcodeService()->appCodeUnlimit($valueData, 'pages/activity/goods_bargain_details/index', 280);
  842. if (!$res) throw new ValidateException('二维码生成失败');
  843. $uploadType = (int)sys_config('upload_type', 1);
  844. $upload = UploadService::init();
  845. $res = (string)EntityBody::factory($res);
  846. $res = $upload->to('routine/activity/bargain/code')->validate()->stream($res, $name);
  847. if ($res === false) {
  848. throw new ValidateException($upload->getError());
  849. }
  850. $imageInfo = $upload->getUploadInfo();
  851. $imageInfo['image_type'] = $uploadType;
  852. if ($imageInfo['image_type'] == 1) $remoteImage = UtilService::remoteImage($siteUrl . $imageInfo['dir']);
  853. else $remoteImage = UtilService::remoteImage($imageInfo['dir']);
  854. if (!$remoteImage['status']) throw new ValidateException($remoteImage['msg']);
  855. $systemAttachmentServices->save([
  856. 'name' => $imageInfo['name'],
  857. 'att_dir' => $imageInfo['dir'],
  858. 'satt_dir' => $imageInfo['thumb_path'],
  859. 'att_size' => $imageInfo['size'],
  860. 'att_type' => $imageInfo['type'],
  861. 'image_type' => $imageInfo['image_type'],
  862. 'module_type' => 2,
  863. 'time' => time(),
  864. 'pid' => 1,
  865. 'type' => 1
  866. ]);
  867. $url = $imageInfo['dir'];
  868. } else $url = $imageInfo['att_dir'];
  869. if ($imageInfo['image_type'] == 1) {
  870. $data['url'] = $siteUrl . $url;
  871. } else {
  872. $data['url'] = $url;
  873. }
  874. } catch (\Throwable $e) {
  875. }
  876. }
  877. return $data;
  878. }
  879. /**
  880. * 验证砍价下单库存限量
  881. * @param int $uid
  882. * @param int $bargainId
  883. * @param int $cartNum
  884. * @param string $unique
  885. * @return array
  886. * @throws \think\db\exception\DataNotFoundException
  887. * @throws \think\db\exception\DbException
  888. * @throws \think\db\exception\ModelNotFoundException
  889. */
  890. public function checkBargainStock(int $uid, int $bargainId, int $cartNum = 1, string $unique = '')
  891. {
  892. if (!$this->validBargain($bargainId)) {
  893. throw new ValidateException('该商品已下架或删除');
  894. }
  895. /** @var StoreProductAttrValueServices $attrValueServices */
  896. $attrValueServices = app()->make(StoreProductAttrValueServices::class);
  897. $attrInfo = $attrValueServices->getOne(['product_id' => $bargainId, 'type' => 2]);
  898. if (!$attrInfo || $attrInfo['product_id'] != $bargainId) {
  899. throw new ValidateException('请选择有效的商品属性');
  900. }
  901. $productInfo = $this->dao->get($bargainId, ['*', 'title as store_name']);
  902. /** @var StoreBargainUserServices $bargainUserService */
  903. $bargainUserService = app()->make(StoreBargainUserServices::class);
  904. $bargainUserInfo = $bargainUserService->getOne(['uid' => $uid, 'bargain_id' => $bargainId, 'status' => 1, 'is_del' => 0]);
  905. if ($bargainUserInfo['bargain_price_min'] < bcsub((string)$bargainUserInfo['bargain_price'], (string)$bargainUserInfo['price'], 2)) {
  906. throw new ValidateException('砍价未成功');
  907. }
  908. $unique = $attrInfo['unique'];
  909. if ($cartNum > $attrInfo['quota']) {
  910. throw new ValidateException('该商品库存不足' . $cartNum);
  911. }
  912. return [$attrInfo, $unique, $productInfo, $bargainUserInfo];
  913. }
  914. }