123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983 |
- <?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;
- /**
- * 商品管理
- *
- * @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);
- $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;
- 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
- ->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;
- }
-
- return json($list);
- }
- /**
- * 复制商品
- */
- 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('复制失败:系统错误');
- }
- }
- }
|