Goods.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. <?php
  2. namespace app\admin\controller\shop;
  3. use app\common\controller\Backend;
  4. use Exception;
  5. use think\Db;
  6. use think\exception\PDOException;
  7. use think\exception\ValidateException;
  8. use app\admin\model\shop\GoodsAttr;
  9. use app\admin\model\shop\Spec;
  10. use app\admin\model\shop\GoodsSkuSpec;
  11. use app\common\Enum\GoodsEnum;
  12. use app\common\Service\SkuSpec as SkuSpecService;
  13. use app\common\Enum\StatusEnum;
  14. use app\common\Service\DiscountService;
  15. /**
  16. * 商品管理
  17. *
  18. * @icon fa fa-circle-o
  19. */
  20. class Goods extends Backend
  21. {
  22. /**
  23. * 快速搜索时执行查找的字段
  24. */
  25. protected $searchFields = 'id,goods_sn,title,subtitle';
  26. /**
  27. * Goods模型对象
  28. * @var \app\admin\model\shop\Goods
  29. */
  30. protected $model = null;
  31. protected $sku_model = null;
  32. public function _initialize()
  33. {
  34. parent::_initialize();
  35. $this->model = new \app\admin\model\shop\Goods;
  36. $this->sku_model = new \app\admin\model\shop\GoodsSku;
  37. // $this->view->assign("flagList", $this->model->getFlagList());
  38. // $this->view->assign("statusList", $this->model->getStatusList());
  39. $this->view->assign("goodsTypeList", GoodsEnum::getGoodsTypeMap());
  40. $this->assignconfig("goodsTypeList", json_encode(GoodsEnum::getGoodsTypeMap()));
  41. $this->view->assign("statusList", GoodsEnum::getGoodsStatusMap());
  42. $this->assignconfig("statusList", json_encode(GoodsEnum::getGoodsStatusMap()));
  43. $this->view->assign("specTypeList", GoodsEnum::getSpecTypeMap());
  44. $this->assignconfig("specTypeList", json_encode(GoodsEnum::getSpecTypeMap()));
  45. $this->view->assign("deliveryTypeList", GoodsEnum::getDeliveryTypeMap());
  46. $this->view->assign("onlineTypeList", GoodsEnum::getOnlineTypeMap());
  47. $this->view->assign("expressTypeList", GoodsEnum::getExpressTypeMap());
  48. $this->view->assign("stockShowTypeList", GoodsEnum::getStockShowTypeMap());
  49. $this->view->assign("salesShowTypeList", GoodsEnum::getSalesShowTypeMap());
  50. $this->view->assign("yesNoList", StatusEnum::getYesNoMap());
  51. }
  52. /**
  53. * 检查商品编码是否重复
  54. */
  55. public function checkGoodsSn()
  56. {
  57. $goods_sn = $this->request->param('goods_sn');
  58. $id = $this->request->param('id', 0);
  59. if (empty($goods_sn)) {
  60. $this->error('商品编码不能为空');
  61. }
  62. $where = [['goods_sn', '=', $goods_sn]];
  63. if ($id > 0) {
  64. $where[] = ['id', '<>', $id];
  65. }
  66. $exists = $this->model->where($where)->find();
  67. if ($exists) {
  68. $this->error('商品编码已存在');
  69. }
  70. $this->success('商品编码可用');
  71. }
  72. /**
  73. * 查看
  74. */
  75. public function index()
  76. {
  77. //设置过滤方法
  78. $this->request->filter(['strip_tags', 'trim']);
  79. if ($this->request->isAjax()) {
  80. //如果发送的来源是Selectpage,则转发到Selectpage
  81. if ($this->request->request('keyField')) {
  82. return $this->selectpage();
  83. }
  84. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  85. $list = $this->model
  86. ->with(['Freight', 'Brand', 'Category'])
  87. ->where($where)
  88. ->order($sort, $order)
  89. ->paginate($limit);
  90. // 查询是否有折扣活动 根据ID
  91. $arrGoodsId = $list->column('id');
  92. // 获取商品与活动的映射关系
  93. $goodsActivityMapping = DiscountService::getGoodsActivityMapping($arrGoodsId);
  94. // 为每个商品添加活动信息
  95. $list->each(function(&$goods) use ($goodsActivityMapping) {
  96. $activityData = $goodsActivityMapping[$goods['id']] ?? null;
  97. if ($activityData) {
  98. $goods['activity_name'] = $activityData['name'] ?? '';
  99. $goods['activity_id'] = $activityData['id'] ?? 0;
  100. $goods['activity_type'] = $activityData['activity_type'] ?? '';
  101. $goods['activity_status'] = '进行中';
  102. } else {
  103. $goods['activity_name'] = '';
  104. $goods['activity_id'] = 0;
  105. $goods['activity_type'] = '';
  106. $goods['activity_status'] = '无活动';
  107. }
  108. });
  109. $result = array("total" => $list->total(), "rows" => $list->items());
  110. return json($result);
  111. }
  112. return $this->view->fetch();
  113. }
  114. /**
  115. * 查看
  116. */
  117. public function select()
  118. {
  119. //设置过滤方法
  120. $this->request->filter(['strip_tags', 'trim']);
  121. if ($this->request->isAjax()) {
  122. //如果发送的来源是Selectpage,则转发到Selectpage
  123. if ($this->request->request('keyField')) {
  124. return $this->selectpage();
  125. }
  126. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  127. $list = $this->model
  128. ->with(['Freight', 'Brand', 'Category'])
  129. ->where($where)
  130. ->order($sort, $order)
  131. ->paginate($limit);
  132. // 为每个商品添加SKU信息
  133. $items = $list->items();
  134. foreach ($items as &$item) {
  135. // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
  136. $sku = \app\common\model\Sku::where('goods_id', $item['id'])->find();
  137. $item['sku_id'] = $sku ? $sku['id'] : 0;
  138. }
  139. $result = array("total" => $list->total(), "rows" => $items);
  140. return json($result);
  141. }
  142. return $this->view->fetch();
  143. }
  144. //检查属性skus 和 spec 是否对上
  145. protected function checkSku($skus, $spec)
  146. {
  147. foreach ($skus as $item) {
  148. if (!isset($item['skus']) || !is_array($item['skus']) || empty($item['skus'])) {
  149. throw new Exception('规格属性不能为空');
  150. }
  151. if (!isset($item['price'])) {
  152. throw new Exception('请录入价格');
  153. }
  154. foreach ($item['skus'] as $k => $v) {
  155. if (empty($v) && !is_numeric($v)) {
  156. throw new Exception('规格【' . $v . '】属性值不能为空');
  157. }
  158. if (!isset($spec[$k]['value']) || (empty($spec[$k]['name']) && !is_numeric($spec[$k]['name']))) {
  159. throw new Exception('规格【' . $v . '】名称不能为空');
  160. }
  161. foreach ($spec[$k]['value'] as $m => $n) {
  162. // 兼容新格式(对象)和旧格式(字符串)
  163. $valueText = is_array($n) ? $n['name'] : $n;
  164. if (stripos($valueText, ',') !== false) {
  165. throw new Exception('规格【' . $v . '】属性值中不能包含,');
  166. }
  167. }
  168. // 检查重复值(提取name字段进行比较)
  169. $valueNames = array_map(function($n) {
  170. return is_array($n) ? $n['name'] : $n;
  171. }, $spec[$k]['value']);
  172. if (count($valueNames) != count(array_unique($valueNames))) {
  173. throw new Exception('规格【' . $v . '】属性值中不能有重复值');
  174. }
  175. // 检查规格值是否匹配(支持新旧格式)
  176. $valueNames = array_map(function($n) {
  177. return is_array($n) ? $n['name'] : $n;
  178. }, $spec[$k]['value']);
  179. if (empty($spec[$k]['value']) || !in_array($v, $valueNames)) {
  180. throw new Exception('规格【' . $v . '】属性不匹配');
  181. }
  182. }
  183. }
  184. }
  185. protected function getSkuId($skus, $newSpec, $spec)
  186. {
  187. $arr = [];
  188. foreach ($skus as $index => $item) {
  189. $specArr = $spec[$index];
  190. foreach ($newSpec as $subindex => $subitem) {
  191. if ($subitem['spec_name'] == $specArr['name'] && $subitem['spec_value_value'] == $item) {
  192. $arr[] = $subitem['id'];
  193. }
  194. }
  195. }
  196. sort($arr);
  197. return implode(',', $arr);
  198. }
  199. /**
  200. * 生成SKU属性JSON字符串
  201. * @param array $skus 当前SKU的规格值数组
  202. * @param array $newSpec 规格映射数据
  203. * @param array $spec 规格原始数据
  204. * @return string JSON格式的SKU属性字符串
  205. */
  206. protected function generateSkuAttr($skus, $newSpec, $spec)
  207. {
  208. $skuAttr = [];
  209. foreach ($skus as $index => $item) {
  210. $specArr = $spec[$index];
  211. foreach ($newSpec as $subindex => $subitem) {
  212. if ($subitem['spec_name'] == $specArr['name'] && $subitem['spec_value_value'] == $item) {
  213. $skuAttr[] = [
  214. 'key' => $subitem['spec_name'],
  215. 'value' => $subitem['spec_value_value'],
  216. 'key_id' => $subitem['spec_id'],
  217. 'value_id' => $subitem['spec_value_id'],
  218. 'type' => $specArr['type'] ?? 'basic' // 增加规格类型字段
  219. ];
  220. break;
  221. }
  222. }
  223. }
  224. return json_encode($skuAttr, JSON_UNESCAPED_UNICODE);
  225. }
  226. /**
  227. * 根据上下架时间计算商品状态
  228. * @param array $params 商品参数
  229. * @return int 商品状态
  230. */
  231. protected function calculateGoodsStatus($params)
  232. {
  233. $currentTime = time();
  234. // 获取上架时间设置 - 前端传递的上架类型字段(使用status字段)
  235. $onlineType = isset($params['status']) ? intval($params['status']) : GoodsEnum::ONLINE_TYPE_NOT_NOW;
  236. $scheduledOnlineTime = isset($params['scheduled_online_time']) ? strtotime($params['scheduled_online_time']) : 0;
  237. // 获取下架时间设置
  238. $isAutoOffline = isset($params['is_auto_offline']) ? intval($params['is_auto_offline']) : 0;
  239. $scheduledOfflineTime = isset($params['scheduled_offline_time']) ? strtotime($params['scheduled_offline_time']) : 0;
  240. // 根据上架类型判断状态
  241. switch ($onlineType) {
  242. case GoodsEnum::ONLINE_TYPE_IMMEDIATE: // 立即上架
  243. // 检查是否需要自动下架
  244. if ($isAutoOffline && $scheduledOfflineTime > 0) {
  245. if ($currentTime >= $scheduledOfflineTime) {
  246. return GoodsEnum::STATUS_OFF_SALE; // 已下架
  247. }
  248. }
  249. return GoodsEnum::STATUS_ON_SALE; // 销售中
  250. case GoodsEnum::ONLINE_TYPE_NOT_NOW: // 暂不上架
  251. return GoodsEnum::STATUS_IN_STORAGE; // 仓库中
  252. case GoodsEnum::ONLINE_TYPE_SCHEDULED: // 定时上架
  253. if ($scheduledOnlineTime <= 0) {
  254. return GoodsEnum::STATUS_IN_STORAGE; // 未设置上架时间,保持仓库中
  255. }
  256. if ($currentTime < $scheduledOnlineTime) {
  257. return GoodsEnum::STATUS_IN_STORAGE; // 未到上架时间,仓库中
  258. }
  259. // 已到上架时间,检查下架时间
  260. if ($isAutoOffline && $scheduledOfflineTime > 0) {
  261. if ($currentTime >= $scheduledOfflineTime) {
  262. return GoodsEnum::STATUS_OFF_SALE; // 已下架
  263. }
  264. }
  265. return GoodsEnum::STATUS_ON_SALE; // 销售中
  266. default:
  267. return GoodsEnum::STATUS_IN_STORAGE; // 默认仓库中
  268. }
  269. }
  270. /**
  271. * 处理商品SKU(统一处理单规格和多规格)
  272. * @param array $params 商品参数
  273. * @param int $goods_id 商品ID
  274. * @throws \Exception
  275. */
  276. protected function processGoodsSku($params, $goods_id)
  277. {
  278. // 统一通过skus和spec字段处理
  279. if (!isset($params['skus']) || !isset($params['spec'])) {
  280. throw new \Exception('SKU数据格式错误');
  281. }
  282. $skus = (array)json_decode($params['skus'], true);
  283. $spec = (array)json_decode($params['spec'], true);
  284. if (empty($skus)) {
  285. throw new \Exception('SKU数据不能为空');
  286. }
  287. // 判断是单规格还是多规格
  288. if (empty($spec) && count($skus) === 1) {
  289. // 单规格处理
  290. $this->processSingleSpecSku($skus[0], $goods_id);
  291. } else {
  292. // 多规格处理
  293. $this->processMultiSpecSku($skus, $spec, $goods_id);
  294. }
  295. }
  296. /**
  297. * 处理单规格商品SKU
  298. * @param array $skuData SKU数据
  299. * @param int $goods_id 商品ID
  300. */
  301. protected function processSingleSpecSku($skuData, $goods_id)
  302. {
  303. // 验证单规格SKU数据
  304. $this->validateSingleSpecSku($skuData);
  305. // 如果原来是多规格,先清理多余的SKU记录和规格关联
  306. $existingSkuCount = $this->sku_model->where('goods_id', $goods_id)->count();
  307. if ($existingSkuCount > 1) {
  308. // 从多规格改为单规格,删除所有旧记录
  309. $this->sku_model->where('goods_id', $goods_id)->delete();
  310. // 删除规格关联数据
  311. Db::name('shop_goods_sku_spec')->where('goods_id', $goods_id)->delete();
  312. }
  313. // 查询现有的SKU记录
  314. $existingSku = $this->sku_model->where('goods_id', $goods_id)->find();
  315. // 创建单规格SKU数据
  316. $newSkuData = $this->buildSingleSkuData($skuData, $goods_id);
  317. $defaultSkuId = 0;
  318. if ($existingSku) {
  319. // 单规格商品已存在SKU记录,直接更新(保持ID和销量不变)
  320. $newSkuData['sales'] = $existingSku->sales; // 保持原有销量
  321. $existingSku->save($newSkuData);
  322. $defaultSkuId = $existingSku->id;
  323. } else {
  324. // 新商品,创建SKU记录
  325. $newSkuData['sales'] = 0;
  326. $newSku = $this->sku_model->create($newSkuData);
  327. $defaultSkuId = $newSku->id;
  328. }
  329. // 更新商品主表信息
  330. $this->updateGoodsForSingleSpec($skuData, $goods_id, $defaultSkuId);
  331. }
  332. /**
  333. * 验证单规格SKU数据
  334. * @param array $skuData
  335. * @throws \Exception
  336. */
  337. protected function validateSingleSpecSku($skuData)
  338. {
  339. if (!isset($skuData['price']) || floatval($skuData['price']) <= 0) {
  340. throw new \Exception('单规格商品销售价必须大于0');
  341. }
  342. if (!isset($skuData['stocks']) || intval($skuData['stocks']) <= 0) {
  343. throw new \Exception('单规格商品库存必须大于0');
  344. }
  345. }
  346. /**
  347. * 构建单规格SKU数据
  348. * @param array $skuData
  349. * @param int $goods_id
  350. * @return array
  351. */
  352. protected function buildSingleSkuData($skuData, $goods_id)
  353. {
  354. return [
  355. 'goods_id' => $goods_id,
  356. 'spec_value_ids' => '', // 单规格无规格值ID
  357. 'sku_attr' => '', // 单规格无规格属性
  358. 'sku_sn' => $skuData['sku_sn'] ?? '',
  359. 'image' => $skuData['image'] ?? '',
  360. 'price' => floatval($skuData['price'] ?? 0),
  361. 'lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
  362. 'cost_price' => floatval($skuData['cost_price'] ?? 0),
  363. 'weight' => floatval($skuData['weight'] ?? 0),
  364. 'volume' => floatval($skuData['volume'] ?? 0),
  365. 'stocks' => intval($skuData['stocks'] ?? 0),
  366. 'status' => 1,
  367. 'is_default' => 1, // 单规格默认为默认SKU
  368. ];
  369. }
  370. /**
  371. * 更新商品主表信息(单规格)
  372. * @param array $skuData
  373. * @param int $goods_id
  374. * @param int $defaultSkuId
  375. */
  376. protected function updateGoodsForSingleSpec($skuData, $goods_id, $defaultSkuId)
  377. {
  378. $updateData = [
  379. 'spec_type' => 0, // 单规格
  380. 'stocks' => intval($skuData['stocks'] ?? 0),
  381. 'min_price' => floatval($skuData['price'] ?? 0),
  382. 'max_price' => floatval($skuData['price'] ?? 0),
  383. 'price' => floatval($skuData['price'] ?? 0),
  384. 'min_lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
  385. 'max_lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
  386. 'lineation_price' => floatval($skuData['lineation_price'] ?? 0),
  387. 'default_sku_id' => $defaultSkuId,
  388. ];
  389. $this->model->where('id', $goods_id)->update($updateData);
  390. }
  391. /**
  392. * 处理多规格商品SKU
  393. * @param array $skus SKU数据数组
  394. * @param array $spec 规格数据数组
  395. * @param int $goods_id 商品ID
  396. */
  397. protected function processMultiSpecSku($skus, $spec, $goods_id)
  398. {
  399. // 验证多规格数据
  400. $this->validateMultiSpecSku($skus, $spec);
  401. // 规格属性入库,传递规格类型信息
  402. $specList = Spec::push($spec);
  403. $newSpec = GoodsSkuSpec::push($specList, $goods_id, $spec);
  404. // 处理SKU数据
  405. $this->processSkuData($skus, $newSpec, $spec, $goods_id);
  406. // 处理默认SKU
  407. $defaultSkuId = $this->processDefaultSku($skus, $goods_id);
  408. // 更新商品主表信息
  409. $this->updateGoodsForMultiSpec($skus, $goods_id, $defaultSkuId);
  410. // 清理无用的SKU记录
  411. $this->cleanupUnusedSkus($goods_id, count($skus));
  412. }
  413. /**
  414. * 验证多规格SKU数据
  415. * @param array $skus
  416. * @param array $spec
  417. * @throws \Exception
  418. */
  419. protected function validateMultiSpecSku($skus, $spec)
  420. {
  421. if (empty($spec)) {
  422. throw new \Exception('多规格商品必须设置规格信息');
  423. }
  424. // 验证是否有有效的SKU
  425. $hasValidSku = false;
  426. foreach ($skus as $sku) {
  427. if (isset($sku['status']) && ($sku['status'] == 1 || $sku['status'] === '1')) {
  428. $hasValidSku = true;
  429. if (!isset($sku['price']) || floatval($sku['price']) <= 0) {
  430. throw new \Exception('SKU销售价必须大于0');
  431. }
  432. if (!isset($sku['stocks']) || intval($sku['stocks']) <= 0) {
  433. throw new \Exception('SKU库存必须大于0');
  434. }
  435. }
  436. }
  437. if (!$hasValidSku) {
  438. throw new \Exception('多规格商品至少需要一个有效的SKU');
  439. }
  440. }
  441. /**
  442. * 处理SKU数据
  443. * @param array $skus
  444. * @param array $newSpec
  445. * @param array $spec
  446. * @param int $goods_id
  447. */
  448. protected function processSkuData($skus, $newSpec, $spec, $goods_id)
  449. {
  450. $existingSkus = $this->sku_model->where('goods_id', $goods_id)->select();
  451. $newSkuData = [];
  452. foreach ($skus as $k => $sk) {
  453. $newSkuId = $this->getSkuId($sk['skus'], $newSpec, $spec);
  454. $skuAttr = $this->generateSkuAttr($sk['skus'], $newSpec, $spec);
  455. $skuData = $this->buildMultiSkuData($sk, $goods_id, $newSkuId, $skuAttr);
  456. if (isset($existingSkus[$k])) {
  457. $existingSku = $existingSkus[$k];
  458. $oldSkuId = $this->normalizeSkuId($existingSku['spec_value_ids']);
  459. if ($oldSkuId == $newSkuId) {
  460. // 规格匹配,更新数据
  461. $skuData['sales'] = $existingSku->sales; // 保持原有销量
  462. $existingSku->save($skuData);
  463. } else {
  464. // 规格不匹配,重置销量
  465. $skuData['sales'] = 0;
  466. $existingSku->save($skuData);
  467. }
  468. unset($existingSkus[$k]);
  469. } else {
  470. // 新增SKU
  471. $skuData['sales'] = 0;
  472. $newSkuData[] = $skuData;
  473. }
  474. }
  475. if (!empty($newSkuData)) {
  476. $this->sku_model->saveAll($newSkuData);
  477. }
  478. }
  479. /**
  480. * 构建多规格SKU数据
  481. * @param array $skuData
  482. * @param int $goods_id
  483. * @param string $specValueIds
  484. * @param string $skuAttr
  485. * @return array
  486. */
  487. protected function buildMultiSkuData($skuData, $goods_id, $specValueIds, $skuAttr)
  488. {
  489. return [
  490. 'goods_id' => $goods_id,
  491. 'spec_value_ids' => $specValueIds,
  492. 'sku_attr' => $skuAttr,
  493. 'sku_sn' => $skuData['sku_sn'] ?? '',
  494. 'image' => $skuData['image'] ?? '',
  495. 'price' => floatval($skuData['price'] ?? 0),
  496. 'lineation_price'=> floatval($skuData['lineation_price'] ?? 0),
  497. 'cost_price' => floatval($skuData['cost_price'] ?? 0),
  498. 'weight' => floatval($skuData['weight'] ?? 0),
  499. 'volume' => floatval($skuData['volume'] ?? 0),
  500. 'stocks' => intval($skuData['stocks'] ?? 0),
  501. 'status' => isset($skuData['status']) ? intval($skuData['status']) : 1,
  502. 'is_default' => isset($skuData['is_default']) ? intval($skuData['is_default']) : 0,
  503. ];
  504. }
  505. /**
  506. * 规范化SKU ID字符串
  507. * @param string $skuIds
  508. * @return string
  509. */
  510. protected function normalizeSkuId($skuIds)
  511. {
  512. $idsArray = explode(',', $skuIds);
  513. sort($idsArray);
  514. return implode(',', $idsArray);
  515. }
  516. /**
  517. * 处理默认SKU
  518. * @param array $skus
  519. * @param int $goods_id
  520. * @return int
  521. */
  522. protected function processDefaultSku($skus, $goods_id)
  523. {
  524. $defaultSkuId = 0;
  525. $hasDefault = false;
  526. // 检查是否有明确设置的默认SKU
  527. foreach ($skus as $sku) {
  528. if (isset($sku['is_default']) && $sku['is_default']) {
  529. $hasDefault = true;
  530. break;
  531. }
  532. }
  533. if (!$hasDefault && !empty($skus)) {
  534. // 如果没有明确设置默认SKU,则使用第一个有效SKU作为默认
  535. $firstValidSku = $this->sku_model->where('goods_id', $goods_id)
  536. ->where('status', 1)
  537. ->order('id', 'asc')
  538. ->find();
  539. if ($firstValidSku) {
  540. $firstValidSku->save(['is_default' => 1]);
  541. $defaultSkuId = $firstValidSku->id;
  542. }
  543. } else {
  544. // 查找默认SKU的ID
  545. $defaultSku = $this->sku_model->where('goods_id', $goods_id)
  546. ->where('is_default', 1)
  547. ->find();
  548. if ($defaultSku) {
  549. $defaultSkuId = $defaultSku->id;
  550. }
  551. }
  552. return $defaultSkuId;
  553. }
  554. /**
  555. * 更新商品主表信息(多规格)
  556. * @param array $skus
  557. * @param int $goods_id
  558. * @param int $defaultSkuId
  559. */
  560. protected function updateGoodsForMultiSpec($skus, $goods_id, $defaultSkuId)
  561. {
  562. if (empty($skus)) {
  563. $this->model->where('id', $goods_id)->update(['spec_type' => 0]);
  564. return;
  565. }
  566. // 计算价格范围和库存
  567. $priceStats = $this->calculatePriceStats($skus);
  568. $totalStocks = $this->calculateTotalStocks($skus);
  569. $updateData = [
  570. 'stocks' => $totalStocks,
  571. 'spec_type' => 1,
  572. 'min_price' => $priceStats['min_price'],
  573. 'max_price' => $priceStats['max_price'],
  574. 'price' => $priceStats['avg_price'],
  575. 'min_lineation_price'=> $priceStats['min_lineation_price'],
  576. 'max_lineation_price'=> $priceStats['max_lineation_price'],
  577. 'lineation_price' => $priceStats['avg_lineation_price'],
  578. ];
  579. if ($defaultSkuId > 0) {
  580. $updateData['default_sku_id'] = $defaultSkuId;
  581. }
  582. $this->model->where('id', $goods_id)->update($updateData);
  583. }
  584. /**
  585. * 计算价格统计信息
  586. * @param array $skus
  587. * @return array
  588. */
  589. protected function calculatePriceStats($skus)
  590. {
  591. $prices = array_column($skus, 'price');
  592. $lineationPrices = array_filter(array_column($skus, 'lineation_price'), function($price) {
  593. return $price > 0;
  594. });
  595. // 计算平均价格
  596. $validPrices = array_filter($prices, function($price) { return $price > 0; });
  597. $avgPrice = !empty($validPrices) ? array_sum($validPrices) / count($validPrices) : 0;
  598. // 计算平均划线价格
  599. $avgLineationPrice = !empty($lineationPrices) ? array_sum($lineationPrices) / count($lineationPrices) : 0;
  600. return [
  601. 'min_price' => !empty($prices) ? min($prices) : 0,
  602. 'max_price' => !empty($prices) ? max($prices) : 0,
  603. 'avg_price' => round($avgPrice, 2),
  604. 'min_lineation_price' => !empty($lineationPrices) ? min($lineationPrices) : 0,
  605. 'max_lineation_price' => !empty($lineationPrices) ? max($lineationPrices) : 0,
  606. 'avg_lineation_price' => round($avgLineationPrice, 2),
  607. ];
  608. }
  609. /**
  610. * 计算总库存
  611. * @param array $skus
  612. * @return int
  613. */
  614. protected function calculateTotalStocks($skus)
  615. {
  616. $totalStocks = 0;
  617. foreach ($skus as $sku) {
  618. $totalStocks += intval($sku['stocks'] ?? 0);
  619. }
  620. return $totalStocks;
  621. }
  622. /**
  623. * 清理无用的SKU记录
  624. * @param int $goods_id
  625. * @param int $currentSkuCount
  626. */
  627. protected function cleanupUnusedSkus($goods_id, $currentSkuCount)
  628. {
  629. // 删除多余的SKU记录(保留当前SKU数量)
  630. $allSkus = $this->sku_model->where('goods_id', $goods_id)->order('id', 'asc')->select();
  631. if (count($allSkus) > $currentSkuCount) {
  632. $skusToDelete = array_slice($allSkus->toArray(), $currentSkuCount);
  633. foreach ($skusToDelete as $sku) {
  634. $this->sku_model->where('id', $sku['id'])->delete();
  635. }
  636. }
  637. }
  638. /**
  639. * 添加
  640. */
  641. public function add()
  642. {
  643. if ($this->request->isPost()) {
  644. $params = $this->request->post("row/a");
  645. if ($params) {
  646. $params = $this->preExcludeFields($params);
  647. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  648. $params[$this->dataLimitField] = $this->auth->id;
  649. }
  650. $result = false;
  651. Db::startTrans();
  652. try {
  653. //是否采用模型验证
  654. if ($this->modelValidate) {
  655. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  656. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  657. // 添加规格数据到验证参数中
  658. if (isset($params['skus']) && isset($params['spec'])) {
  659. $params['spec_data'] = json_decode($params['spec'], true);
  660. $params['sku_data'] = json_decode($params['skus'], true);
  661. }
  662. $this->model->validateFailException(true)->validate($validate);
  663. }
  664. // 备份上架类型,因为status字段将被覆盖为最终状态
  665. $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
  666. // 将online_type映射到status字段用于计算
  667. if (isset($params['online_type'])) {
  668. $params['status'] = $params['online_type'];
  669. unset($params['online_type']);
  670. }
  671. // 先保存商品基础信息(暂时不保存status字段)
  672. $statusBackup = $params['status'] ?? null;
  673. unset($params['status']); // 临时移除status避免冲突
  674. $result = $this->model->allowField(true)->save($params);
  675. // 根据上下架时间自动计算商品状态并更新
  676. $params['status'] = $statusBackup; // 恢复用于计算
  677. $calculatedStatus = $this->calculateGoodsStatus($params);
  678. $this->model->where('id', $this->model->id)->update([
  679. 'status' => $calculatedStatus,
  680. 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
  681. ]);
  682. // 调试输出
  683. \think\Log::write('商品添加 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
  684. //商品规格处理
  685. if (isset($params['skus']) && isset($params['spec'])) {
  686. $skus = (array)json_decode($params['skus'], true);
  687. $spec = (array)json_decode($params['spec'], true);
  688. // 只对多规格进行checkSku验证
  689. if (!empty($spec)) {
  690. $this->checkSku($skus, $spec);
  691. }
  692. // 统一处理SKU
  693. $this->processGoodsSku($params, $this->model->id);
  694. } else {
  695. throw new \Exception('商品规格数据不能为空');
  696. }
  697. //商品属性
  698. if (isset($params['attribute_ids'])) {
  699. GoodsAttr::addGoodsAttr($params['attribute_ids'], $this->model->id);
  700. }
  701. Db::commit();
  702. } catch (ValidateException $e) {
  703. Db::rollback();
  704. $this->error($e->getMessage());
  705. } catch (PDOException $e) {
  706. Db::rollback();
  707. $this->error($e->getMessage());
  708. } catch (Exception $e) {
  709. Db::rollback();
  710. $this->error($e->getMessage());
  711. }
  712. if ($result !== false) {
  713. $this->success();
  714. } else {
  715. $this->error(__('No rows were inserted'));
  716. }
  717. }
  718. $this->error(__('Parameter %s can not be empty', ''));
  719. }
  720. return $this->view->fetch();
  721. }
  722. /**
  723. * 编辑
  724. */
  725. public function edit($ids = null)
  726. {
  727. $row = $this->model->find($ids);
  728. if (!$row) {
  729. $this->error(__('No Results were found'));
  730. }
  731. $adminIds = $this->getDataLimitAdminIds();
  732. if (is_array($adminIds)) {
  733. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  734. $this->error(__('You have no permission'));
  735. }
  736. }
  737. if ($this->request->isPost()) {
  738. $params = $this->request->post("row/a");
  739. if ($params) {
  740. $params = $this->preExcludeFields($params);
  741. $result = false;
  742. // 查询该商品是否参与进行中的折扣活动
  743. if (DiscountService::hasActivity($row->id)) {
  744. $this->error('该商品参与了进行中的折扣活动,不能编辑');
  745. }
  746. Db::startTrans();
  747. try {
  748. //是否采用模型验证
  749. if ($this->modelValidate) {
  750. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  751. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  752. // 添加规格数据到验证参数中
  753. if (isset($params['skus']) && isset($params['spec'])) {
  754. $params['spec_data'] = json_decode($params['spec'], true);
  755. $params['sku_data'] = json_decode($params['skus'], true);
  756. }
  757. $row->validateFailException(true)->validate($validate);
  758. }
  759. // 备份上架类型,因为status字段将被覆盖为最终状态
  760. $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
  761. // 将online_type映射到status字段用于计算
  762. if (isset($params['online_type'])) {
  763. $params['status'] = $params['online_type'];
  764. unset($params['online_type']);
  765. }
  766. // 先保存商品基础信息(暂时不保存status字段)
  767. $statusBackup = $params['status'] ?? null;
  768. unset($params['status']); // 临时移除status避免冲突
  769. $result = $row->allowField(true)->save($params);
  770. // 根据上下架时间自动计算商品状态并更新
  771. $params['status'] = $statusBackup; // 恢复用于计算
  772. $calculatedStatus = $this->calculateGoodsStatus($params);
  773. $this->model->where('id', $row->id)->update([
  774. 'status' => $calculatedStatus,
  775. 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
  776. ]);
  777. // 调试输出
  778. \think\Log::write('商品编辑 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
  779. //商品规格处理
  780. if (isset($params['skus']) && isset($params['spec'])) {
  781. $skus = (array)json_decode($params['skus'], true);
  782. $spec = (array)json_decode($params['spec'], true);
  783. // 只对多规格进行checkSku验证
  784. if (!empty($spec)) {
  785. $this->checkSku($skus, $spec);
  786. }
  787. // 统一处理SKU
  788. $this->processGoodsSku($params, $row->id);
  789. } else {
  790. throw new \Exception('商品规格数据不能为空');
  791. }
  792. //商品属性
  793. if (isset($params['attribute_ids'])) {
  794. GoodsAttr::addGoodsAttr($params['attribute_ids'], $row->id);
  795. }
  796. Db::commit();
  797. } catch (ValidateException $e) {
  798. Db::rollback();
  799. $this->error($e->getMessage());
  800. } catch (PDOException $e) {
  801. Db::rollback();
  802. $this->error($e->getMessage());
  803. } catch (Exception $e) {
  804. Db::rollback();
  805. $this->error($e->getMessage());
  806. }
  807. if ($result !== false) {
  808. $this->success();
  809. } else {
  810. $this->error(__('No rows were updated'));
  811. }
  812. }
  813. $this->error(__('Parameter %s can not be empty', ''));
  814. }
  815. // 查询SKU数据
  816. $list = $this->sku_model->where('goods_id', $row->id)->select();
  817. // 构造规格数据结构
  818. $spec_data = [];
  819. $spec_values = []; // 用于传递给前端的规格值完整数据
  820. if ($row->spec_type == 1) { // 多规格商品
  821. // 查询规格和规格值,包含规格类型
  822. $specs = Db::name('shop_goods_sku_spec')
  823. ->alias('gss')
  824. ->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')
  825. ->join('shop_spec sp', 'sp.id = gss.spec_id', 'LEFT')
  826. ->join('shop_spec_value sv', 'sv.id = gss.spec_value_id', 'LEFT')
  827. ->where('gss.goods_id', $row->id)
  828. ->order('sp.id asc, sv.id asc')
  829. ->select();
  830. // 按规格分组
  831. $spec_groups = [];
  832. foreach ($specs as $spec) {
  833. if (!isset($spec_groups[$spec['spec_id']])) {
  834. $spec_groups[$spec['spec_id']]['name'] = $spec['spec_name'];
  835. $spec_groups[$spec['spec_id']]['type'] = $spec['spec_type'] == 2 ? 'custom' : 'basic';
  836. $spec_groups[$spec['spec_id']]['value'] = [];
  837. }
  838. $spec_groups[$spec['spec_id']]['value'][] = [
  839. 'id' => $spec['spec_value_id'],
  840. 'name' => $spec['value'],
  841. 'image' => $spec['image'] ?: '',
  842. 'description' => $spec['desc'] ?: ''
  843. ];
  844. // 构造规格值数据,用于前端初始化
  845. $spec_values[] = [
  846. 'spec_name' => $spec['spec_name'],
  847. 'spec_type' => $spec['spec_type'],
  848. 'value' => $spec['value'],
  849. 'image' => $spec['image'] ?: '',
  850. 'description' => $spec['desc'] ?: ''
  851. ];
  852. }
  853. // 转换为前端需要的格式
  854. foreach ($spec_groups as $spec_id => $spec_info) {
  855. $spec_data[] = [
  856. 'id' => $spec_id,
  857. 'name' => $spec_info['name'],
  858. 'type' => $spec_info['type'],
  859. 'value' => $spec_info['value']
  860. ];
  861. }
  862. }
  863. $this->view->assign("row", $row);
  864. $this->assignconfig('goods', $row);
  865. $this->assignconfig('goods_skus', $list);
  866. $this->assignconfig('spec_data', $spec_data); // 传递规格数据结构
  867. $this->assignconfig('spec_values', $spec_values); // 传递规格值完整数据
  868. return $this->view->fetch();
  869. }
  870. /**
  871. * 获取多个商品信息
  872. */
  873. public function getGoodsByIds()
  874. {
  875. $ids = $this->request->request('ids');
  876. if (!$ids) {
  877. $this->error('请选择商品');
  878. }
  879. $ids = explode(',', $ids);
  880. $list = $this->model
  881. ->with(['Category'])
  882. ->where('id', 'in', $ids)
  883. ->select();
  884. // 处理图片URL和SKU信息
  885. foreach ($list as &$item) {
  886. if ($item['image']) {
  887. $item['image'] = cdnurl($item['image'], true);
  888. }
  889. // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
  890. $sku = \app\common\model\Sku::where('goods_id', $item['id'])->find();
  891. $item['sku_id'] = $sku ? $sku['id'] : 0;
  892. }
  893. $this->success('获取成功', null, $list);
  894. }
  895. /**
  896. * 根据ID批量获取商品信息
  897. */
  898. public function get_goods_by_ids()
  899. {
  900. $ids = $this->request->request('ids');
  901. if (!$ids) {
  902. $this->error('请选择商品');
  903. }
  904. $ids = explode(',', $ids);
  905. $list = $this->model
  906. ->where('id', 'in', $ids)
  907. ->select();
  908. // 转换商品结果为数组
  909. $goodsData = [];
  910. if ($list) {
  911. foreach ($list as $item) {
  912. $goodsData[] = is_array($item) ? $item : $item->toArray();
  913. }
  914. }
  915. // 如果没有商品数据,直接返回空数组
  916. if (empty($goodsData)) {
  917. return json([]);
  918. }
  919. // 一次性查询所有商品的SKU信息
  920. $allSkusResult = Db::name('shop_goods_sku')
  921. ->where('goods_id', 'in', $ids)
  922. ->order('is_default desc, id asc')
  923. ->select();
  924. // 按商品ID分组SKU数据
  925. $skusByGoods = [];
  926. foreach ($allSkusResult as $sku) {
  927. $skuArray = is_array($sku) ? $sku : $sku->toArray();
  928. $skusByGoods[$skuArray['goods_id']][] = $skuArray;
  929. }
  930. // 找出多规格商品ID
  931. $multiSpecGoodsIds = [];
  932. foreach ($goodsData as $item) {
  933. if ($item['spec_type'] == 1) {
  934. $multiSpecGoodsIds[] = $item['id'];
  935. }
  936. }
  937. // 一次性查询所有多规格商品的规格信息
  938. $specsByGoods = [];
  939. if (!empty($multiSpecGoodsIds)) {
  940. $allSpecsResult = Db::name('shop_goods_sku_spec')
  941. ->alias('gss')
  942. ->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')
  943. ->join('shop_spec sp', 'sp.id=gss.spec_id', 'LEFT')
  944. ->join('shop_spec_value sv', 'sv.id=gss.spec_value_id', 'LEFT')
  945. ->where('gss.goods_id', 'in', $multiSpecGoodsIds)
  946. ->order('gss.goods_id asc, sp.id asc, sv.id asc')
  947. ->select();
  948. // 按商品ID分组规格数据
  949. foreach ($allSpecsResult as $spec) {
  950. $specArray = is_array($spec) ? $spec : $spec->toArray();
  951. $specsByGoods[$specArray['goods_id']][] = $specArray;
  952. }
  953. }
  954. // 一次性查询所有SKU的规格属性文本
  955. $allSkuIds = [];
  956. foreach ($skusByGoods as $skus) {
  957. foreach ($skus as $sku) {
  958. $allSkuIds[] = $sku['id'];
  959. }
  960. }
  961. $skuSpecTexts = [];
  962. if (!empty($allSkuIds)) {
  963. $skuSpecResults = Db::name('shop_goods_sku')
  964. ->alias('sku')
  965. ->field('sku.id, GROUP_CONCAT(sp.name,":",sv.value ORDER BY sp.id asc) as specs_text')
  966. ->join('shop_goods_sku_spec gss', "FIND_IN_SET(gss.id, sku.spec_value_ids)", 'LEFT')
  967. ->join('shop_spec sp', 'sp.id=gss.spec_id', 'LEFT')
  968. ->join('shop_spec_value sv', 'sv.id=gss.spec_value_id', 'LEFT')
  969. ->where('sku.id', 'in', $allSkuIds)
  970. ->group('sku.id')
  971. ->select();
  972. foreach ($skuSpecResults as $result) {
  973. $resultArray = is_array($result) ? $result : $result->toArray();
  974. $skuSpecTexts[$resultArray['id']] = $resultArray['specs_text'] ?: '';
  975. }
  976. }
  977. // 处理每个商品的详细信息(纯数据组装,无数据库查询)
  978. foreach ($goodsData as &$item) {
  979. if ($item['image']) {
  980. $item['image'] = cdnurl($item['image'], true);
  981. }
  982. // 获取商品的SKU信息
  983. $skus = $skusByGoods[$item['id']] ?? [];
  984. if ($skus) {
  985. // 获取第一个SKU ID(单规格商品通常只有一个SKU)
  986. $item['sku_id'] = $skus[0]['id'];
  987. // 为每个SKU添加规格属性文本
  988. foreach ($skus as &$sku) {
  989. $sku['specs_text'] = $skuSpecTexts[$sku['id']] ?? '';
  990. }
  991. $item['skus'] = $skus;
  992. // 如果是多规格商品,添加规格数据
  993. if ($item['spec_type'] == 1) {
  994. $specs = $specsByGoods[$item['id']] ?? [];
  995. // 按规格分组构建规格数据结构
  996. $spec_groups = [];
  997. foreach ($specs as $spec) {
  998. if (!isset($spec_groups[$spec['spec_id']])) {
  999. $spec_groups[$spec['spec_id']]['id'] = $spec['spec_id'];
  1000. $spec_groups[$spec['spec_id']]['name'] = $spec['spec_name'];
  1001. $spec_groups[$spec['spec_id']]['type'] = $spec['spec_type'] == 2 ? 'custom' : 'basic';
  1002. $spec_groups[$spec['spec_id']]['value'] = [];
  1003. }
  1004. $spec_groups[$spec['spec_id']]['value'][] = [
  1005. 'id' => $spec['spec_value_id'],
  1006. 'name' => $spec['value'],
  1007. 'image' => $spec['image'] ?: '',
  1008. 'description' => $spec['desc'] ?: ''
  1009. ];
  1010. }
  1011. // 转换为数组格式,与前端渲染一致
  1012. $item['spec'] = array_values($spec_groups);
  1013. } else {
  1014. // 单规格商品,没有spec数据
  1015. $item['spec'] = [];
  1016. }
  1017. } else {
  1018. $item['sku_id'] = 0;
  1019. $item['skus'] = [];
  1020. $item['spec'] = [];
  1021. }
  1022. }
  1023. return json($goodsData);
  1024. }
  1025. /**
  1026. * 复制商品
  1027. */
  1028. public function copy($ids = null)
  1029. {
  1030. $row = $this->model->find($ids);
  1031. if (!$row) {
  1032. $this->error(__('No Results were found'));
  1033. }
  1034. $adminIds = $this->getDataLimitAdminIds();
  1035. if (is_array($adminIds)) {
  1036. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  1037. $this->error(__('You have no permission'));
  1038. }
  1039. }
  1040. Db::startTrans();
  1041. try {
  1042. // 复制商品基本信息
  1043. $goodsData = $row->toArray();
  1044. // 调试输出
  1045. \think\Log::write('开始复制商品,原商品ID: ' . $row->id, 'info');
  1046. // 移除不需要复制的字段
  1047. unset($goodsData['id'], $goodsData['createtime'], $goodsData['updatetime']);
  1048. // 修改商品名称和编码,添加"复制"标识
  1049. $goodsData['title'] = $goodsData['title'] . ' (复制)';
  1050. $goodsData['goods_sn'] = $goodsData['goods_sn'] . '_copy_' . date('YmdHis');
  1051. $goodsData['status'] = \app\common\Enum\GoodsEnum::STATUS_IN_STORAGE; // 复制的商品默认为仓库中状态
  1052. $goodsData['online_type'] = \app\common\Enum\GoodsEnum::ONLINE_TYPE_NOT_NOW; // 暂不上架
  1053. $goodsData['sales'] = 0; // 重置销量
  1054. $goodsData['views'] = 0; // 重置浏览量
  1055. // 创建新商品
  1056. $newGoods = $this->model->create($goodsData);
  1057. $newGoodsId = $newGoods->id;
  1058. // 复制商品SKU信息
  1059. $skuList = $this->sku_model->where('goods_id', $row->id)->select();
  1060. \think\Log::write('查询到SKU数量: ' . ($skuList ? count($skuList) : 0), 'info');
  1061. $newSkuData = [];
  1062. $defaultSkuId = 0;
  1063. if ($skuList && !$skuList->isEmpty()) {
  1064. foreach ($skuList as $sku) {
  1065. $skuData = $sku->toArray();
  1066. unset($skuData['id'], $skuData['createtime'], $skuData['updatetime']);
  1067. $skuData['goods_id'] = $newGoodsId;
  1068. $skuData['sales'] = 0; // 重置销量
  1069. $skuData['sku_sn'] = $skuData['sku_sn'] . '_copy_' . date('YmdHis');
  1070. $newSkuData[] = $skuData;
  1071. }
  1072. }
  1073. if (!empty($newSkuData)) {
  1074. $newSkus = $this->sku_model->saveAll($newSkuData);
  1075. // 获取第一个SKU作为默认SKU
  1076. if (!empty($newSkus)) {
  1077. $defaultSkuId = $newSkus[0]->id;
  1078. }
  1079. } else {
  1080. // 如果没有SKU数据,创建一个默认的SKU
  1081. \think\Log::write('没有找到SKU数据,创建默认SKU', 'info');
  1082. $defaultSkuData = [
  1083. 'goods_id' => $newGoodsId,
  1084. 'spec_value_ids' => '',
  1085. 'sku_attr' => '', // 单规格无规格属性
  1086. 'sku_sn' => $goodsData['goods_sn'] ?? 'SKU_' . date('YmdHis'),
  1087. 'image' => $goodsData['image'] ?? '',
  1088. 'price' => isset($goodsData['price']) ? $goodsData['price'] : 0.01,
  1089. 'lineation_price' => isset($goodsData['lineation_price']) ? $goodsData['lineation_price'] : 0,
  1090. 'cost_price' => 0,
  1091. 'weight' => 0,
  1092. 'volume' => 0,
  1093. 'stocks' => 1,
  1094. 'sales' => 0,
  1095. 'status' => 1,
  1096. 'is_default' => 1,
  1097. ];
  1098. $newSku = $this->sku_model->create($defaultSkuData);
  1099. $defaultSkuId = $newSku->id;
  1100. }
  1101. // 更新商品默认SKU
  1102. if ($defaultSkuId > 0) {
  1103. $newGoods->save(['default_sku_id' => $defaultSkuId]);
  1104. }
  1105. // 复制商品规格信息(如果是多规格商品)
  1106. if ($row->spec_type == 1) {
  1107. // 复制商品规格关联
  1108. $goodsSpecList = Db::name('shop_goods_sku_spec')
  1109. ->where('goods_id', $row->id)
  1110. ->select();
  1111. $newGoodsSpecData = [];
  1112. if ($goodsSpecList && is_array($goodsSpecList) && !empty($goodsSpecList)) {
  1113. foreach ($goodsSpecList as $goodsSpec) {
  1114. $newGoodsSpecData[] = [
  1115. 'goods_id' => $newGoodsId,
  1116. 'spec_id' => $goodsSpec['spec_id'],
  1117. 'spec_value_id' => $goodsSpec['spec_value_id'],
  1118. 'createtime' => time(),
  1119. 'updatetime' => time()
  1120. ];
  1121. }
  1122. }
  1123. if (!empty($newGoodsSpecData)) {
  1124. Db::name('shop_goods_sku_spec')->insertAll($newGoodsSpecData);
  1125. }
  1126. }
  1127. // 复制商品属性信息
  1128. $goodsAttrList = Db::name('shop_goods_attr')
  1129. ->where('goods_id', $row->id)
  1130. ->select();
  1131. $newGoodsAttrData = [];
  1132. if ($goodsAttrList && is_array($goodsAttrList) && !empty($goodsAttrList)) {
  1133. foreach ($goodsAttrList as $goodsAttr) {
  1134. $newGoodsAttrData[] = [
  1135. 'goods_id' => $newGoodsId,
  1136. 'attr_id' => $goodsAttr['attr_id'],
  1137. 'attr_value' => $goodsAttr['attr_value'],
  1138. 'createtime' => time(),
  1139. 'updatetime' => time()
  1140. ];
  1141. }
  1142. }
  1143. if (!empty($newGoodsAttrData)) {
  1144. Db::name('shop_goods_attr')->insertAll($newGoodsAttrData);
  1145. }
  1146. Db::commit();
  1147. \think\Log::write('商品复制成功,新商品ID: ' . $newGoodsId, 'info');
  1148. $this->success('商品复制成功', null, ['goods_id' => $newGoodsId]);
  1149. } catch (Exception $e) {
  1150. Db::rollback();
  1151. \think\Log::write('商品复制失败: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行: ' . $e->getLine(), 'error');
  1152. $this->error('复制失败:' . $e->getMessage());
  1153. } catch (\Throwable $e) {
  1154. Db::rollback();
  1155. \think\Log::write('商品复制出现严重错误: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行: ' . $e->getLine(), 'error');
  1156. $this->error('复制失败:系统错误');
  1157. }
  1158. }
  1159. }