| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911 |
- <?php
- namespace bizHd\goods\classes;
- use biz\shop\classes\MainClass;
- use biz\stock\classes\GoodsStockRecordClass;
- use biz\shop\classes\ShopCapitalClass;
- use biz\stat\classes\StatCgPlantClass;
- use biz\stat\classes\StatOutClass;
- use bizHd\goods\services\GoodsCategoryService;
- use bizHd\message\classes\ChatClass;
- use bizHd\order\classes\OrderClass;
- use bizHd\work\classes\WorkClass;
- use bizHd\work\classes\WorkItemClass;
- use common\components\business;
- use common\components\dict;
- use common\components\imgUtil;
- use common\components\orderSn;
- use common\components\stringUtil;
- use common\components\util;
- use Yii;
- use bizHd\base\classes\BaseClass;
- use bizHd\goods\models\GoodsCategory;
- class GoodsClass extends BaseClass
- {
- public static $baseFile = '\bizHd\goods\models\Goods';
- const LOCK_STOCK_GOODS = 'lock_stock_goods_';//修改库存锁
- public static function orderCreateGoods($data)
- {
- $name = $data['name'] ?? '';
- $salePrice = $data['unitGoodsPrice'] ?? 0;
- $sjId = $data['sjId'] ?? 0;
- $mainId = $data['mainId'] ?? 0;
- $shopId = $data['shopId'] ?? 0;
- $kindId = $data['kindId'] ?? 0;
- $kindName = $data['kindName'] ?? '';
- $flowerNum = $data['flowerNum'] ?? 0;
- $status = 0;
- $delStatus = 0;
- $catId = $data['catId'] ?? 0;
- if (empty($catId)) {
- //制作台过来的使用默认分类id
- $hasCat = CategoryClass::getByCondition(['mainId' => $mainId, 'flower' => 1, 'default' => 1], true);
- if (empty($hasCat)) {
- $catData = [
- 'mainId' => $mainId,
- 'sjId' => $sjId,
- 'shopId' => $shopId,
- 'default' => 1,
- 'flower' => 1,
- 'categoryName' => '未分类',
- 'inTurn' => 0,
- 'status' => 0,
- ];
- $hasCat = CategoryClass::add($catData, true);
- }
- $catId = $hasCat->id ?? 0;
- if (empty($catId)) {
- util::fail('没有找到分类');
- }
- }
- $catIds = [$catId];
- $cover = !empty($data['cover']) ? $data['cover'] : 'default-img.png';
- $shopImg = [$cover];
- if (isset($data['shopImg']) && is_array($data['shopImg'])) {
- $shopImg = $data['shopImg'];
- }
- $spu = $data['spu'] ?? '';
- $addGoodsData = [
- 'name' => $name,
- 'flower' => 1,
- 'property' => 0,
- 'price' => $salePrice,
- 'sjId' => $sjId,
- 'mainId' => $mainId,
- 'shopId' => $shopId,
- 'status' => $status,
- 'delStatus' => $delStatus,
- 'shopImg' => $shopImg,
- 'catIds' => $catIds,
- 'cover' => $cover,
- 'spu' => $spu,
- 'stock' => 999,
- 'priceType' => 0,
- 'kindId' => $kindId,
- 'kindName' => $kindName,
- 'flowerNum' => $flowerNum,
- ];
- $respond = self::addGoods($addGoodsData);
- $id = $respond->id ?? 0;
- $property = dict::getDict('property', 'goods');
- $num = $data['num'] ?? 0;
- $unitType = 0;
- $unitPrice = $data['unitGoodsPrice'] ?? 0;
- return [['productId' => $id, 'num' => $num, 'unitType' => $unitType, 'unitPrice' => $unitPrice, 'property' => $property]];
- }
- public static function cgPlant($data, $shop)
- {
- $goodsData = $data['goods'] ?? '';
- if (empty($goodsData)) {
- $name = $data['name'] ?? '';
- if (empty($name)) {
- util::fail('请填写名称');
- }
- $salePrice = $data['salePrice'] ?? 0;
- $sjId = $data['sjId'] ?? 0;
- $shopId = $data['shopId'] ?? 0;
- $mainId = $data['mainId'] ?? 0;
- $status = $data['status'] ?? 0;
- $kindId = $data['kindId'] ?? 0;
- $kindName = $data['kindName'] ?? '';
- $delStatus = $data['delStatus'] ?? 0;
- $num = $data['num'] ?? 0;
- $cgPrice = $data['cgPrice'] ?? 0;
- $sendCost = $data['sendCost'] ?? 0;
- $shopImg = $data['shopImg'] ?? [];
- if ($sendCost > 0) {
- $div = bcdiv($sendCost, $num, 2);
- $cgPrice = bcadd($cgPrice, $div, 2);
- }
- $cover = isset($shopImg[0]) ? $shopImg[0] : '';
- $catId = $data['catId'] ?? 0;
- if (empty($catId)) {
- $hasCat = CategoryClass::getByCondition(['mainId' => $mainId, 'flower' => 0, 'default' => 1], true);
- if (empty($hasCat)) {
- $catData = [
- 'mainId' => $mainId,
- 'sjId' => $sjId,
- 'shopId' => $shopId,
- 'default' => 1,
- 'flower' => 0,
- 'categoryName' => '未分类',
- 'inTurn' => 0,
- 'status' => 0,
- ];
- $hasCat = CategoryClass::add($catData, true);
- }
- $catId = $hasCat->id ?? 0;
- if (empty($catId)) {
- util::fail('还是没有找到分类');
- }
- }
- $catIds = [$catId];
- $addGoodsData = [
- 'name' => $name,
- 'flower' => 0,
- 'property' => 0,
- 'price' => $salePrice,
- 'sjId' => $sjId,
- 'mainId' => $mainId,
- 'shopId' => $shopId,
- 'status' => $status,
- 'delStatus' => $delStatus,
- 'shopImg' => $shopImg,
- 'catIds' => $catIds,
- 'cover' => $cover,
- 'kindId' => $kindId,
- 'kindName' => $kindName
- ];
- $respond = self::addGoods($addGoodsData);
- $goodsId = $respond->id ?? 0;
- $goodsSn = $respond->sn ?? '';
- $goodsData = json_encode([['goodsId' => $goodsId, 'num' => $num, 'price' => $cgPrice, 'salePrice' => $salePrice, 'goodsSn' => $goodsSn, 'cover' => $cover]]);
- }
- $goodsData = json_decode($goodsData, true);
- if (empty($goodsData) || !is_array($goodsData)) {
- util::fail('没有找到商品');
- }
- $ids = array_column($goodsData, 'goodsId');
- $ids = array_unique(array_filter($ids));
- if (empty($ids)) {
- util::fail('没有商品哦');
- }
- $goodsInfo = self::getByIds($ids, null, 'id');
- $orderSn = orderSn::getGoodsCgSn();
- $mainId = $data['mainId'] ?? 0;
- $sjId = $data['sjId'] ?? 0;
- $shopId = $data['shopId'] ?? 0;
- $staffName = $data['staffName'] ?? '';
- $staffId = $data['staffId'] ?? 0;
- $goodsPrice = 0;
- $totalNum = 0;
- foreach ($goodsData as $postGoods) {
- $goodsId = $postGoods['goodsId'] ?? 0;
- $goodsSn = $postGoods['goodsSn'] ?? '';
- $name = $goodsInfo[$goodsId]['name'] ?? '';
- $kindId = $goodsInfo[$goodsId]['kindId'] ?? 0;
- $kindName = $goodsInfo[$goodsId]['kindName'] ?? '';
- $cover = $postGoods['cover'] ?? '';
- $num = $postGoods['num'] ?? 0;
- $totalNum = bcadd($num, $totalNum);
- $cgPrice = $postGoods['price'] ?? 0;
- $salePrice = $postGoods['salePrice'] ?? 0;
- if (empty($salePrice)) {
- $salePrice = $goodsInfo[$goodsId]['price'] ?? 0;
- }
- $totalPrice = bcmul($cgPrice, $num, 2);
- $addCgItem = [
- 'orderSn' => $orderSn,
- 'goodsId' => $goodsId,
- 'goodsSn' => $goodsSn,
- 'name' => $name,
- 'cover' => $cover,
- 'num' => $num,
- 'price' => $cgPrice,
- 'totalPrice' => $totalPrice,
- 'salePrice' => $salePrice,
- 'mainId' => $mainId,
- 'shopId' => $shopId,
- 'sjId' => $sjId,
- 'relateName' => $staffName,
- 'kindId' => $kindId,
- 'kindName' => $kindName,
- ];
- PlantCgItemClass::addData($addCgItem);
- $goodsPrice = bcadd($totalPrice, $goodsPrice, 2);
- }
- $remark = $data['remark'] ?? '';
- $sendCost = isset($data['sendCost']) && is_numeric($data['sendCost']) ? $data['sendCost'] : 0;
- $labourCost = $data['labourCost'] ?? 0;
- $otherCost = bcadd($sendCost, $labourCost, 2);
- $prePrice = bcadd($goodsPrice, $otherCost, 2);
- $orderPrice = $prePrice;
- $orderData = [
- 'orderSn' => $orderSn,
- 'mainId' => $mainId,
- 'orderSn' => $orderSn,
- 'stockChange' => 1,
- 'sjId' => $sjId,
- 'shopId' => $shopId,
- 'sendCost' => $sendCost,
- 'goodsPrice' => $goodsPrice,
- 'prePrice' => $prePrice,
- 'orderPrice' => $orderPrice,
- 'actPrice' => $prePrice,
- 'realPrice' => $prePrice,
- 'num' => $totalNum,
- 'staffName' => $staffName,
- 'staffId' => $staffId,
- 'status' => 3,
- 'remark' => $remark,
- ];
- $return = PlantCgClass::addData($orderData);
- $id = $return->id ?? 0;
- //总支出增加
- $main = MainClass::getLockById($mainId);
- if (empty($main)) {
- util::fail('没有找到门店53');
- }
- $currentCg = bcadd($main->totalPurchase, $orderPrice, 2);
- $main->totalPurchase = $currentCg;
- $currentCgPlant = bcadd($main->totalPurchasePlant, $orderPrice, 2);
- $main->totalPurchase = $currentCgPlant;
- $currentExpend = bcadd($main->totalExpend, $orderPrice, 2);
- $main->totalExpend = $currentExpend;
- $main->save();
- //支出统计
- StatOutClass::updateOrInsert($main, $shop, $orderPrice);
- //支出流水
- $capitalType = dict::getDict('capitalType', 'hdCgPlant', 'id');
- $event = '采购盆栽绿植等';
- $capitalData = [
- 'capitalType' => $capitalType,
- 'io' => 0,
- 'relateId' => $id,
- 'totalExpend' => $currentExpend,
- 'amount' => $orderPrice,
- 'mainId' => $mainId,
- 'event' => $event,
- 'mainId' => $mainId,
- ];
- ShopCapitalClass::addCapital($capitalData);
- //采购总量统计
- $cgNum = $return->num ?? 0;
- StatCgPlantClass::replace($main, $orderPrice, $cgNum);
- return $return;
- }
- /**
- * 花束海报主图 OSS 路径:优先 shopImg 第一张(与列表展示一致),并修正 default-img 等
- */
- public static function getPosterCoverPath($goods)
- {
- $cover = '';
- $shopImg = is_object($goods) ? ($goods->shopImg ?? '') : ($goods['shopImg'] ?? '');
- if (!empty($shopImg)) {
- $arr = is_string($shopImg) ? json_decode($shopImg, true) : $shopImg;
- if (is_array($arr) && !empty($arr[0])) {
- $cover = is_string($arr[0]) ? $arr[0] : '';
- }
- }
- if ($cover === '') {
- $cover = is_object($goods) ? ($goods->cover ?? '') : ($goods['cover'] ?? '');
- }
- return imgUtil::normalizeOssObjectPath($cover);
- }
- //获取商品完整详情,包括商品的分类 ssh 2019.12.3
- public static function getGoodsInfo($id, $shop, $custom, $params)
- {
- $info = self::getById($id);
- if (empty($info)) {
- return [];
- }
- $list = self::groupGoodsBaseInfo([$info], $shop, $custom, $params);
- return current($list);
- }
- public static function getGoodsData($where, $params)
- {
- // 获取分页参数
- $page = Yii::$app->request->get('page', 1);
- $pageSize = Yii::$app->request->get('pageSize', 20);
- $flowerNum = $params['flowerNum'] ?? 0;
- // 查询某分类下有库存的商品
- $query = GoodsCategory::find()
- ->where($where)
- ->joinWith(['goods' => function ($query) use ($flowerNum) {
- $query->andWhere(['>', 'xhGoods.stock', 0]);
- if (isset($flowerNum) && $flowerNum > 0) {
- $query->andWhere(['xhGoods.flowerNum' => $flowerNum]);
- }
- }])
- ->andWhere(['xhGoodsCategory.delStatus' => 0])
- ->orderBy(['inTurn' => SORT_DESC]);
- // 获取总数
- $total = $query->count();
- // 分页查询
- $goodsList = $query->offset(($page - 1) * $pageSize)
- ->limit($pageSize)
- ->all();
- // 整理结果,只要有库存的商品
- $list = [];
- foreach ($goodsList as $goodsCategory) {
- if ($goodsCategory->goods) { // 只要有关联且有库存的商品
- $list[] = $goodsCategory->goods->attributes;
- }
- }
- if (!empty($list)) {
- $list = self::groupGoodsBaseInfo($list);
- }
- $totalPage = ceil($total / $pageSize);
- $moreData = $totalPage > $page ? 1 : 0;//是否还有更多数据
- return [
- 'list' => $list,
- 'total' => $total,
- 'page' => $page,
- 'pageSize' => $pageSize,
- 'moreData' => $moreData
- ];
- }
- //$data 可以是一维数组,也可以二维数组
- //花束的价格全部由这边输出 $custom $params 必须预留,为后面做准备
- //会返回两个参数 price 价格,涨价后的价格 priceBeforeRise 涨价前的价格,如果price==priceBeforeRise说明没有涨价
- public static function getFinalPrice($data, $shop, $custom, $params)
- {
- if (empty($data)) {
- return $data;
- }
- $mainId = $shop->mainId;
- $rise = GoodsSettingClass::getRise($mainId);
- $riseSwitch = $rise['riseSwitch'] ?? 0;
- $riseType = $rise['riseType'] ?? 0;
- $riseAmount = $rise['riseAmount'] ?? 0;
- reset($data);
- $current = current($data);
- if (is_array($current)) {
- //处理多个商品
- foreach ($data as $key => $item) {
- $item = self::modifyAndRisePrice($item, $shop, $riseSwitch, $riseType, $riseAmount, $custom, $params);
- $data[$key] = $item;
- }
- } else {
- //单个商品
- $data = self::modifyAndRisePrice($data, $shop, $riseSwitch, $riseType, $riseAmount, $custom, $params);
- }
- return $data;
- }
- //改价和涨价的处理 ssh 20250907
- public static function modifyAndRisePrice($data, $shop, $riseSwitch, $riseType, $riseAmount, $custom, $params)
- {
- $shopId = $shop->id;
- $userId = $custom['userId'] ?? 0;
- $goodsId = $data['id'] ?? 0;
- // $key = 'report_price:' . $shopId . '_' . $userId . '_' . $goodsId; // 从redis获取报价,关键词 shopId_userId_goodsId
- $key = ChatClass::getQuotedPriceKey($shopId, $userId, $goodsId);
- $reportPrice = Yii::$app->redis->executeCommand('GET', [$key]);
- if (floatval($reportPrice) > 0) {
- //只要报价,不管是有无价格类型,就从报价里取,不参与涨价
- $data['price'] = $reportPrice;
- //无价类型变成有价类型
- $data['priceType'] = 1;
- } else {
- if (isset($data['priceType']) && $data['priceType'] == 0) {
- //没有报价,无价商品不参与涨价
- } else {
- //没有报价,有价商品参与涨价
- $data = self::obeyRiseRule($data, $riseSwitch, $riseType, $riseAmount, $custom, $params);
- }
- }
- return $data;
- }
- //遵循涨价规则 ssh 20250828
- //会返回两个参数 price 价格或涨价后的价格 priceBeforeRise 涨价前的价格,如果price==priceBeforeRise说明没有涨价
- public static function obeyRiseRule($data, $riseSwitch, $riseType, $riseAmount, $custom, $params)
- {
- //注意制作单那边也会调到这个方法 $custom暂时传的是空的,搜索关键词 work_if_need_custom !!!!!!!!!!!!!!!!!!!!!
- $price = $data['price'] ?? 0;
- $priceBeforeRise = $price;
- //后台修改商品时,取原价,不需要显示涨价金额 getOriginalPrice=1 有涨价也强制取原价
- $getOriginalPrice = $params['getOriginalPrice'] ?? 0;
- if ($riseSwitch == 1 && $riseAmount > 0 && $getOriginalPrice == 0) {
- if ($riseType == 0) {
- //百分比
- $add = sprintf("%.1f", ($price * $riseAmount / 100));
- $price = bcadd($price, $add, 2);
- } else {
- //金额
- $price = bcadd($price, $riseAmount, 2);
- }
- }
- $data['price'] = $price;
- $data['priceBeforeRise'] = $priceBeforeRise;
- return $data;
- }
- public static function groupGoodsBaseInfo($list, $shop, $custom, $params)
- {
- if (empty($list)) {
- return [];
- }
- // 收集所有商品ID
- $goodsIds = array_column($list, 'id');
- // 一次性获取所有商品的分类关系
- $allGoodsCategories = GoodsCategoryClass::getGoodsHasCategoryIdsBatch($goodsIds);
- // &$val 这里的指向符号不能去掉
- foreach ($list as $key => &$val) {
- $id = $val['id'];
- //大中小图片转化
- $val = business::formatGoodsImg($val);
- //免费配送范围
- $val['freeSendDist'] = 5;
- $val['createDate'] = isset($val['createTime']) ? date("Y-m-d", strtotime($val['createTime'])) : '';
- //商品的分类
- $categoryIds = $allGoodsCategories[$id] ?? [];
- $val['categoryIdList'] = $categoryIds;
- $shortCover = $val['cover'] ?? '';
- $val['shortCover'] = $shortCover;
- $val['cover'] = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_800,w_800";
- $val['smallCover'] = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_230,w_230";
- $val['miniCover'] = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_130,w_130";
- $val['bigCover'] = imgUtil::groupImg($shortCover) . "?x-oss-process=image/resize,m_fill,h_800,w_800";
- $actualSold = $val['actualSold'] ?? 0;
- $sold = $val['sold'] ?? 0;
- $totalSold = bcadd($actualSold, $sold);
- $val['totalSold'] = $totalSold;
- $val = self::getFinalPrice($val, $shop, $custom, $params);
- $price = $val['price'] ?? 0;
- //冗余给前端使用的字段,这样花束开单前端很多东西就不再需要修改,重要,不要删除 ssh
- $val['bigCount'] = 0;
- $stock = $val['stock'] ?? 0;
- $val['bigNum'] = $stock;
- $val['smallNum'] = 0;
- $val['classId'] = 0;
- $val['bigPrice'] = $price;
- $val['smallPrice'] = $price;
- }
- //获取最终需要的价格
- return $list;
- }
- //新建商品 ssh 20220404
- public static function addGoods($data, $work = null)
- {
- $data['createTime'] = date("Y-m-d H:i:s");
- if (!empty($data['shopImg'])) {
- $data['shopImg'] = json_encode($data['shopImg']);
- }
- $data['py'] = stringUtil::py($data['name']);
- $flowerNum = $data['flowerNum'] ?? 0;
- $kindId = $data['kindId'] ?? 0;
- $kindName = $data['kindName'] ?? '';
- $sn = orderSn::getGoodsSn($data);
- $data['sn'] = $sn;
- $addStock = $data['stock'] ?? 0;
- unset($data['stock']);
- $info = self::add($data, true);
- $id = $info->id;
- $name = $info->name;
- $py = $data['py'] ?? '';
- $sjId = $data['sjId'] ?? 0;
- $mainId = $data['mainId'] ?? 0;
- $shopId = $data['shopId'] ?? 0;
- $flower = $data['flower'] ?? 0;
- $status = $data['status'] ?? 0;
- $staffName = $data['staffName'] ?? '';
- if ($addStock > 0) {
- $stockRespond = GoodsClass::addStock($id, $mainId, $addStock);
- $oldStock = $stockRespond['oldStock'] ?? 0;
- $newStock = $stockRespond['newStock'] ?? 0;
- $recordData = [];
- $recordData['sjId'] = $sjId;
- $recordData['shopId'] = $shopId;
- $recordData['mainId'] = $mainId;
- $recordData['orderSn'] = '';
- $recordData['goodsId'] = $id;
- $recordData['goodsNum'] = $addStock;
- $recordData['oldStock'] = $oldStock;
- $recordData['newStock'] = $newStock;
- $recordData['relateName'] = $staffName;
- GoodsStockRecordClass::pdGoods($recordData);
- }
- $delStatus = $data['delStatus'] ?? 0;
- $setItemNum = $data['setItemNum'] ?? 0;
- $categoryData = CategoryClass::getCategory($mainId);
- $catIds = $data['catIds'] ?? [];
- foreach ($catIds as $catId) {
- $cName = $categoryData[$catId]['categoryName'];
- $addCategory = [
- 'gId' => $id,
- 'name' => $name,
- 'cId' => $catId,
- 'cName' => $cName,
- 'sjId' => $sjId,
- 'py' => $py,
- 'mainId' => $mainId,
- 'flower' => $flower,
- 'flowerNum' => $flowerNum,
- 'sn' => $sn,
- 'status' => $status,
- 'delStatus' => $delStatus,
- 'setItemNum' => $setItemNum,
- 'kindId' => $kindId,
- 'kindName' => $kindName,
- ];
- GoodsCategoryClass::add($addCategory);
- CategoryClass::counters(['goodsNum' => 1], ['id' => $catId]);
- }
- if (!empty($work)) {
- $workSn = $work->workSn ?? '';
- $workItemList = WorkItemClass::getAllByCondition(['workSn' => $workSn], null, '*', null, true);
- if (!empty($workItemList)) {
- foreach ($workItemList as $item) {
- $itemId = $item->itemId ?? 0;
- $ptItemId = $item->ptItemId ?? 0;
- $num = $item->num ?? 0;
- $count = $item->count ?? 0;
- $ratio = $item->ratio ?? 0;
- $bigName = $item->bigName ?? '';
- $smallName = $item->smallName ?? '';
- $unitType = $item->unitType ?? 0;
- $unitName = $item->unitName ?? 0;
- $currentName = $item->name ?? '';
- $cover = $item->cover ?? '';
- $goodsItemData = [
- 'name' => $currentName,
- 'cover' => $cover,
- 'sjId' => $sjId,
- 'shopId' => $shopId,
- 'mainId' => $mainId,
- 'goodsId' => $id,
- 'itemId' => $itemId,
- 'ptItemId' => $ptItemId,
- 'num' => $num,
- 'count' => $count,
- 'ratio' => $ratio,
- 'bigName' => $bigName,
- 'smallName' => $smallName,
- 'unitType' => $unitType,
- 'unitName' => $unitName,
- ];
- GoodsItemClass::addData($goodsItemData);
- }
- }
- } else {
- $itemList = $data['itemList'] ?? '';
- $itemArr = json_decode($itemList, true);
- //新建花束有子项,采购绿植没有子项
- if (!empty($itemArr)) {
- foreach ($itemArr as $item) {
- $goodsItemData = [
- 'name' => $item['name'] ?? '',
- 'cover' => $item['cover'] ?? '',
- 'sjId' => $sjId,
- 'shopId' => $shopId,
- 'mainId' => $mainId,
- 'goodsId' => $id,
- 'itemId' => $item['id'] ?? 0,
- 'ptItemId' => $item['ptItemId'] ?? 0,
- 'num' => $item['num'] ?? 0,
- 'count' => $item['count'] ?? 0,
- 'ratio' => $item['ratio'] ?? 0,
- 'bigName' => $item['bigName'] ?? '',
- 'smallName' => $item['smallName'] ?? '',
- 'unitType' => $item['unitType'] ?? 0,
- 'unitName' => $item['unitName'] ?? '',
- ];
- GoodsItemClass::addData($goodsItemData);
- }
- }
- }
- return $info;
- }
- //更新商品
- public static function updateGoods($goods, $data, $staff)
- {
- $id = $goods['id'] ?? 0;
- $preSetItemNum = $goods['setItemNum'] ?? 0;
- $categoryIdList = !empty($data['categoryIdList']) ? $data['categoryIdList'] : [];
- unset($data['categoryIdList']);
- if (empty($categoryIdList)) {
- util::fail('没有选择分类');
- }
- $name = $data['name'] ?? '';
- $py = stringUtil::py($name);
- $flower = $data['flower'] ?? 0;
- $sjId = $data['sjId'] ?? 0;
- $mainId = $data['mainId'] ?? 0;
- $shopId = $data['shopId'] ?? 0;
- $status = $data['status'] ?? 0;
- $setItemNum = isset($data['setItemNum']) && is_numeric($data['setItemNum']) ? $data['setItemNum'] : $preSetItemNum;
- $categoryData = CategoryClass::getCategory($mainId);
- $hasCategoryIds = array_keys($categoryData);
- $diff = array_diff($categoryIdList, $hasCategoryIds);
- if (!empty($diff)) {
- util::fail('不能使用别人的分类');
- }
- //精确处理分类变更:分别处理删除、新增、修改三种情况
- $goodsHasCategoryIds = GoodsCategoryService::getGoodsHasCategoryIds($id);
- // 1. 找出需要删除的分类:原有分类中不在新分类列表中的
- $toDeleteCategoryIds = array_diff($goodsHasCategoryIds, $categoryIdList);
- if (!empty($toDeleteCategoryIds)) {
- //GoodsCategoryClass::deleteByCondition(['gId' => $id, 'cId' => ['in', $toDeleteCategoryIds]]); //不支持,改用 ActiveRecord 的 deleteAll 方法
- GoodsCategoryClass::getModel()::deleteAll(['and', ['gId' => $id], ['in', 'cId', $toDeleteCategoryIds]]); //先通过 getModel 获取 AR 实例,再调用 deleteAll 方法
- //\bizHd\goods\models\GoodsCategory::deleteAll(['and', ['gId' => $id], ['in', 'cId', $toDeleteCategoryIds]]); //直接调用 deleteAll 方法
- CategoryClass::counters(['goodsNum' => -1], ['id' => $toDeleteCategoryIds]);
- }
- // 2. 找出需要新增的分类:新分类列表中不在原有分类中的
- $toAddCategoryIds = array_diff($categoryIdList, $goodsHasCategoryIds);
- if (!empty($toAddCategoryIds)) {
- $addCategory = [];
- foreach ($toAddCategoryIds as $categoryId) {
- $cName = $categoryData[$categoryId]['categoryName'];
- $addCategory[] = [
- 'gId' => $id,
- 'name' => $name,
- 'py' => $py,
- 'cId' => $categoryId,
- 'cName' => $cName,
- 'sjId' => $sjId,
- 'flower' => $flower,
- 'mainId' => $mainId,
- 'setItemNum' => $setItemNum,
- ];
- }
- GoodsCategoryClass::batchAdd($addCategory);
- CategoryClass::counters(['goodsNum' => 1], ['id' => $toAddCategoryIds]);
- }
- // 3. 处理需要修改的分类:既在原有分类中也在新分类列表中的
- $toUpdateCategoryIds = array_intersect($goodsHasCategoryIds, $categoryIdList);
- if (!empty($toUpdateCategoryIds)) {
- foreach ($toUpdateCategoryIds as $categoryId) {
- $cName = $categoryData[$categoryId]['categoryName'];
- $updateData = [
- 'name' => $name,
- 'py' => $py,
- 'cName' => $cName,
- 'setItemNum' => $setItemNum,
- ];
- GoodsCategoryClass::updateByCondition(['gId' => $id, 'cId' => $categoryId], $updateData);
- }
- }
- // 字符串的,即认为是 图片URL
- if (isset($data['cover']) && is_string($data['cover'])) {
- } else {
- $data['cover'] = $data['shopImg'][0] ?? '';
- }
- $data['shopImg'] = json_encode($data['shopImg']);
- $data['py'] = $py;
- //库存可以修改
- if (isset($data['stock']) && is_numeric($data['stock'])) {
- $preStock = $goods['stock'] ?? 0;
- $newStock = $data['stock'];
- if ($newStock != $preStock) {
- if ($staff->super != 1) {
- util::fail('管理员才能修改库存');
- }
- if ($newStock < 0) {
- util::fail("库存不能小于0");
- }
- if (floor($newStock) != $newStock) {
- util::fail('库存请填写整数');
- }
- if ($newStock > $preStock) {
- $diffNum = bcsub($newStock, $preStock);
- $respond = GoodsClass::addStock($id, $mainId, $diffNum);
- } else {
- $diffNum = bcsub($preStock, $newStock);
- $checkStock = false;
- $params = [];
- $respond = GoodsClass::decreaseStock($id, $mainId, $diffNum, $checkStock, $params);
- }
- $oldStock = $respond['oldStock'] ?? 0;
- $newStock = $respond['newStock'] ?? 0;
- $recordData = [];
- $recordData['sjId'] = $sjId;
- $recordData['shopId'] = $shopId;
- $recordData['mainId'] = $mainId;
- $recordData['orderSn'] = '';
- $recordData['goodsId'] = $id;
- $recordData['goodsNum'] = $diffNum;
- $recordData['oldStock'] = $oldStock;
- $recordData['newStock'] = $newStock;
- $recordData['relateName'] = $staff->name ?? '';
- GoodsStockRecordClass::pdGoods($recordData);
- }
- unset($data['stock']);
- }
- self::updateById($id, $data);
- $itemList = $data['itemList'] ?? '';
- $itemArr = json_decode($itemList, true);
- if ($preSetItemNum == 0 && !empty($itemArr)) {
- GoodsItemClass::deleteByCondition(['goodsId' => $id]);
- foreach ($itemArr as $item) {
- $goodsItemData = [
- 'name' => $item['name'] ?? '',
- 'cover' => $item['cover'] ?? '',
- 'sjId' => $sjId,
- 'shopId' => $shopId,
- 'mainId' => $mainId,
- 'goodsId' => $id,
- 'itemId' => $item['id'] ?? 0,
- 'ptItemId' => $item['ptItemId'] ?? 0,
- 'num' => $item['num'] ?? 0,
- 'count' => $item['count'] ?? 0,
- 'ratio' => $item['ratio'] ?? 0,
- 'bigName' => $item['bigName'] ?? '',
- 'smallName' => $item['smallName'] ?? '',
- 'unitType' => $item['unitType'] ?? 0,
- 'unitName' => $item['unitName'] ?? '',
- ];
- GoodsItemClass::addData($goodsItemData);
- }
- }
- }
- // 删除商品 ruidian 2021.5.7
- public static function deleteGoods($id)
- {
- // 当前商品的分类
- $goodsHasCategoryIds = GoodsCategoryService::getGoodsHasCategoryIds($id);
- // 分类商品数-1
- CategoryClass::counters(['goodsNum' => -1], ['id' => $goodsHasCategoryIds]);
- GoodsClass::updateById($id, ['delStatus' => 1]);
- GoodsCategoryClass::updateByCondition(['gId' => $id], ['delStatus' => 1]);
- }
- //产品上下架 ssh 2019.12.8
- public static function changeStatus($id, $status)
- {
- self::updateById($id, ['status' => $status]);
- GoodsCategoryClass::updateByCondition(['gId' => $id], ['status' => $status]);
- }
- //验证商品的有效性 ssh 20201.2.1
- public static function valid($goods, $mainId)
- {
- if (empty($goods)) {
- util::fail('没有找到商品');
- }
- if (isset($goods['mainId']) && $goods['mainId'] == $mainId) {
- return true;
- }
- util::fail('此商品您无法查看哦');
- }
- /**
- * 商品库存变动统一入口:用数据库行锁串行化同一商品的读-算-写。
- */
- private static function runGoodsStockMutation($goodsId, callable $callback)
- {
- $db = Yii::$app->db;
- $currentTransaction = $db->getTransaction();
- $ownTransaction = empty($currentTransaction) || !$currentTransaction->isActive;
- $transaction = $ownTransaction ? $db->beginTransaction() : $currentTransaction;
- try {
- $goodsData = self::getLockById($goodsId);
- if (!$goodsData) {
- util::fail("商品不存在");
- }
- $respond = call_user_func($callback, $goodsData);
- if ($ownTransaction) {
- $transaction->commit();
- }
- return $respond;
- } catch (\Exception $exception) {
- if ($ownTransaction && !empty($transaction) && $transaction->isActive) {
- $transaction->rollBack();
- }
- throw $exception;
- }
- }
- //库存变动入口
- //加库存
- public static function addStock($goodsId, $mainId, $num, $params = [])
- {
- return self::runGoodsStockMutation($goodsId, function ($goodsData) use ($mainId, $num, $params) {
- $goodsMainId = $goodsData->mainId;
- if ($mainId != $goodsMainId) {
- util::fail("非法参数");
- }
- //改库存
- $oldStock = $goodsData->stock;
- $newStock = bcadd($oldStock, $num, 2);
- $goodsData->stock = $newStock;
- $reduceSale = $params['reduceSale'] ?? 0;
- if ($reduceSale == 1) {
- $actualSold = $goodsData->actualSold;
- $newSold = bcsub($actualSold, $num, 2);
- $goodsData->actualSold = max($newSold, 0);
- }
- $goodsData->save();
- return ['oldStock' => $oldStock, 'newStock' => $newStock];
- });
- }
- //减库存
- public static function decreaseStock($goodsId, $mainId, $num, $checkStock = true, $params = [])
- {
- return self::runGoodsStockMutation($goodsId, function ($goodsData) use ($mainId, $num, $checkStock, $params) {
- $goodsMainId = $goodsData->mainId;
- if ($mainId != $goodsMainId) {
- util::fail("非法参数");
- }
- //改库存
- $preStock = $goodsData->stock ?? 0;
- $newStock = bcsub($preStock, $num, 2);
- if ($newStock < 0) {
- if ($checkStock) {
- $goodsName = $goodsData->name ?? '';
- util::fail($goodsName . ',库存不足,剩余:' . $preStock);
- }
- }
- $goodsData->stock = $newStock;
- $addSale = $params['addSale'] ?? 0;
- if ($addSale == 1) {
- //开单减库存增加销量
- $actualSold = $goodsData->actualSold ?? 0;
- $goodsData->actualSold = bcadd($actualSold, $num, 2);
- }
- $goodsData->save();
- return ['oldStock' => $preStock, 'newStock' => $newStock];
- });
- }
- public static function generateSn($goods, $shop)
- {
- if (!empty($goods->sn)) {
- return $goods;
- }
- $shopId = $shop->id;
- $mainId = $shop->mainId;
- $data = ['shopId' => $shopId, 'mainId' => $mainId];
- $sn = orderSn::getGoodsSn($data);
- $goods->sn = $sn;
- $goods->save();
- return $goods;
- }
- }
|