123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337 |
- <?php
- declare(strict_types=1);
- namespace app\store\model;
- use app\common\model\ShopGoods as ShopGoodsModel;
- use app\common\enum\goods\Status as GoodsStatusEnum;
- use app\common\exception\BaseException;
- use app\common\library\helper;
- use think\facade\Db;
- /**
- * 门店商品模型
- * Class ShopGoods
- * @package app\store\model
- */
- class ShopGoods extends ShopGoodsModel
- {
- /**
- * 获取商品列表
- * @param array $param 查询条件
- * @param int $listRows 分页数量
- * @return mixed
- * @throws \think\db\exception\DbException
- */
- public function getList(array $param = [], int $listRows = 15)
- {
- // 筛选条件
- $query = $this->getQueryFilter($param);
- // 排序条件
- $sort = $this->setQuerySort($param);
- // 执行查询
- $list = $query->with(['shops', 'goods.provider', 'shopGoodsSku.goodsSku'=> function($query){
- $query->field("*,IF(stock_num<alarm_stock_num,0,1) as stock_status");
- }])
- ->alias($this->name)
- ->field("{$this->name}.*")
- ->leftJoin('goods', "goods.goods_id = {$this->name}.goods_id")
- ->where('goods.is_delete', '=', 0)
- ->order($sort)
- ->paginate($listRows)
- ->each(function($item) {
- // 商品SKU库存预警状态 0-预警 1-正常
- $stockStatusArr = helper::getArrayColumn($item['shopGoodsSku'], 'stock_status');
- $item['stock_status'] = in_array(0, $stockStatusArr) ? 0 : 1;
- });
- return $list;
- }
- /**
- * 检索排序条件
- * @param array $param
- * @return array|string[]
- */
- private function setQuerySort(array $param = [])
- {
- $params = $this->setQueryDefaultValue($param, [
- 'sortField' => '', // 排序类型 默认空:按创建时间倒序 库存-stock_total
- 'sortOrder' => 'descend', // 排序方式 (descend-高到低 ascend-低到高)
- ]);
- // 排序规则
- $sort = [];
- if ($params['sortField'] === 'stock_total') {
- $sort = $params['sortOrder'] == 'descend' ? ['stock_total' => 'desc'] : ['stock_total' => 'asc'];
- } else {
- $sort = ['create_time' => 'desc'];
- }
- return array_merge($sort, [$this->getPk() => 'desc']);
- }
- /**
- * 检索查询条件
- * @param array $param
- * @return \think\db\BaseQuery
- */
- private function getQueryFilter(array $param)
- {
- // 商品列表获取条件
- $params = $this->setQueryDefaultValue($param, [
- 'goods_no' => '', // 商品编码
- 'status' => -1, // 商品状态 10-上架 20-下架
- 'stock_status' => -1, // 库存状态 0-预警 1-正常
- 'shop_id' => 0, // 门店id 0-全部
- ]);
- // 实例化新查询对象
- $query = $this->getNewQuery();
- // 筛选条件
- $filter = [];
- // 起止时间
- if (!empty($params['betweenTime'])) {
- if (isset($params['betweenTime'][0]) && $params['betweenTime'][0] && isset($params['betweenTime'][1]) && $params['betweenTime'][1]) {
- $times = between_date($params['betweenTime']);
- $filter[] = ['shop_goods.update_time', 'between', [$times['start_date'], $times['end_date']]];
- }
- }
- if (isset($params['stock_status']) && $params['stock_status'] != -1) { // 库存预警
- $filter[] = ['goods.status', '=', GoodsStatusEnum::ON_SALE]; // 出售中
- $filterSku[] = ['stock_num', 'exp', Db::raw('< `alarm_stock_num`')];
- $shopGoodsIds = ShopGoodsSku::where($filterSku)->column('shop_goods_id');
- if ($params['stock_status'] == 1) {
- if (!empty($shopGoodsIds)) {
- $filter[] = ['shop_goods.id', 'not in', $shopGoodsIds];
- }
- } else {
- $filter[] = ['shop_goods.id', 'in', $shopGoodsIds];
- }
- }
- // 商品状态
- $params['status'] > 0 && $filter[] = ['goods.status', '=', (int)$params['status']];
- // 门店id
- $params['shop_id'] > 0 && $filter[] = ['shop_goods.shop_id', '=', (int)$params['shop_id']];
- // 商品编码
- !empty($params['goods_no']) && $filter[] = ['goods.goods_no', 'like', "%{$params['goods_no']}%"];
- // 实例化新查询对象
- return $query->where($filter);
- }
- /**
- * 获取详情
- * @param int $id
- * @return mixed
- * @throws BaseException
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function getDetail(int $id)
- {
- // 关联查询
- $with = ['goods', 'shopGoodsSku.goodsSku'];
- // 获取商品记录
- $goodsInfo = self::with($with)->find($id);
- empty($goodsInfo) && throwError('很抱歉,商品信息不存在');
- return $goodsInfo;
- }
- /**
- * 添加商品
- * @param array $data
- * @return bool
- * @throws \think\db\exception\DataNotFoundException
- * @throws \think\db\exception\DbException
- * @throws \think\db\exception\ModelNotFoundException
- */
- public function add(array $data)
- {
- if (empty($data)) {
- throwError('参数无效');
- }
- // 事务处理
- $this->transaction(function () use ($data) {
- foreach ($data['goods_ids'] as $item) {
- $goodsInfo = Goods::get($item, ['skuList']);
- $shopGoods = $this->get($item);
- if (!empty($goodsInfo) && empty($shopGoods)) {
- // 添加商品
- $res = ShopGoods::create([
- 'shop_id' => $data['shop_id'],
- 'goods_id' => $item
- ]);
- // 新增商品sku信息
- $shopGoodsSku = [];
- foreach ($goodsInfo['skuList'] as $item) {
- $shopGoodsSku[] = [
- 'shop_id' => $res['shop_id'],
- 'shop_goods_id' => $res['id'],
- 'goods_sku_id' => $item['goods_sku_id'],
- 'goods_id' => $res['goods_id'],
- ];
- }
- (new ShopGoodsSku())->saveAll($shopGoodsSku);
- }
- }
- });
- return true;
- }
- /**
- * 移除商品
- */
- public function remove()
- {
- // 事务处理
- $this->transaction(function () {
- $this->delete();
- ShopGoodsSku::where('shop_goods_id', $this->id)->delete();
- // 商品门店库存减掉
- Goods::where('goods_id', $this->goods_id)->dec('shops_stock_total', $this->stock_total)->update();
- });
- return true;
- }
- /**
- * 设置门店商品库存
- */
- public function setStock(array $data)
- {
- if (empty($data['sku_stocks'])) {
- return false;
- }
- // 事务处理
- $this->transaction(function () use ($data) {
- // 保存门店库存数据
- // 先删除
- ShopGoodsSku::where('shop_goods_id', $this->id)->delete();
- // 添加
- $shopGoodsSku = [];
- foreach ($data['sku_stocks'] as $item) {
- $shopGoodsSku[] = [
- 'shop_id' => $this->shop_id,
- 'shop_goods_id' => $this->id,
- 'goods_sku_id' => $item['goods_sku_id'],
- 'goods_id' => $this->goods_id,
- 'stock_num' => $item['stock_num'],
- 'alarm_stock_num' => $item['alarm_stock_num'],
- ];
- }
- (new ShopGoodsSku())->saveAll($shopGoodsSku);
- $oldStockTotal = $this->stock_total;
- $stockTotal = helper::getArrayColumnSum($shopGoodsSku, 'stock_num');
- $alarmStockTotal = helper::getArrayColumnSum($shopGoodsSku, 'alarm_stock_num');
- // 商品门店库存变更
- $diff = $stockTotal - $oldStockTotal;
- if ($diff > 0) {
- // 库存增加
- Goods::where('goods_id', $this->goods_id)->inc('shops_stock_total', $diff)->update();
- } elseif ($diff < 0) {
- Goods::where('goods_id', $this->goods_id)->dec('shops_stock_total', -$diff)->update();
- }
- // 更新门店商品总库存数据
- $this->stock_total = $stockTotal;
- $this->alarm_stock_total = $alarmStockTotal;
- $this->save();
- });
- return true;
- }
- /**
- * 更新全部门店商品SKU
- * 1.增加SKU,不删除
- * 2.增加SKU,删除SKU
- * 3.不增加,删除SKU
- * 删除部分
- * 删除全部 设置为单规格
- */
- public function updateAllShopGoodsSku($goodsId, $skuList)
- {
- $newSkuIdsArr = helper::getArrayColumn($skuList, 'goods_sku_id');
- // 获取原有的skuList
- $oldSkuIdsArr = GoodsSku::where('goods_id', $goodsId)->column('goods_sku_id');
- // 获取新增的sku
- $addList = array_values(array_diff($newSkuIdsArr, $oldSkuIdsArr));
- // 获取删除的sku
- $removeList = array_values(array_diff($oldSkuIdsArr, $newSkuIdsArr));
- // 如果删除全部SKU,则表示是单规格
- if (count($addList) == 0 && count($removeList) > 0 && count($removeList) == count($oldSkuIdsArr)) {
- $addList = [0 => "0"];
- }
- if ($addList == $removeList) {
- return true;
- }
- if (empty($addList) && empty($removeList)) {
- return true;
- }
- if (!empty($removeList)) {
- // 移除商品SKU
- ShopGoodsSku::where('goods_id', $goodsId)->whereIn('goods_sku_id', $removeList)->delete();
- }
- $shopGoodsList = ShopGoods::where('goods_id', $goodsId)->select();
- $shopStockTotalAdd = 0;
- $shopStockTotalRemove = 0;
- foreach ($shopGoodsList as $item) {
-
- // 新增商品SKU
- $addData = [];
- if (!empty($addList)) {
- foreach ($addList as $v) {
- $addData[] = [
- 'shop_id' => $item['shop_id'],
- 'shop_goods_id' => $item['id'],
- 'goods_sku_id' => $v,
- 'goods_id' => $item['goods_id']
- ];
- }
- (new ShopGoodsSku())->saveAll($addData);
- }
-
- $newList = ShopGoodsSku::where('shop_goods_id', $item['id'])->select();
- $stockTotal = helper::getArrayColumnSum($newList, 'stock_num');
- $alarmStockTotal = helper::getArrayColumnSum($newList, 'alarm_stock_num');
- $diff = $stockTotal - $item['stock_total'];
- if ($diff > 0) {
- // 库存增加
- $shopStockTotalAdd += $diff;
- } elseif ($diff < 0) {
- $shopStockTotalRemove += -$diff;
- }
- // 更新门店商品总库存数据
- $item->stock_total = $stockTotal;
- $item->alarm_stock_total = $alarmStockTotal;
- $item->save();
- }
- // 商品门店库存变更
- Goods::where('goods_id', $goodsId)->inc('shops_stock_total', $shopStockTotalAdd)->update();
- Goods::where('goods_id', $goodsId)->dec('shops_stock_total', $shopStockTotalRemove)->update();
- }
- // 获取库存预警的商品
- public function getAlarmGoodsTotal()
- {
- return ShopGoodsSku::alias('sku')
- ->leftJoin('goods', 'goods.goods_id=sku.goods_id')
- ->where([
- ['goods.status', '=', GoodsStatusEnum::ON_SALE],
- ['goods.is_delete', '=', 0],
- ['stock_num', 'exp', Db::raw('< `alarm_stock_num`')]
- ])
- ->count();
- }
- }
|