StoreBargainServices.php 43 KB

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