| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- <?php
- namespace addons\CloudStock\common\services;
- use addons\CloudStock\common\models\CloudStockAgentGoods;
- use common\enums\StatusEnum;
- use common\models\goods\Goods;
- use common\models\goods\GoodsAttr;
- class CloudStockAgentGoodsService extends BaseService
- {
- /**
- * 检查代理商品是否存在
- *
- * @param int $goodsId
- *
- * @return bool
- */
- public function goodsExist(int $goodsId)
- {
- return (bool)CloudStockAgentGoods::find()
- ->where([
- 'goods_id' => $goodsId,
- 'user_id' => $this->user_id,
- 'status' => StatusEnum::ENABLED,
- 'mall_id' => $this->mall_id
- ])
- ->count();
- }
- /**
- * 获取商品库存
- *
- * @param array $goodsIds
- *
- * @return array
- */
- public function getGoodsStock(array $goodsIds): array
- {
- return CloudStockAgentGoods::find()
- ->where([
- 'goods_id' => $goodsIds,
- 'user_id' => $this->user_id,
- 'status' => StatusEnum::ENABLED,
- 'mall_id' => $this->mall_id
- ])
- ->select('num')
- ->indexBy('goods_id')
- ->column();
- }
- /**
- * 验证给定商品id和数量,验证商品库存是否足够
- *
- * @param array $goodsGoodsNumList
- *
- * @return bool
- */
- public function checkGoodsStockByGoodsIds(array $goodsGoodsNumList): bool
- {
- $goodsIds = array_column($goodsGoodsNumList, 'goods_id');
- $goodsStock = $this->getGoodsStock($goodsIds);
- foreach ($goodsGoodsNumList as $item) {
- $goodsId = $item['goods_id'];
- if (!isset($goodsStock[$goodsId])) {
- $this->setError(sprintf('未查询到商品,商品ID:%d', $goodsId));
- return false;
- }
- if ($goodsStock[$goodsId] < $item['num']) {
- $this->setError(sprintf('商品ID:%d 库存不足,剩余%d件', $goodsId, $goodsStock[$goodsId]));
- return false;
- }
- }
- return true;
- }
- /**
- * @param array $goodsIds
- *
- * @return bool
- */
- public function checkGoodsDataByGoodsIds(array $goodsIds): bool
- {
- $findGoodsIds = Goods::find()
- ->where([
- 'mall_id' => $this->mall_id,
- 'status' => StatusEnum::ENABLED,
- 'id' => $goodsIds,
- 'is_on_sale' => 1,
- 'is_attr' => 0
- ])
- ->select('id')
- ->column();
- foreach ($goodsIds as $goodsId) {
- if (!in_array($goodsId, $findGoodsIds)) {
- $this->setError(sprintf('商品数据异常,商品ID:%d', $goodsId));
- return false;
- }
- }
- return true;
- }
- /**
- * 获取单规格商品的attr id
- *
- * @return void
- */
- public function getGoodsAttrMap(array $goodsIds): array
- {
- return GoodsAttr::find()
- ->where(['goods_id' => $goodsIds, 'status' => StatusEnum::ENABLED])
- ->select('id')
- ->indexBy('goods_id')
- ->column();
- }
- }
|