123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329 |
- <?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(统一处理单规格和多规格)
- * @param array $params 商品参数
- * @param int $goods_id 商品ID
- * @throws \Exception
- */
- protected function processGoodsSku($params, $goods_id)
- {
- // 统一通过skus和spec字段处理
- if (!isset($params['skus']) || !isset($params['spec'])) {
- throw new \Exception('SKU数据格式错误');
- }
- $skus = (array)json_decode($params['skus'], true);
- $spec = (array)json_decode($params['spec'], true);
-
- if (empty($skus)) {
- throw new \Exception('SKU数据不能为空');
- }
-
- // 判断是单规格还是多规格
- if (empty($spec) && count($skus) === 1) {
- // 单规格处理
- $this->processSingleSpecSku($skus[0], $goods_id);
- } else {
- // 多规格处理
- $this->processMultiSpecSku($skus, $spec, $goods_id);
- }
- }
- /**
- * 处理单规格商品SKU
- * @param array $skuData SKU数据
- * @param int $goods_id 商品ID
- */
- protected function processSingleSpecSku($skuData, $goods_id)
- {
- // 验证单规格SKU数据
- $this->validateSingleSpecSku($skuData);
-
- // 如果原来是多规格,先清理多余的SKU记录和规格关联
- $existingSkuCount = $this->sku_model->where('goods_id', $goods_id)->count();
- if ($existingSkuCount > 1) {
- // 从多规格改为单规格,删除所有旧记录
- $this->sku_model->where('goods_id', $goods_id)->delete();
- // 删除规格关联数据
- Db::name('shop_goods_sku_spec')->where('goods_id', $goods_id)->delete();
- }
-
- // 查询现有的SKU记录
- $existingSku = $this->sku_model->where('goods_id', $goods_id)->find();
-
- // 创建单规格SKU数据
- $newSkuData = $this->buildSingleSkuData($skuData, $goods_id);
-
- $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;
- }
-
- // 更新商品主表信息
- $this->updateGoodsForSingleSpec($skuData, $goods_id, $defaultSkuId);
- }
-
- /**
- * 验证单规格SKU数据
- * @param array $skuData
- * @throws \Exception
- */
- protected function validateSingleSpecSku($skuData)
- {
- if (!isset($skuData['price']) || floatval($skuData['price']) <= 0) {
- throw new \Exception('单规格商品销售价必须大于0');
- }
-
- if (!isset($skuData['stocks']) || intval($skuData['stocks']) <= 0) {
- throw new \Exception('单规格商品库存必须大于0');
- }
- }
-
- /**
- * 构建单规格SKU数据
- * @param array $skuData
- * @param int $goods_id
- * @return array
- */
- protected function buildSingleSkuData($skuData, $goods_id)
- {
- return [
- 'goods_id' => $goods_id,
- 'spec_value_ids' => '', // 单规格无规格值ID
- 'sku_attr' => '', // 单规格无规格属性
- 'sku_sn' => $skuData['sku_sn'] ?? '',
- 'image' => $skuData['image'] ?? '',
- 'price' => floatval($skuData['price'] ?? 0),
- 'lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
- 'cost_price' => floatval($skuData['cost_price'] ?? 0),
- 'weight' => floatval($skuData['weight'] ?? 0),
- 'volume' => floatval($skuData['volume'] ?? 0),
- 'stocks' => intval($skuData['stocks'] ?? 0),
- 'status' => 1,
- 'is_default' => 1, // 单规格默认为默认SKU
- ];
- }
-
- /**
- * 更新商品主表信息(单规格)
- * @param array $skuData
- * @param int $goods_id
- * @param int $defaultSkuId
- */
- protected function updateGoodsForSingleSpec($skuData, $goods_id, $defaultSkuId)
- {
- $updateData = [
- 'spec_type' => 0, // 单规格
- 'stocks' => intval($skuData['stocks'] ?? 0),
- 'min_price' => floatval($skuData['price'] ?? 0),
- 'max_price' => floatval($skuData['price'] ?? 0),
- 'price' => floatval($skuData['price'] ?? 0),
- 'min_lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
- 'max_lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
- 'lineation_price' => floatval($skuData['lineation_price'] ?? 0),
- 'default_sku_id' => $defaultSkuId,
- ];
-
- $this->model->where('id', $goods_id)->update($updateData);
- }
- /**
- * 处理多规格商品SKU
- * @param array $skus SKU数据数组
- * @param array $spec 规格数据数组
- * @param int $goods_id 商品ID
- */
- protected function processMultiSpecSku($skus, $spec, $goods_id)
- {
- // 验证多规格数据
- $this->validateMultiSpecSku($skus, $spec);
-
- // 规格属性入库,传递规格类型信息
- $specList = Spec::push($spec);
- $newSpec = GoodsSkuSpec::push($specList, $goods_id, $spec);
-
- // 处理SKU数据
- $this->processSkuData($skus, $newSpec, $spec, $goods_id);
-
- // 处理默认SKU
- $defaultSkuId = $this->processDefaultSku($skus, $goods_id);
-
- // 更新商品主表信息
- $this->updateGoodsForMultiSpec($skus, $goods_id, $defaultSkuId);
-
- // 清理无用的SKU记录
- $this->cleanupUnusedSkus($goods_id, count($skus));
- }
-
- /**
- * 验证多规格SKU数据
- * @param array $skus
- * @param array $spec
- * @throws \Exception
- */
- protected function validateMultiSpecSku($skus, $spec)
- {
- if (empty($spec)) {
- throw new \Exception('多规格商品必须设置规格信息');
- }
-
- // 验证是否有有效的SKU
- $hasValidSku = false;
- foreach ($skus as $sku) {
- if (isset($sku['status']) && ($sku['status'] == 1 || $sku['status'] === '1')) {
- $hasValidSku = true;
-
- if (!isset($sku['price']) || floatval($sku['price']) <= 0) {
- throw new \Exception('SKU销售价必须大于0');
- }
-
- if (!isset($sku['stocks']) || intval($sku['stocks']) <= 0) {
- throw new \Exception('SKU库存必须大于0');
- }
- }
- }
-
- if (!$hasValidSku) {
- throw new \Exception('多规格商品至少需要一个有效的SKU');
- }
- }
-
- /**
- * 处理SKU数据
- * @param array $skus
- * @param array $newSpec
- * @param array $spec
- * @param int $goods_id
- */
- protected function processSkuData($skus, $newSpec, $spec, $goods_id)
- {
- $existingSkus = $this->sku_model->where('goods_id', $goods_id)->select();
- $newSkuData = [];
-
- foreach ($skus as $k => $sk) {
- $newSkuId = $this->getSkuId($sk['skus'], $newSpec, $spec);
- $skuAttr = $this->generateSkuAttr($sk['skus'], $newSpec, $spec);
-
- $skuData = $this->buildMultiSkuData($sk, $goods_id, $newSkuId, $skuAttr);
-
- if (isset($existingSkus[$k])) {
- $existingSku = $existingSkus[$k];
- $oldSkuId = $this->normalizeSkuId($existingSku['spec_value_ids']);
-
- if ($oldSkuId == $newSkuId) {
- // 规格匹配,更新数据
- $skuData['sales'] = $existingSku->sales; // 保持原有销量
- $existingSku->save($skuData);
- } else {
- // 规格不匹配,重置销量
- $skuData['sales'] = 0;
- $existingSku->save($skuData);
- }
- unset($existingSkus[$k]);
- } else {
- // 新增SKU
- $skuData['sales'] = 0;
- $newSkuData[] = $skuData;
- }
- }
-
- if (!empty($newSkuData)) {
- $this->sku_model->saveAll($newSkuData);
- }
- }
-
- /**
- * 构建多规格SKU数据
- * @param array $skuData
- * @param int $goods_id
- * @param string $specValueIds
- * @param string $skuAttr
- * @return array
- */
- protected function buildMultiSkuData($skuData, $goods_id, $specValueIds, $skuAttr)
- {
- return [
- 'goods_id' => $goods_id,
- 'spec_value_ids' => $specValueIds,
- 'sku_attr' => $skuAttr,
- 'sku_sn' => $skuData['sku_sn'] ?? '',
- 'image' => $skuData['image'] ?? '',
- 'price' => floatval($skuData['price'] ?? 0),
- 'lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
- 'cost_price' => floatval($skuData['cost_price'] ?? 0),
- 'weight' => floatval($skuData['weight'] ?? 0),
- 'volume' => floatval($skuData['volume'] ?? 0),
- 'stocks' => intval($skuData['stocks'] ?? 0),
- 'status' => isset($skuData['status']) ? intval($skuData['status']) : 1,
- 'is_default' => isset($skuData['is_default']) ? intval($skuData['is_default']) : 0,
- ];
- }
-
- /**
- * 规范化SKU ID字符串
- * @param string $skuIds
- * @return string
- */
- protected function normalizeSkuId($skuIds)
- {
- $idsArray = explode(',', $skuIds);
- sort($idsArray);
- return implode(',', $idsArray);
- }
-
- /**
- * 处理默认SKU
- * @param array $skus
- * @param int $goods_id
- * @return int
- */
- protected function processDefaultSku($skus, $goods_id)
- {
- $defaultSkuId = 0;
- $hasDefault = false;
-
- // 检查是否有明确设置的默认SKU
- foreach ($skus as $sku) {
- if (isset($sku['is_default']) && $sku['is_default']) {
- $hasDefault = true;
- break;
- }
- }
-
- if (!$hasDefault && !empty($skus)) {
- // 如果没有明确设置默认SKU,则使用第一个有效SKU作为默认
- $firstValidSku = $this->sku_model->where('goods_id', $goods_id)
- ->where('status', 1)
- ->order('id', 'asc')
- ->find();
- if ($firstValidSku) {
- $firstValidSku->save(['is_default' => 1]);
- $defaultSkuId = $firstValidSku->id;
- }
- } else {
- // 查找默认SKU的ID
- $defaultSku = $this->sku_model->where('goods_id', $goods_id)
- ->where('is_default', 1)
- ->find();
- if ($defaultSku) {
- $defaultSkuId = $defaultSku->id;
- }
- }
-
- return $defaultSkuId;
- }
-
- /**
- * 更新商品主表信息(多规格)
- * @param array $skus
- * @param int $goods_id
- * @param int $defaultSkuId
- */
- protected function updateGoodsForMultiSpec($skus, $goods_id, $defaultSkuId)
- {
- if (empty($skus)) {
- $this->model->where('id', $goods_id)->update(['spec_type' => 0]);
- return;
- }
-
- // 计算价格范围和库存
- $priceStats = $this->calculatePriceStats($skus);
- $totalStocks = $this->calculateTotalStocks($skus);
-
- $updateData = [
- 'stocks' => $totalStocks,
- 'spec_type' => 1,
- 'min_price' => $priceStats['min_price'],
- 'max_price' => $priceStats['max_price'],
- 'price' => $priceStats['avg_price'],
- 'min_lineation_price'=> $priceStats['min_lineation_price'],
- 'max_lineation_price'=> $priceStats['max_lineation_price'],
- 'lineation_price' => $priceStats['avg_lineation_price'],
- ];
-
- if ($defaultSkuId > 0) {
- $updateData['default_sku_id'] = $defaultSkuId;
- }
-
- $this->model->where('id', $goods_id)->update($updateData);
- }
-
- /**
- * 计算价格统计信息
- * @param array $skus
- * @return array
- */
- protected function calculatePriceStats($skus)
- {
- $prices = array_column($skus, 'price');
- $lineationPrices = array_filter(array_column($skus, 'lineation_price'), function($price) {
- return $price > 0;
- });
-
- // 计算平均价格
- $validPrices = array_filter($prices, function($price) { return $price > 0; });
- $avgPrice = !empty($validPrices) ? array_sum($validPrices) / count($validPrices) : 0;
-
- // 计算平均划线价格
- $avgLineationPrice = !empty($lineationPrices) ? array_sum($lineationPrices) / count($lineationPrices) : 0;
-
- return [
- 'min_price' => !empty($prices) ? min($prices) : 0,
- 'max_price' => !empty($prices) ? max($prices) : 0,
- 'avg_price' => round($avgPrice, 2),
- 'min_lineation_price' => !empty($lineationPrices) ? min($lineationPrices) : 0,
- 'max_lineation_price' => !empty($lineationPrices) ? max($lineationPrices) : 0,
- 'avg_lineation_price' => round($avgLineationPrice, 2),
- ];
- }
-
- /**
- * 计算总库存
- * @param array $skus
- * @return int
- */
- protected function calculateTotalStocks($skus)
- {
- $totalStocks = 0;
- foreach ($skus as $sku) {
- $totalStocks += intval($sku['stocks'] ?? 0);
- }
- return $totalStocks;
- }
-
- /**
- * 清理无用的SKU记录
- * @param int $goods_id
- * @param int $currentSkuCount
- */
- protected function cleanupUnusedSkus($goods_id, $currentSkuCount)
- {
- // 删除多余的SKU记录(保留当前SKU数量)
- $allSkus = $this->sku_model->where('goods_id', $goods_id)->order('id', 'asc')->select();
- if (count($allSkus) > $currentSkuCount) {
- $skusToDelete = array_slice($allSkus->toArray(), $currentSkuCount);
- foreach ($skusToDelete as $sku) {
- $this->sku_model->where('id', $sku['id'])->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('复制失败:系统错误');
- }
- }
- }
|