12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130 |
- <?php
- namespace app\admin\controller\shop;
- use app\common\controller\Backend;
- use Exception;
- use think\Db;
- use think\exception\PDOException;
- use think\exception\ValidateException;
- use app\admin\model\shop\GoodsAttr;
- use app\admin\model\shop\Spec;
- use app\admin\model\shop\GoodsSkuSpec;
- use app\common\Enum\GoodsEnum;
- use app\common\Service\SkuSpec as SkuSpecService;
- use app\common\Enum\StatusEnum;
- use app\common\Service\DiscountService;
- /**
- * 商品管理
- *
- * @icon fa fa-circle-o
- */
- class Goods extends Backend
- {
- /**
- * 快速搜索时执行查找的字段
- */
- protected $searchFields = 'id,goods_sn,title,subtitle';
- /**
- * Goods模型对象
- * @var \app\admin\model\shop\Goods
- */
- protected $model = null;
- protected $sku_model = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->model = new \app\admin\model\shop\Goods;
- $this->sku_model = new \app\admin\model\shop\GoodsSku;
- // $this->view->assign("flagList", $this->model->getFlagList());
- // $this->view->assign("statusList", $this->model->getStatusList());
- $this->view->assign("goodsTypeList", GoodsEnum::getGoodsTypeMap());
- $this->assignconfig("goodsTypeList", json_encode(GoodsEnum::getGoodsTypeMap()));
- $this->view->assign("statusList", GoodsEnum::getGoodsStatusMap());
- $this->assignconfig("statusList", json_encode(GoodsEnum::getGoodsStatusMap()));
- $this->view->assign("specTypeList", GoodsEnum::getSpecTypeMap());
- $this->assignconfig("specTypeList", json_encode(GoodsEnum::getSpecTypeMap()));
- $this->view->assign("deliveryTypeList", GoodsEnum::getDeliveryTypeMap());
- $this->view->assign("onlineTypeList", GoodsEnum::getOnlineTypeMap());
- $this->view->assign("expressTypeList", GoodsEnum::getExpressTypeMap());
- $this->view->assign("stockShowTypeList", GoodsEnum::getStockShowTypeMap());
- $this->view->assign("salesShowTypeList", GoodsEnum::getSalesShowTypeMap());
- $this->view->assign("yesNoList", StatusEnum::getYesNoMap());
- }
-
- /**
- * 检查商品编码是否重复
- */
- public function checkGoodsSn()
- {
- $goods_sn = $this->request->param('goods_sn');
- $id = $this->request->param('id', 0);
-
- if (empty($goods_sn)) {
- $this->error('商品编码不能为空');
- }
-
- $where = [['goods_sn', '=', $goods_sn]];
- if ($id > 0) {
- $where[] = ['id', '<>', $id];
- }
-
- $exists = $this->model->where($where)->find();
- if ($exists) {
- $this->error('商品编码已存在');
- }
-
- $this->success('商品编码可用');
- }
- /**
- * 查看
- */
- public function index()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- //如果发送的来源是Selectpage,则转发到Selectpage
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $list = $this->model
- ->with(['Freight', 'Brand', 'Category'])
- ->where($where)
- ->order($sort, $order)
- ->paginate($limit);
- // 查询是否有折扣活动 根据ID
- $arrGoodsId = $list->column('id');
-
- // 获取商品与活动的映射关系
- $goodsActivityMapping = DiscountService::getGoodsActivityMapping($arrGoodsId);
-
- // 为每个商品添加活动信息
- $list->each(function(&$goods) use ($goodsActivityMapping) {
- $activityData = $goodsActivityMapping[$goods['id']] ?? null;
- if ($activityData) {
- $goods['activity_name'] = $activityData['name'] ?? '';
- $goods['activity_id'] = $activityData['id'] ?? 0;
- $goods['activity_type'] = $activityData['activity_type'] ?? '';
- $goods['activity_status'] = '进行中';
- } else {
- $goods['activity_name'] = '';
- $goods['activity_id'] = 0;
- $goods['activity_type'] = '';
- $goods['activity_status'] = '无活动';
- }
- });
- $result = array("total" => $list->total(), "rows" => $list->items());
- return json($result);
- }
- return $this->view->fetch();
- }
- /**
- * 查看
- */
- public function select()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags', 'trim']);
- if ($this->request->isAjax()) {
- //如果发送的来源是Selectpage,则转发到Selectpage
- if ($this->request->request('keyField')) {
- return $this->selectpage();
- }
- list($where, $sort, $order, $offset, $limit) = $this->buildparams();
- $list = $this->model
- ->with(['Freight', 'Brand', 'Category'])
- ->where($where)
- ->order($sort, $order)
- ->paginate($limit);
- // 为每个商品添加SKU信息
- $items = $list->items();
- foreach ($items as &$item) {
- // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
- $sku = \app\common\model\Sku::where('goods_id', $item['id'])->find();
- $item['sku_id'] = $sku ? $sku['id'] : 0;
- }
- $result = array("total" => $list->total(), "rows" => $items);
- return json($result);
- }
- return $this->view->fetch();
- }
- //检查属性skus 和 spec 是否对上
- protected function checkSku($skus, $spec)
- {
- foreach ($skus as $item) {
- if (!isset($item['skus']) || !is_array($item['skus']) || empty($item['skus'])) {
- throw new Exception('规格属性不能为空');
- }
- if (!isset($item['price'])) {
- throw new Exception('请录入价格');
- }
- foreach ($item['skus'] as $k => $v) {
- if (empty($v) && !is_numeric($v)) {
- throw new Exception('规格【' . $v . '】属性值不能为空');
- }
- if (!isset($spec[$k]['value']) || (empty($spec[$k]['name']) && !is_numeric($spec[$k]['name']))) {
- throw new Exception('规格【' . $v . '】名称不能为空');
- }
- foreach ($spec[$k]['value'] as $m => $n) {
- // 兼容新格式(对象)和旧格式(字符串)
- $valueText = is_array($n) ? $n['name'] : $n;
- if (stripos($valueText, ',') !== false) {
- throw new Exception('规格【' . $v . '】属性值中不能包含,');
- }
- }
- // 检查重复值(提取name字段进行比较)
- $valueNames = array_map(function($n) {
- return is_array($n) ? $n['name'] : $n;
- }, $spec[$k]['value']);
- if (count($valueNames) != count(array_unique($valueNames))) {
- throw new Exception('规格【' . $v . '】属性值中不能有重复值');
- }
- // 检查规格值是否匹配(支持新旧格式)
- $valueNames = array_map(function($n) {
- return is_array($n) ? $n['name'] : $n;
- }, $spec[$k]['value']);
- if (empty($spec[$k]['value']) || !in_array($v, $valueNames)) {
- throw new Exception('规格【' . $v . '】属性不匹配');
- }
- }
- }
- }
- protected function getSkuId($skus, $newSpec, $spec)
- {
- $arr = [];
- foreach ($skus as $index => $item) {
- $specArr = $spec[$index];
- foreach ($newSpec as $subindex => $subitem) {
- if ($subitem['spec_name'] == $specArr['name'] && $subitem['spec_value_value'] == $item) {
- $arr[] = $subitem['id'];
- }
- }
- }
- sort($arr);
- return implode(',', $arr);
- }
- /**
- * 生成SKU属性JSON字符串
- * @param array $skus 当前SKU的规格值数组
- * @param array $newSpec 规格映射数据
- * @param array $spec 规格原始数据
- * @return string JSON格式的SKU属性字符串
- */
- protected function generateSkuAttr($skus, $newSpec, $spec)
- {
- $skuAttr = [];
- foreach ($skus as $index => $item) {
- $specArr = $spec[$index];
- foreach ($newSpec as $subindex => $subitem) {
- if ($subitem['spec_name'] == $specArr['name'] && $subitem['spec_value_value'] == $item) {
- $skuAttr[] = [
- 'key' => $subitem['spec_name'],
- 'value' => $subitem['spec_value_value'],
- 'key_id' => $subitem['spec_id'],
- 'value_id' => $subitem['spec_value_id'],
- 'type' => $specArr['type'] ?? 'basic' // 增加规格类型字段
- ];
- break;
- }
- }
- }
- return json_encode($skuAttr, JSON_UNESCAPED_UNICODE);
- }
- /**
- * 根据上下架时间计算商品状态
- * @param array $params 商品参数
- * @return int 商品状态
- */
- protected function calculateGoodsStatus($params)
- {
- $currentTime = time();
-
- // 获取上架时间设置 - 前端传递的上架类型字段(使用status字段)
- $onlineType = isset($params['status']) ? intval($params['status']) : GoodsEnum::ONLINE_TYPE_NOT_NOW;
- $scheduledOnlineTime = isset($params['scheduled_online_time']) ? strtotime($params['scheduled_online_time']) : 0;
-
- // 获取下架时间设置
- $isAutoOffline = isset($params['is_auto_offline']) ? intval($params['is_auto_offline']) : 0;
- $scheduledOfflineTime = isset($params['scheduled_offline_time']) ? strtotime($params['scheduled_offline_time']) : 0;
-
- // 根据上架类型判断状态
- switch ($onlineType) {
- case GoodsEnum::ONLINE_TYPE_IMMEDIATE: // 立即上架
- // 检查是否需要自动下架
- if ($isAutoOffline && $scheduledOfflineTime > 0) {
- if ($currentTime >= $scheduledOfflineTime) {
- return GoodsEnum::STATUS_OFF_SALE; // 已下架
- }
- }
- return GoodsEnum::STATUS_ON_SALE; // 销售中
-
- case GoodsEnum::ONLINE_TYPE_NOT_NOW: // 暂不上架
- return GoodsEnum::STATUS_IN_STORAGE; // 仓库中
-
- case GoodsEnum::ONLINE_TYPE_SCHEDULED: // 定时上架
- if ($scheduledOnlineTime <= 0) {
- return GoodsEnum::STATUS_IN_STORAGE; // 未设置上架时间,保持仓库中
- }
-
- if ($currentTime < $scheduledOnlineTime) {
- return GoodsEnum::STATUS_IN_STORAGE; // 未到上架时间,仓库中
- }
-
- // 已到上架时间,检查下架时间
- if ($isAutoOffline && $scheduledOfflineTime > 0) {
- if ($currentTime >= $scheduledOfflineTime) {
- return GoodsEnum::STATUS_OFF_SALE; // 已下架
- }
- }
-
- return GoodsEnum::STATUS_ON_SALE; // 销售中
-
- default:
- return GoodsEnum::STATUS_IN_STORAGE; // 默认仓库中
- }
- }
- //处理商品SKU(统一处理单规格和多规格)
- protected function processGoodsSku($params, $goods_id)
- {
- // 统一通过skus和spec字段处理
- if (isset($params['skus']) && isset($params['spec'])) {
- $skus = (array)json_decode($params['skus'], true);
- $spec = (array)json_decode($params['spec'], true);
-
- // 判断是单规格还是多规格
- if (empty($spec) && count($skus) === 1) {
- // 单规格处理
- $this->addSingleSpecSku($skus[0], $goods_id);
- } else {
- // 多规格处理
- $this->addMultiSpecSku($skus, $spec, $goods_id);
- }
- } else {
- throw new \Exception('SKU数据格式错误');
- }
- }
- //添加单规格商品SKU
- protected function addSingleSpecSku($skuData, $goods_id)
- {
- // 如果原来是多规格,先清理多余的SKU记录
- $existingSkuCount = $this->sku_model->where('goods_id', $goods_id)->count();
- if ($existingSkuCount > 1) {
- // 从多规格改为单规格,删除所有旧记录
- $this->sku_model->where('goods_id', $goods_id)->delete();
- }
-
- // 查询现有的SKU记录
- $existingSku = $this->sku_model->where('goods_id', $goods_id)->find();
-
- // 创建单规格SKU数据
- $newSkuData = [
- 'goods_id' => $goods_id,
- 'spec_value_ids' => '', // 单规格无规格值ID
- 'sku_attr' => '', // 单规格无规格属性
- 'sku_sn' => $skuData['sku_sn'] ?? '',
- 'image' => $skuData['image'] ?? '',
- 'price' => $skuData['price'] ?? 0,
- 'lineation_price'=> $skuData['lineation_price'] ?? 0,
- 'cost_price' => $skuData['cost_price'] ?? 0,
- 'weight' => $skuData['weight'] ?? 0,
- 'volume' => $skuData['volume'] ?? 0,
- 'stocks' => $skuData['stocks'] ?? 0,
- 'status' => 1,
- 'is_default' => 1, // 单规格默认为默认SKU
- ];
-
- $defaultSkuId = 0;
-
- if ($existingSku) {
- // 单规格商品已存在SKU记录,直接更新(保持ID和销量不变)
- $newSkuData['sales'] = $existingSku->sales; // 保持原有销量
- $existingSku->save($newSkuData);
- $defaultSkuId = $existingSku->id;
- } else {
- // 新商品,创建SKU记录
- $newSkuData['sales'] = 0;
- $newSku = $this->sku_model->create($newSkuData);
- $defaultSkuId = $newSku->id;
- }
-
- // 更新商品主表信息
- $updateData = [
- 'spec_type' => 0, // 单规格
- 'stocks' => $skuData['stocks'] ?? 0,
- 'min_price' => $skuData['price'] ?? 0,
- 'max_price' => $skuData['price'] ?? 0,
- 'price' => $skuData['price'] ?? 0,
- 'min_lineation_price'=> $skuData['lineation_price'] ?? 0,
- 'max_lineation_price'=> $skuData['lineation_price'] ?? 0,
- 'lineation_price' => $skuData['lineation_price'] ?? 0,
- 'default_sku_id' => $defaultSkuId,
- ];
-
- $this->model->where('id', $goods_id)->update($updateData);
- }
- //添加商品多规格
- protected function addMultiSpecSku($skus, $spec, $goods_id)
- {
- //属性入库,传递规格类型信息
- $specList = Spec::push($spec);
- $newSpec = GoodsSkuSpec::push($specList, $goods_id, $spec);
- //匹配属性
- $list = $this->sku_model->where('goods_id', $goods_id)->select();
- $newData = [];
- $stocks = 0;
- foreach ($skus as $k => $sk) {
- $newSkuId = $this->getSkuId($sk['skus'], $newSpec, $spec);
-
- // 生成SKU规格属性JSON字符串
- $skuAttr = $this->generateSkuAttr($sk['skus'], $newSpec, $spec);
-
- $newSkuData = [
- 'goods_id' => $goods_id,
- 'spec_value_ids' => $newSkuId,
- 'sku_attr' => $skuAttr,
- 'sku_sn' => $sk['sku_sn'] ?? '',
- 'image' => $sk['image'] ?? '',
- 'price' => $sk['price'] ?? 0,
- 'lineation_price' => $sk['lineation_price'] ?? 0,
- 'cost_price' => $sk['cost_price'] ?? 0,
- 'weight' => $sk['weight'] ?? 0,
- 'volume' => $sk['volume'] ?? 0,
- 'stocks' => $sk['stocks'] ?? 0,
- 'status' => isset($sk['status']) ? intval($sk['status']) : 1,
- 'is_default' => isset($sk['is_default']) ? intval($sk['is_default']) : 0,
- ];
- if (isset($list[$k])) {
- $row = $list[$k];
- $oldSkuIdsArr = explode(',', $row['spec_value_ids']);
- sort($oldSkuIdsArr);
- $oldSkuId = implode(',', $oldSkuIdsArr);
- if ($oldSkuId == $newSkuId) {
- //相等的更新
- $row->save($newSkuData);
- } else {
- //不等的
- $row->save(array_merge($newSkuData, ['sales' => 0]));
- }
- unset($list[$k]);
- } else { //多余的
- $newData[] = array_merge($newSkuData, ['sales' => 0]);
- }
- $stocks = bcadd($stocks, $sk['stocks'] ?? 0);
- }
- if (!empty($newData)) {
- $this->sku_model->saveAll($newData);
- }
-
- // 处理默认SKU
- $defaultSkuId = 0;
- $hasDefault = false;
- foreach ($skus as $k => $sk) {
- if (isset($sk['is_default']) && $sk['is_default']) {
- $hasDefault = true;
- break;
- }
- }
-
- // 如果没有明确设置默认SKU,则使用第一个SKU作为默认
- if (!$hasDefault && !empty($skus)) {
- $firstSku = $this->sku_model->where('goods_id', $goods_id)->order('id', 'asc')->find();
- if ($firstSku) {
- $firstSku->save(['is_default' => 1]);
- $defaultSkuId = $firstSku->id;
- }
- } else {
- // 查找默认SKU的ID
- $defaultSku = $this->sku_model->where('goods_id', $goods_id)->where('is_default', 1)->find();
- if ($defaultSku) {
- $defaultSkuId = $defaultSku->id;
- }
- }
-
- //更新库存和默认SKU,计算价格范围
- if (!empty($skus)) {
- $prices = array_column($skus, 'price');
- $lineationPrices = array_column($skus, 'lineation_price');
-
- // 使用bc函数计算平均价格,保证精度
- $totalPrice = '0';
- $validPriceCount = 0;
- foreach ($prices as $price) {
- if ($price > 0) {
- $totalPrice = bcadd($totalPrice, (string)$price, 2);
- $validPriceCount++;
- }
- }
-
- // 计算平均价格
- $avgPrice = $validPriceCount > 0 ? bcdiv($totalPrice, (string)$validPriceCount, 2) : '0.00';
-
- // 使用bc函数计算平均划线价格
- $totalLineationPrice = '0';
- $validLineationPriceCount = 0;
- foreach ($lineationPrices as $lineationPrice) {
- if ($lineationPrice > 0) {
- $totalLineationPrice = bcadd($totalLineationPrice, (string)$lineationPrice, 2);
- $validLineationPriceCount++;
- }
- }
-
- // 计算平均划线价格
- $avgLineationPrice = $validLineationPriceCount > 0 ? bcdiv($totalLineationPrice, (string)$validLineationPriceCount, 2) : '0.00';
-
- // 过滤掉0值的划线价格来计算最大最小值
- $validLineationPrices = array_filter($lineationPrices, function($price) {
- return $price > 0;
- });
-
- $updateData = [
- 'stocks' => $stocks,
- 'spec_type' => 1,
- 'min_price' => min($prices),
- 'max_price' => max($prices),
- 'price' => $avgPrice,
- 'min_lineation_price' => !empty($validLineationPrices) ? min($validLineationPrices) : '0.00',
- 'max_lineation_price' => !empty($validLineationPrices) ? max($validLineationPrices) : '0.00',
- 'lineation_price' => $avgLineationPrice
- ];
- if ($defaultSkuId > 0) {
- $updateData['default_sku_id'] = $defaultSkuId;
- }
- $this->model->where('id', $goods_id)->update($updateData);
- } else {
- $this->model->where('id', $goods_id)->update(['spec_type' => 0]);
- }
- //原来多的删除
- foreach ($list as $it) {
- $it->delete();
- }
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
- $params[$this->dataLimitField] = $this->auth->id;
- }
- $result = false;
- Db::startTrans();
- try {
- //是否采用模型验证
- if ($this->modelValidate) {
- $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
-
- // 添加规格数据到验证参数中
- if (isset($params['skus']) && isset($params['spec'])) {
- $params['spec_data'] = json_decode($params['spec'], true);
- $params['sku_data'] = json_decode($params['skus'], true);
- }
-
- $this->model->validateFailException(true)->validate($validate);
- }
-
- // 备份上架类型,因为status字段将被覆盖为最终状态
- $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
-
- // 将online_type映射到status字段用于计算
- if (isset($params['online_type'])) {
- $params['status'] = $params['online_type'];
- unset($params['online_type']);
- }
-
- // 先保存商品基础信息(暂时不保存status字段)
- $statusBackup = $params['status'] ?? null;
- unset($params['status']); // 临时移除status避免冲突
- $result = $this->model->allowField(true)->save($params);
-
- // 根据上下架时间自动计算商品状态并更新
- $params['status'] = $statusBackup; // 恢复用于计算
- $calculatedStatus = $this->calculateGoodsStatus($params);
- $this->model->where('id', $this->model->id)->update([
- 'status' => $calculatedStatus,
- 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
- ]);
-
- // 调试输出
- \think\Log::write('商品添加 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
- //商品规格处理
- if (isset($params['skus']) && isset($params['spec'])) {
- $skus = (array)json_decode($params['skus'], true);
- $spec = (array)json_decode($params['spec'], true);
-
- // 只对多规格进行checkSku验证
- if (!empty($spec)) {
- $this->checkSku($skus, $spec);
- }
-
- // 统一处理SKU
- $this->processGoodsSku($params, $this->model->id);
- } else {
- throw new \Exception('商品规格数据不能为空');
- }
- //商品属性
- if (isset($params['attribute_ids'])) {
- GoodsAttr::addGoodsAttr($params['attribute_ids'], $this->model->id);
- }
- Db::commit();
- } catch (ValidateException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (PDOException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were inserted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- return $this->view->fetch();
- }
- /**
- * 编辑
- */
- public function edit($ids = null)
- {
- $row = $this->model->find($ids);
- if (!$row) {
- $this->error(__('No Results were found'));
- }
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds)) {
- if (!in_array($row[$this->dataLimitField], $adminIds)) {
- $this->error(__('You have no permission'));
- }
- }
- if ($this->request->isPost()) {
- $params = $this->request->post("row/a");
- if ($params) {
- $params = $this->preExcludeFields($params);
- $result = false;
- // 查询该商品是否参与进行中的折扣活动
- if (DiscountService::hasActivity($row->id)) {
- $this->error('该商品参与了进行中的折扣活动,不能编辑');
- }
- Db::startTrans();
- try {
- //是否采用模型验证
- if ($this->modelValidate) {
- $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
-
- // 添加规格数据到验证参数中
- if (isset($params['skus']) && isset($params['spec'])) {
- $params['spec_data'] = json_decode($params['spec'], true);
- $params['sku_data'] = json_decode($params['skus'], true);
- }
-
- $row->validateFailException(true)->validate($validate);
- }
-
- // 备份上架类型,因为status字段将被覆盖为最终状态
- $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
-
- // 将online_type映射到status字段用于计算
- if (isset($params['online_type'])) {
- $params['status'] = $params['online_type'];
- unset($params['online_type']);
- }
-
- // 先保存商品基础信息(暂时不保存status字段)
- $statusBackup = $params['status'] ?? null;
- unset($params['status']); // 临时移除status避免冲突
- $result = $row->allowField(true)->save($params);
-
- // 根据上下架时间自动计算商品状态并更新
- $params['status'] = $statusBackup; // 恢复用于计算
- $calculatedStatus = $this->calculateGoodsStatus($params);
- $this->model->where('id', $row->id)->update([
- 'status' => $calculatedStatus,
- 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
- ]);
-
- // 调试输出
- \think\Log::write('商品编辑 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
- //商品规格处理
- if (isset($params['skus']) && isset($params['spec'])) {
- $skus = (array)json_decode($params['skus'], true);
- $spec = (array)json_decode($params['spec'], true);
-
- // 只对多规格进行checkSku验证
- if (!empty($spec)) {
- $this->checkSku($skus, $spec);
- }
-
- // 统一处理SKU
- $this->processGoodsSku($params, $row->id);
- } else {
- throw new \Exception('商品规格数据不能为空');
- }
- //商品属性
- if (isset($params['attribute_ids'])) {
- GoodsAttr::addGoodsAttr($params['attribute_ids'], $row->id);
- }
- Db::commit();
- } catch (ValidateException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (PDOException $e) {
- Db::rollback();
- $this->error($e->getMessage());
- } catch (Exception $e) {
- Db::rollback();
- $this->error($e->getMessage());
- }
- if ($result !== false) {
- $this->success();
- } else {
- $this->error(__('No rows were updated'));
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
-
-
- // 查询SKU数据
- $list = $this->sku_model->where('goods_id', $row->id)->select();
-
- // 构造规格数据结构
- $spec_data = [];
- $spec_values = []; // 用于传递给前端的规格值完整数据
- if ($row->spec_type == 1) { // 多规格商品
- // 查询规格和规格值,包含规格类型
- $specs = Db::name('shop_goods_sku_spec')
- ->alias('gss')
- ->field('sp.id as spec_id, sp.name as spec_name, sp.type as spec_type, sv.id as spec_value_id, sv.value, sv.image, sv.desc')
- ->join('shop_spec sp', 'sp.id = gss.spec_id', 'LEFT')
- ->join('shop_spec_value sv', 'sv.id = gss.spec_value_id', 'LEFT')
- ->where('gss.goods_id', $row->id)
- ->order('sp.id asc, sv.id asc')
- ->select();
-
- // 按规格分组
- $spec_groups = [];
- foreach ($specs as $spec) {
- if (!isset($spec_groups[$spec['spec_id']])) {
- $spec_groups[$spec['spec_id']]['name'] = $spec['spec_name'];
- $spec_groups[$spec['spec_id']]['type'] = $spec['spec_type'] == 2 ? 'custom' : 'basic';
- $spec_groups[$spec['spec_id']]['value'] = [];
- }
- $spec_groups[$spec['spec_id']]['value'][] = [
- 'id' => $spec['spec_value_id'],
- 'name' => $spec['value'],
- 'image' => $spec['image'] ?: '',
- 'description' => $spec['desc'] ?: ''
- ];
-
- // 构造规格值数据,用于前端初始化
- $spec_values[] = [
- 'spec_name' => $spec['spec_name'],
- 'spec_type' => $spec['spec_type'],
- 'value' => $spec['value'],
- 'image' => $spec['image'] ?: '',
- 'description' => $spec['desc'] ?: ''
- ];
- }
-
- // 转换为前端需要的格式
- foreach ($spec_groups as $spec_id => $spec_info) {
- $spec_data[] = [
- 'id' => $spec_id,
- 'name' => $spec_info['name'],
- 'type' => $spec_info['type'],
- 'value' => $spec_info['value']
- ];
- }
- }
-
- $this->view->assign("row", $row);
- $this->assignconfig('goods', $row);
- $this->assignconfig('goods_skus', $list);
- $this->assignconfig('spec_data', $spec_data); // 传递规格数据结构
- $this->assignconfig('spec_values', $spec_values); // 传递规格值完整数据
- return $this->view->fetch();
- }
- /**
- * 获取多个商品信息
- */
- public function getGoodsByIds()
- {
- $ids = $this->request->request('ids');
- if (!$ids) {
- $this->error('请选择商品');
- }
-
- $ids = explode(',', $ids);
- $list = $this->model
- ->with(['Category'])
- ->where('id', 'in', $ids)
- ->select();
-
- // 处理图片URL和SKU信息
- foreach ($list as &$item) {
- if ($item['image']) {
- $item['image'] = cdnurl($item['image'], true);
- }
-
- // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
- $sku = \app\common\model\Sku::where('goods_id', $item['id'])->find();
- $item['sku_id'] = $sku ? $sku['id'] : 0;
- }
-
-
- $this->success('获取成功', null, $list);
- }
- /**
- * 根据ID批量获取商品信息
- */
- public function get_goods_by_ids()
- {
- $ids = $this->request->request('ids');
- if (!$ids) {
- $this->error('请选择商品');
- }
-
- $ids = explode(',', $ids);
- $list = $this->model
- ->where('id', 'in', $ids)
- ->select();
-
- // 转换商品结果为数组
- $goodsData = [];
- if ($list) {
- foreach ($list as $item) {
- $goodsData[] = is_array($item) ? $item : $item->toArray();
- }
- }
-
- // 如果没有商品数据,直接返回空数组
- if (empty($goodsData)) {
- return json([]);
- }
-
- // 一次性查询所有商品的SKU信息
- $allSkusResult = Db::name('shop_goods_sku')
- ->where('goods_id', 'in', $ids)
- ->order('is_default desc, id asc')
- ->select();
-
- // 按商品ID分组SKU数据
- $skusByGoods = [];
- foreach ($allSkusResult as $sku) {
- $skuArray = is_array($sku) ? $sku : $sku->toArray();
- $skusByGoods[$skuArray['goods_id']][] = $skuArray;
- }
-
- // 找出多规格商品ID
- $multiSpecGoodsIds = [];
- foreach ($goodsData as $item) {
- if ($item['spec_type'] == 1) {
- $multiSpecGoodsIds[] = $item['id'];
- }
- }
-
- // 一次性查询所有多规格商品的规格信息
- $specsByGoods = [];
- if (!empty($multiSpecGoodsIds)) {
- $allSpecsResult = Db::name('shop_goods_sku_spec')
- ->alias('gss')
- ->field('sp.id as spec_id, sp.name as spec_name, sp.type as spec_type, sv.id as spec_value_id, sv.value, sv.image, sv.desc, gss.goods_id')
- ->join('shop_spec sp', 'sp.id=gss.spec_id', 'LEFT')
- ->join('shop_spec_value sv', 'sv.id=gss.spec_value_id', 'LEFT')
- ->where('gss.goods_id', 'in', $multiSpecGoodsIds)
- ->order('gss.goods_id asc, sp.id asc, sv.id asc')
- ->select();
-
- // 按商品ID分组规格数据
- foreach ($allSpecsResult as $spec) {
- $specArray = is_array($spec) ? $spec : $spec->toArray();
- $specsByGoods[$specArray['goods_id']][] = $specArray;
- }
- }
-
- // 一次性查询所有SKU的规格属性文本
- $allSkuIds = [];
- foreach ($skusByGoods as $skus) {
- foreach ($skus as $sku) {
- $allSkuIds[] = $sku['id'];
- }
- }
-
- $skuSpecTexts = [];
- if (!empty($allSkuIds)) {
- $skuSpecResults = Db::name('shop_goods_sku')
- ->alias('sku')
- ->field('sku.id, GROUP_CONCAT(sp.name,":",sv.value ORDER BY sp.id asc) as specs_text')
- ->join('shop_goods_sku_spec gss', "FIND_IN_SET(gss.id, sku.spec_value_ids)", 'LEFT')
- ->join('shop_spec sp', 'sp.id=gss.spec_id', 'LEFT')
- ->join('shop_spec_value sv', 'sv.id=gss.spec_value_id', 'LEFT')
- ->where('sku.id', 'in', $allSkuIds)
- ->group('sku.id')
- ->select();
-
- foreach ($skuSpecResults as $result) {
- $resultArray = is_array($result) ? $result : $result->toArray();
- $skuSpecTexts[$resultArray['id']] = $resultArray['specs_text'] ?: '';
- }
- }
-
- // 处理每个商品的详细信息(纯数据组装,无数据库查询)
- foreach ($goodsData as &$item) {
- if ($item['image']) {
- $item['image'] = cdnurl($item['image'], true);
- }
-
- // 获取商品的SKU信息
- $skus = $skusByGoods[$item['id']] ?? [];
-
- if ($skus) {
- // 获取第一个SKU ID(单规格商品通常只有一个SKU)
- $item['sku_id'] = $skus[0]['id'];
-
- // 为每个SKU添加规格属性文本
- foreach ($skus as &$sku) {
- $sku['specs_text'] = $skuSpecTexts[$sku['id']] ?? '';
- }
- $item['skus'] = $skus;
-
- // 如果是多规格商品,添加规格数据
- if ($item['spec_type'] == 1) {
- $specs = $specsByGoods[$item['id']] ?? [];
-
- // 按规格分组构建规格数据结构
- $spec_groups = [];
- foreach ($specs as $spec) {
- if (!isset($spec_groups[$spec['spec_id']])) {
- $spec_groups[$spec['spec_id']]['id'] = $spec['spec_id'];
- $spec_groups[$spec['spec_id']]['name'] = $spec['spec_name'];
- $spec_groups[$spec['spec_id']]['type'] = $spec['spec_type'] == 2 ? 'custom' : 'basic';
- $spec_groups[$spec['spec_id']]['value'] = [];
- }
- $spec_groups[$spec['spec_id']]['value'][] = [
- 'id' => $spec['spec_value_id'],
- 'name' => $spec['value'],
- 'image' => $spec['image'] ?: '',
- 'description' => $spec['desc'] ?: ''
- ];
- }
-
- // 转换为数组格式,与前端渲染一致
- $item['spec'] = array_values($spec_groups);
- } else {
- // 单规格商品,没有spec数据
- $item['spec'] = [];
- }
- } else {
- $item['sku_id'] = 0;
- $item['skus'] = [];
- $item['spec'] = [];
- }
- }
-
- return json($goodsData);
- }
- /**
- * 复制商品
- */
- public function copy($ids = null)
- {
- $row = $this->model->find($ids);
- if (!$row) {
- $this->error(__('No Results were found'));
- }
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds)) {
- if (!in_array($row[$this->dataLimitField], $adminIds)) {
- $this->error(__('You have no permission'));
- }
- }
- Db::startTrans();
- try {
- // 复制商品基本信息
- $goodsData = $row->toArray();
-
- // 调试输出
- \think\Log::write('开始复制商品,原商品ID: ' . $row->id, 'info');
-
- // 移除不需要复制的字段
- unset($goodsData['id'], $goodsData['createtime'], $goodsData['updatetime']);
-
- // 修改商品名称和编码,添加"复制"标识
- $goodsData['title'] = $goodsData['title'] . ' (复制)';
- $goodsData['goods_sn'] = $goodsData['goods_sn'] . '_copy_' . date('YmdHis');
- $goodsData['status'] = \app\common\Enum\GoodsEnum::STATUS_IN_STORAGE; // 复制的商品默认为仓库中状态
- $goodsData['online_type'] = \app\common\Enum\GoodsEnum::ONLINE_TYPE_NOT_NOW; // 暂不上架
- $goodsData['sales'] = 0; // 重置销量
- $goodsData['views'] = 0; // 重置浏览量
-
- // 创建新商品
- $newGoods = $this->model->create($goodsData);
- $newGoodsId = $newGoods->id;
-
- // 复制商品SKU信息
- $skuList = $this->sku_model->where('goods_id', $row->id)->select();
- \think\Log::write('查询到SKU数量: ' . ($skuList ? count($skuList) : 0), 'info');
- $newSkuData = [];
- $defaultSkuId = 0;
-
- if ($skuList && !$skuList->isEmpty()) {
- foreach ($skuList as $sku) {
- $skuData = $sku->toArray();
- unset($skuData['id'], $skuData['createtime'], $skuData['updatetime']);
-
- $skuData['goods_id'] = $newGoodsId;
- $skuData['sales'] = 0; // 重置销量
- $skuData['sku_sn'] = $skuData['sku_sn'] . '_copy_' . date('YmdHis');
-
- $newSkuData[] = $skuData;
- }
- }
-
- if (!empty($newSkuData)) {
- $newSkus = $this->sku_model->saveAll($newSkuData);
- // 获取第一个SKU作为默认SKU
- if (!empty($newSkus)) {
- $defaultSkuId = $newSkus[0]->id;
- }
- } else {
- // 如果没有SKU数据,创建一个默认的SKU
- \think\Log::write('没有找到SKU数据,创建默认SKU', 'info');
- $defaultSkuData = [
- 'goods_id' => $newGoodsId,
- 'spec_value_ids' => '',
- 'sku_attr' => '', // 单规格无规格属性
- 'sku_sn' => $goodsData['goods_sn'] ?? 'SKU_' . date('YmdHis'),
- 'image' => $goodsData['image'] ?? '',
- 'price' => isset($goodsData['price']) ? $goodsData['price'] : 0.01,
- 'lineation_price' => isset($goodsData['lineation_price']) ? $goodsData['lineation_price'] : 0,
- 'cost_price' => 0,
- 'weight' => 0,
- 'volume' => 0,
- 'stocks' => 1,
- 'sales' => 0,
- 'status' => 1,
- 'is_default' => 1,
- ];
- $newSku = $this->sku_model->create($defaultSkuData);
- $defaultSkuId = $newSku->id;
- }
-
- // 更新商品默认SKU
- if ($defaultSkuId > 0) {
- $newGoods->save(['default_sku_id' => $defaultSkuId]);
- }
-
- // 复制商品规格信息(如果是多规格商品)
- if ($row->spec_type == 1) {
- // 复制商品规格关联
- $goodsSpecList = Db::name('shop_goods_sku_spec')
- ->where('goods_id', $row->id)
- ->select();
-
- $newGoodsSpecData = [];
- if ($goodsSpecList && is_array($goodsSpecList) && !empty($goodsSpecList)) {
- foreach ($goodsSpecList as $goodsSpec) {
- $newGoodsSpecData[] = [
- 'goods_id' => $newGoodsId,
- 'spec_id' => $goodsSpec['spec_id'],
- 'spec_value_id' => $goodsSpec['spec_value_id'],
- 'createtime' => time(),
- 'updatetime' => time()
- ];
- }
- }
-
- if (!empty($newGoodsSpecData)) {
- Db::name('shop_goods_sku_spec')->insertAll($newGoodsSpecData);
- }
- }
-
- // 复制商品属性信息
- $goodsAttrList = Db::name('shop_goods_attr')
- ->where('goods_id', $row->id)
- ->select();
-
- $newGoodsAttrData = [];
- if ($goodsAttrList && is_array($goodsAttrList) && !empty($goodsAttrList)) {
- foreach ($goodsAttrList as $goodsAttr) {
- $newGoodsAttrData[] = [
- 'goods_id' => $newGoodsId,
- 'attr_id' => $goodsAttr['attr_id'],
- 'attr_value' => $goodsAttr['attr_value'],
- 'createtime' => time(),
- 'updatetime' => time()
- ];
- }
- }
-
- if (!empty($newGoodsAttrData)) {
- Db::name('shop_goods_attr')->insertAll($newGoodsAttrData);
- }
-
- Db::commit();
- \think\Log::write('商品复制成功,新商品ID: ' . $newGoodsId, 'info');
- $this->success('商品复制成功', null, ['goods_id' => $newGoodsId]);
-
- } catch (Exception $e) {
- Db::rollback();
- \think\Log::write('商品复制失败: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行: ' . $e->getLine(), 'error');
- $this->error('复制失败:' . $e->getMessage());
- } catch (\Throwable $e) {
- Db::rollback();
- \think\Log::write('商品复制出现严重错误: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行: ' . $e->getLine(), 'error');
- $this->error('复制失败:系统错误');
- }
- }
- }
|