ShopGoods.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\store\model;
  4. use app\common\model\ShopGoods as ShopGoodsModel;
  5. use app\common\enum\goods\Status as GoodsStatusEnum;
  6. use app\common\exception\BaseException;
  7. use app\common\library\helper;
  8. use think\facade\Db;
  9. /**
  10. * 门店商品模型
  11. * Class ShopGoods
  12. * @package app\store\model
  13. */
  14. class ShopGoods extends ShopGoodsModel
  15. {
  16. /**
  17. * 获取商品列表
  18. * @param array $param 查询条件
  19. * @param int $listRows 分页数量
  20. * @return mixed
  21. * @throws \think\db\exception\DbException
  22. */
  23. public function getList(array $param = [], int $listRows = 15)
  24. {
  25. // 筛选条件
  26. $query = $this->getQueryFilter($param);
  27. // 排序条件
  28. $sort = $this->setQuerySort($param);
  29. // 执行查询
  30. $list = $query->with(['shops', 'goods.provider', 'shopGoodsSku.goodsSku'=> function($query){
  31. $query->field("*,IF(stock_num<alarm_stock_num,0,1) as stock_status");
  32. }])
  33. ->alias($this->name)
  34. ->field("{$this->name}.*")
  35. ->leftJoin('goods', "goods.goods_id = {$this->name}.goods_id")
  36. ->where('goods.is_delete', '=', 0)
  37. ->order($sort)
  38. ->paginate($listRows)
  39. ->each(function($item) {
  40. // 商品SKU库存预警状态 0-预警 1-正常
  41. $stockStatusArr = helper::getArrayColumn($item['shopGoodsSku'], 'stock_status');
  42. $item['stock_status'] = in_array(0, $stockStatusArr) ? 0 : 1;
  43. });
  44. return $list;
  45. }
  46. /**
  47. * 检索排序条件
  48. * @param array $param
  49. * @return array|string[]
  50. */
  51. private function setQuerySort(array $param = [])
  52. {
  53. $params = $this->setQueryDefaultValue($param, [
  54. 'sortField' => '', // 排序类型 默认空:按创建时间倒序 库存-stock_total
  55. 'sortOrder' => 'descend', // 排序方式 (descend-高到低 ascend-低到高)
  56. ]);
  57. // 排序规则
  58. $sort = [];
  59. if ($params['sortField'] === 'stock_total') {
  60. $sort = $params['sortOrder'] == 'descend' ? ['stock_total' => 'desc'] : ['stock_total' => 'asc'];
  61. } else {
  62. $sort = ['create_time' => 'desc'];
  63. }
  64. return array_merge($sort, [$this->getPk() => 'desc']);
  65. }
  66. /**
  67. * 检索查询条件
  68. * @param array $param
  69. * @return \think\db\BaseQuery
  70. */
  71. private function getQueryFilter(array $param)
  72. {
  73. // 商品列表获取条件
  74. $params = $this->setQueryDefaultValue($param, [
  75. 'goods_no' => '', // 商品编码
  76. 'status' => -1, // 商品状态 10-上架 20-下架
  77. 'stock_status' => -1, // 库存状态 0-预警 1-正常
  78. 'shop_id' => 0, // 门店id 0-全部
  79. ]);
  80. // 实例化新查询对象
  81. $query = $this->getNewQuery();
  82. // 筛选条件
  83. $filter = [];
  84. // 起止时间
  85. if (!empty($params['betweenTime'])) {
  86. if (isset($params['betweenTime'][0]) && $params['betweenTime'][0] && isset($params['betweenTime'][1]) && $params['betweenTime'][1]) {
  87. $times = between_date($params['betweenTime']);
  88. $filter[] = ['shop_goods.update_time', 'between', [$times['start_date'], $times['end_date']]];
  89. }
  90. }
  91. if (isset($params['stock_status']) && $params['stock_status'] != -1) { // 库存预警
  92. $filter[] = ['goods.status', '=', GoodsStatusEnum::ON_SALE]; // 出售中
  93. $filterSku[] = ['stock_num', 'exp', Db::raw('< `alarm_stock_num`')];
  94. $shopGoodsIds = ShopGoodsSku::where($filterSku)->column('shop_goods_id');
  95. if ($params['stock_status'] == 1) {
  96. if (!empty($shopGoodsIds)) {
  97. $filter[] = ['shop_goods.id', 'not in', $shopGoodsIds];
  98. }
  99. } else {
  100. $filter[] = ['shop_goods.id', 'in', $shopGoodsIds];
  101. }
  102. }
  103. // 商品状态
  104. $params['status'] > 0 && $filter[] = ['goods.status', '=', (int)$params['status']];
  105. // 门店id
  106. $params['shop_id'] > 0 && $filter[] = ['shop_goods.shop_id', '=', (int)$params['shop_id']];
  107. // 商品编码
  108. !empty($params['goods_no']) && $filter[] = ['goods.goods_no', 'like', "%{$params['goods_no']}%"];
  109. // 实例化新查询对象
  110. return $query->where($filter);
  111. }
  112. /**
  113. * 获取详情
  114. * @param int $id
  115. * @return mixed
  116. * @throws BaseException
  117. * @throws \think\db\exception\DataNotFoundException
  118. * @throws \think\db\exception\DbException
  119. * @throws \think\db\exception\ModelNotFoundException
  120. */
  121. public function getDetail(int $id)
  122. {
  123. // 关联查询
  124. $with = ['goods', 'shopGoodsSku.goodsSku'];
  125. // 获取商品记录
  126. $goodsInfo = self::with($with)->find($id);
  127. empty($goodsInfo) && throwError('很抱歉,商品信息不存在');
  128. return $goodsInfo;
  129. }
  130. /**
  131. * 添加商品
  132. * @param array $data
  133. * @return bool
  134. * @throws \think\db\exception\DataNotFoundException
  135. * @throws \think\db\exception\DbException
  136. * @throws \think\db\exception\ModelNotFoundException
  137. */
  138. public function add(array $data)
  139. {
  140. if (empty($data)) {
  141. throwError('参数无效');
  142. }
  143. // 事务处理
  144. $this->transaction(function () use ($data) {
  145. foreach ($data['goods_ids'] as $item) {
  146. $goodsInfo = Goods::get($item, ['skuList']);
  147. $shopGoods = $this->get($item);
  148. if (!empty($goodsInfo) && empty($shopGoods)) {
  149. // 添加商品
  150. $res = ShopGoods::create([
  151. 'shop_id' => $data['shop_id'],
  152. 'goods_id' => $item
  153. ]);
  154. // 新增商品sku信息
  155. $shopGoodsSku = [];
  156. foreach ($goodsInfo['skuList'] as $item) {
  157. $shopGoodsSku[] = [
  158. 'shop_id' => $res['shop_id'],
  159. 'shop_goods_id' => $res['id'],
  160. 'goods_sku_id' => $item['goods_sku_id'],
  161. 'goods_id' => $res['goods_id'],
  162. ];
  163. }
  164. (new ShopGoodsSku())->saveAll($shopGoodsSku);
  165. }
  166. }
  167. });
  168. return true;
  169. }
  170. /**
  171. * 移除商品
  172. */
  173. public function remove()
  174. {
  175. // 事务处理
  176. $this->transaction(function () {
  177. $this->delete();
  178. ShopGoodsSku::where('shop_goods_id', $this->id)->delete();
  179. // 商品门店库存减掉
  180. Goods::where('goods_id', $this->goods_id)->dec('shops_stock_total', $this->stock_total)->update();
  181. });
  182. return true;
  183. }
  184. /**
  185. * 设置门店商品库存
  186. */
  187. public function setStock(array $data)
  188. {
  189. if (empty($data['sku_stocks'])) {
  190. return false;
  191. }
  192. // 事务处理
  193. $this->transaction(function () use ($data) {
  194. // 保存门店库存数据
  195. // 先删除
  196. ShopGoodsSku::where('shop_goods_id', $this->id)->delete();
  197. // 添加
  198. $shopGoodsSku = [];
  199. foreach ($data['sku_stocks'] as $item) {
  200. $shopGoodsSku[] = [
  201. 'shop_id' => $this->shop_id,
  202. 'shop_goods_id' => $this->id,
  203. 'goods_sku_id' => $item['goods_sku_id'],
  204. 'goods_id' => $this->goods_id,
  205. 'stock_num' => $item['stock_num'],
  206. 'alarm_stock_num' => $item['alarm_stock_num'],
  207. ];
  208. }
  209. (new ShopGoodsSku())->saveAll($shopGoodsSku);
  210. $oldStockTotal = $this->stock_total;
  211. $stockTotal = helper::getArrayColumnSum($shopGoodsSku, 'stock_num');
  212. $alarmStockTotal = helper::getArrayColumnSum($shopGoodsSku, 'alarm_stock_num');
  213. // 商品门店库存变更
  214. $diff = $stockTotal - $oldStockTotal;
  215. if ($diff > 0) {
  216. // 库存增加
  217. Goods::where('goods_id', $this->goods_id)->inc('shops_stock_total', $diff)->update();
  218. } elseif ($diff < 0) {
  219. Goods::where('goods_id', $this->goods_id)->dec('shops_stock_total', -$diff)->update();
  220. }
  221. // 更新门店商品总库存数据
  222. $this->stock_total = $stockTotal;
  223. $this->alarm_stock_total = $alarmStockTotal;
  224. $this->save();
  225. });
  226. return true;
  227. }
  228. /**
  229. * 更新全部门店商品SKU
  230. * 1.增加SKU,不删除
  231. * 2.增加SKU,删除SKU
  232. * 3.不增加,删除SKU
  233. * 删除部分
  234. * 删除全部 设置为单规格
  235. */
  236. public function updateAllShopGoodsSku($goodsId, $skuList)
  237. {
  238. $newSkuIdsArr = helper::getArrayColumn($skuList, 'goods_sku_id');
  239. // 获取原有的skuList
  240. $oldSkuIdsArr = GoodsSku::where('goods_id', $goodsId)->column('goods_sku_id');
  241. // 获取新增的sku
  242. $addList = array_values(array_diff($newSkuIdsArr, $oldSkuIdsArr));
  243. // 获取删除的sku
  244. $removeList = array_values(array_diff($oldSkuIdsArr, $newSkuIdsArr));
  245. // 如果删除全部SKU,则表示是单规格
  246. if (count($addList) == 0 && count($removeList) > 0 && count($removeList) == count($oldSkuIdsArr)) {
  247. $addList = [0 => "0"];
  248. }
  249. if ($addList == $removeList) {
  250. return true;
  251. }
  252. if (empty($addList) && empty($removeList)) {
  253. return true;
  254. }
  255. if (!empty($removeList)) {
  256. // 移除商品SKU
  257. ShopGoodsSku::where('goods_id', $goodsId)->whereIn('goods_sku_id', $removeList)->delete();
  258. }
  259. $shopGoodsList = ShopGoods::where('goods_id', $goodsId)->select();
  260. $shopStockTotalAdd = 0;
  261. $shopStockTotalRemove = 0;
  262. foreach ($shopGoodsList as $item) {
  263. // 新增商品SKU
  264. $addData = [];
  265. if (!empty($addList)) {
  266. foreach ($addList as $v) {
  267. $addData[] = [
  268. 'shop_id' => $item['shop_id'],
  269. 'shop_goods_id' => $item['id'],
  270. 'goods_sku_id' => $v,
  271. 'goods_id' => $item['goods_id']
  272. ];
  273. }
  274. (new ShopGoodsSku())->saveAll($addData);
  275. }
  276. $newList = ShopGoodsSku::where('shop_goods_id', $item['id'])->select();
  277. $stockTotal = helper::getArrayColumnSum($newList, 'stock_num');
  278. $alarmStockTotal = helper::getArrayColumnSum($newList, 'alarm_stock_num');
  279. $diff = $stockTotal - $item['stock_total'];
  280. if ($diff > 0) {
  281. // 库存增加
  282. $shopStockTotalAdd += $diff;
  283. } elseif ($diff < 0) {
  284. $shopStockTotalRemove += -$diff;
  285. }
  286. // 更新门店商品总库存数据
  287. $item->stock_total = $stockTotal;
  288. $item->alarm_stock_total = $alarmStockTotal;
  289. $item->save();
  290. }
  291. // 商品门店库存变更
  292. Goods::where('goods_id', $goodsId)->inc('shops_stock_total', $shopStockTotalAdd)->update();
  293. Goods::where('goods_id', $goodsId)->dec('shops_stock_total', $shopStockTotalRemove)->update();
  294. }
  295. // 获取库存预警的商品
  296. public function getAlarmGoodsTotal()
  297. {
  298. return ShopGoodsSku::alias('sku')
  299. ->leftJoin('goods', 'goods.goods_id=sku.goods_id')
  300. ->where([
  301. ['goods.status', '=', GoodsStatusEnum::ON_SALE],
  302. ['goods.is_delete', '=', 0],
  303. ['stock_num', 'exp', Db::raw('< `alarm_stock_num`')]
  304. ])
  305. ->count();
  306. }
  307. }