Goods.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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. //处理商品SKU(统一处理单规格和多规格)
  271. protected function processGoodsSku($params, $goods_id)
  272. {
  273. // 统一通过skus和spec字段处理
  274. if (isset($params['skus']) && isset($params['spec'])) {
  275. $skus = (array)json_decode($params['skus'], true);
  276. $spec = (array)json_decode($params['spec'], true);
  277. // 判断是单规格还是多规格
  278. if (empty($spec) && count($skus) === 1) {
  279. // 单规格处理
  280. $this->addSingleSpecSku($skus[0], $goods_id);
  281. } else {
  282. // 多规格处理
  283. $this->addMultiSpecSku($skus, $spec, $goods_id);
  284. }
  285. } else {
  286. throw new \Exception('SKU数据格式错误');
  287. }
  288. }
  289. //添加单规格商品SKU
  290. protected function addSingleSpecSku($skuData, $goods_id)
  291. {
  292. // 如果原来是多规格,先清理多余的SKU记录
  293. $existingSkuCount = $this->sku_model->where('goods_id', $goods_id)->count();
  294. if ($existingSkuCount > 1) {
  295. // 从多规格改为单规格,删除所有旧记录
  296. $this->sku_model->where('goods_id', $goods_id)->delete();
  297. }
  298. // 查询现有的SKU记录
  299. $existingSku = $this->sku_model->where('goods_id', $goods_id)->find();
  300. // 创建单规格SKU数据
  301. $newSkuData = [
  302. 'goods_id' => $goods_id,
  303. 'spec_value_ids' => '', // 单规格无规格值ID
  304. 'sku_attr' => '', // 单规格无规格属性
  305. 'sku_sn' => $skuData['sku_sn'] ?? '',
  306. 'image' => $skuData['image'] ?? '',
  307. 'price' => $skuData['price'] ?? 0,
  308. 'lineation_price'=> $skuData['lineation_price'] ?? 0,
  309. 'cost_price' => $skuData['cost_price'] ?? 0,
  310. 'weight' => $skuData['weight'] ?? 0,
  311. 'volume' => $skuData['volume'] ?? 0,
  312. 'stocks' => $skuData['stocks'] ?? 0,
  313. 'status' => 1,
  314. 'is_default' => 1, // 单规格默认为默认SKU
  315. ];
  316. $defaultSkuId = 0;
  317. if ($existingSku) {
  318. // 单规格商品已存在SKU记录,直接更新(保持ID和销量不变)
  319. $newSkuData['sales'] = $existingSku->sales; // 保持原有销量
  320. $existingSku->save($newSkuData);
  321. $defaultSkuId = $existingSku->id;
  322. } else {
  323. // 新商品,创建SKU记录
  324. $newSkuData['sales'] = 0;
  325. $newSku = $this->sku_model->create($newSkuData);
  326. $defaultSkuId = $newSku->id;
  327. }
  328. // 更新商品主表信息
  329. $updateData = [
  330. 'spec_type' => 0, // 单规格
  331. 'stocks' => $skuData['stocks'] ?? 0,
  332. 'min_price' => $skuData['price'] ?? 0,
  333. 'max_price' => $skuData['price'] ?? 0,
  334. 'price' => $skuData['price'] ?? 0,
  335. 'min_lineation_price'=> $skuData['lineation_price'] ?? 0,
  336. 'max_lineation_price'=> $skuData['lineation_price'] ?? 0,
  337. 'lineation_price' => $skuData['lineation_price'] ?? 0,
  338. 'default_sku_id' => $defaultSkuId,
  339. ];
  340. $this->model->where('id', $goods_id)->update($updateData);
  341. }
  342. //添加商品多规格
  343. protected function addMultiSpecSku($skus, $spec, $goods_id)
  344. {
  345. //属性入库,传递规格类型信息
  346. $specList = Spec::push($spec);
  347. $newSpec = GoodsSkuSpec::push($specList, $goods_id, $spec);
  348. //匹配属性
  349. $list = $this->sku_model->where('goods_id', $goods_id)->select();
  350. $newData = [];
  351. $stocks = 0;
  352. foreach ($skus as $k => $sk) {
  353. $newSkuId = $this->getSkuId($sk['skus'], $newSpec, $spec);
  354. // 生成SKU规格属性JSON字符串
  355. $skuAttr = $this->generateSkuAttr($sk['skus'], $newSpec, $spec);
  356. $newSkuData = [
  357. 'goods_id' => $goods_id,
  358. 'spec_value_ids' => $newSkuId,
  359. 'sku_attr' => $skuAttr,
  360. 'sku_sn' => $sk['sku_sn'] ?? '',
  361. 'image' => $sk['image'] ?? '',
  362. 'price' => $sk['price'] ?? 0,
  363. 'lineation_price' => $sk['lineation_price'] ?? 0,
  364. 'cost_price' => $sk['cost_price'] ?? 0,
  365. 'weight' => $sk['weight'] ?? 0,
  366. 'volume' => $sk['volume'] ?? 0,
  367. 'stocks' => $sk['stocks'] ?? 0,
  368. 'status' => isset($sk['status']) ? intval($sk['status']) : 1,
  369. 'is_default' => isset($sk['is_default']) ? intval($sk['is_default']) : 0,
  370. ];
  371. if (isset($list[$k])) {
  372. $row = $list[$k];
  373. $oldSkuIdsArr = explode(',', $row['spec_value_ids']);
  374. sort($oldSkuIdsArr);
  375. $oldSkuId = implode(',', $oldSkuIdsArr);
  376. if ($oldSkuId == $newSkuId) {
  377. //相等的更新
  378. $row->save($newSkuData);
  379. } else {
  380. //不等的
  381. $row->save(array_merge($newSkuData, ['sales' => 0]));
  382. }
  383. unset($list[$k]);
  384. } else { //多余的
  385. $newData[] = array_merge($newSkuData, ['sales' => 0]);
  386. }
  387. $stocks = bcadd($stocks, $sk['stocks'] ?? 0);
  388. }
  389. if (!empty($newData)) {
  390. $this->sku_model->saveAll($newData);
  391. }
  392. // 处理默认SKU
  393. $defaultSkuId = 0;
  394. $hasDefault = false;
  395. foreach ($skus as $k => $sk) {
  396. if (isset($sk['is_default']) && $sk['is_default']) {
  397. $hasDefault = true;
  398. break;
  399. }
  400. }
  401. // 如果没有明确设置默认SKU,则使用第一个SKU作为默认
  402. if (!$hasDefault && !empty($skus)) {
  403. $firstSku = $this->sku_model->where('goods_id', $goods_id)->order('id', 'asc')->find();
  404. if ($firstSku) {
  405. $firstSku->save(['is_default' => 1]);
  406. $defaultSkuId = $firstSku->id;
  407. }
  408. } else {
  409. // 查找默认SKU的ID
  410. $defaultSku = $this->sku_model->where('goods_id', $goods_id)->where('is_default', 1)->find();
  411. if ($defaultSku) {
  412. $defaultSkuId = $defaultSku->id;
  413. }
  414. }
  415. //更新库存和默认SKU,计算价格范围
  416. if (!empty($skus)) {
  417. $prices = array_column($skus, 'price');
  418. $lineationPrices = array_column($skus, 'lineation_price');
  419. // 使用bc函数计算平均价格,保证精度
  420. $totalPrice = '0';
  421. $validPriceCount = 0;
  422. foreach ($prices as $price) {
  423. if ($price > 0) {
  424. $totalPrice = bcadd($totalPrice, (string)$price, 2);
  425. $validPriceCount++;
  426. }
  427. }
  428. // 计算平均价格
  429. $avgPrice = $validPriceCount > 0 ? bcdiv($totalPrice, (string)$validPriceCount, 2) : '0.00';
  430. // 使用bc函数计算平均划线价格
  431. $totalLineationPrice = '0';
  432. $validLineationPriceCount = 0;
  433. foreach ($lineationPrices as $lineationPrice) {
  434. if ($lineationPrice > 0) {
  435. $totalLineationPrice = bcadd($totalLineationPrice, (string)$lineationPrice, 2);
  436. $validLineationPriceCount++;
  437. }
  438. }
  439. // 计算平均划线价格
  440. $avgLineationPrice = $validLineationPriceCount > 0 ? bcdiv($totalLineationPrice, (string)$validLineationPriceCount, 2) : '0.00';
  441. // 过滤掉0值的划线价格来计算最大最小值
  442. $validLineationPrices = array_filter($lineationPrices, function($price) {
  443. return $price > 0;
  444. });
  445. $updateData = [
  446. 'stocks' => $stocks,
  447. 'spec_type' => 1,
  448. 'min_price' => min($prices),
  449. 'max_price' => max($prices),
  450. 'price' => $avgPrice,
  451. 'min_lineation_price' => !empty($validLineationPrices) ? min($validLineationPrices) : '0.00',
  452. 'max_lineation_price' => !empty($validLineationPrices) ? max($validLineationPrices) : '0.00',
  453. 'lineation_price' => $avgLineationPrice
  454. ];
  455. if ($defaultSkuId > 0) {
  456. $updateData['default_sku_id'] = $defaultSkuId;
  457. }
  458. $this->model->where('id', $goods_id)->update($updateData);
  459. } else {
  460. $this->model->where('id', $goods_id)->update(['spec_type' => 0]);
  461. }
  462. //原来多的删除
  463. foreach ($list as $it) {
  464. $it->delete();
  465. }
  466. }
  467. /**
  468. * 添加
  469. */
  470. public function add()
  471. {
  472. if ($this->request->isPost()) {
  473. $params = $this->request->post("row/a");
  474. if ($params) {
  475. $params = $this->preExcludeFields($params);
  476. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  477. $params[$this->dataLimitField] = $this->auth->id;
  478. }
  479. $result = false;
  480. Db::startTrans();
  481. try {
  482. //是否采用模型验证
  483. if ($this->modelValidate) {
  484. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  485. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  486. // 添加规格数据到验证参数中
  487. if (isset($params['skus']) && isset($params['spec'])) {
  488. $params['spec_data'] = json_decode($params['spec'], true);
  489. $params['sku_data'] = json_decode($params['skus'], true);
  490. }
  491. $this->model->validateFailException(true)->validate($validate);
  492. }
  493. // 备份上架类型,因为status字段将被覆盖为最终状态
  494. $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
  495. // 将online_type映射到status字段用于计算
  496. if (isset($params['online_type'])) {
  497. $params['status'] = $params['online_type'];
  498. unset($params['online_type']);
  499. }
  500. // 先保存商品基础信息(暂时不保存status字段)
  501. $statusBackup = $params['status'] ?? null;
  502. unset($params['status']); // 临时移除status避免冲突
  503. $result = $this->model->allowField(true)->save($params);
  504. // 根据上下架时间自动计算商品状态并更新
  505. $params['status'] = $statusBackup; // 恢复用于计算
  506. $calculatedStatus = $this->calculateGoodsStatus($params);
  507. $this->model->where('id', $this->model->id)->update([
  508. 'status' => $calculatedStatus,
  509. 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
  510. ]);
  511. // 调试输出
  512. \think\Log::write('商品添加 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
  513. //商品规格处理
  514. if (isset($params['skus']) && isset($params['spec'])) {
  515. $skus = (array)json_decode($params['skus'], true);
  516. $spec = (array)json_decode($params['spec'], true);
  517. // 只对多规格进行checkSku验证
  518. if (!empty($spec)) {
  519. $this->checkSku($skus, $spec);
  520. }
  521. // 统一处理SKU
  522. $this->processGoodsSku($params, $this->model->id);
  523. } else {
  524. throw new \Exception('商品规格数据不能为空');
  525. }
  526. //商品属性
  527. if (isset($params['attribute_ids'])) {
  528. GoodsAttr::addGoodsAttr($params['attribute_ids'], $this->model->id);
  529. }
  530. Db::commit();
  531. } catch (ValidateException $e) {
  532. Db::rollback();
  533. $this->error($e->getMessage());
  534. } catch (PDOException $e) {
  535. Db::rollback();
  536. $this->error($e->getMessage());
  537. } catch (Exception $e) {
  538. Db::rollback();
  539. $this->error($e->getMessage());
  540. }
  541. if ($result !== false) {
  542. $this->success();
  543. } else {
  544. $this->error(__('No rows were inserted'));
  545. }
  546. }
  547. $this->error(__('Parameter %s can not be empty', ''));
  548. }
  549. return $this->view->fetch();
  550. }
  551. /**
  552. * 编辑
  553. */
  554. public function edit($ids = null)
  555. {
  556. $row = $this->model->find($ids);
  557. if (!$row) {
  558. $this->error(__('No Results were found'));
  559. }
  560. $adminIds = $this->getDataLimitAdminIds();
  561. if (is_array($adminIds)) {
  562. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  563. $this->error(__('You have no permission'));
  564. }
  565. }
  566. if ($this->request->isPost()) {
  567. $params = $this->request->post("row/a");
  568. if ($params) {
  569. $params = $this->preExcludeFields($params);
  570. $result = false;
  571. // 查询该商品是否参与进行中的折扣活动
  572. if (DiscountService::hasActivity($row->id)) {
  573. $this->error('该商品参与了进行中的折扣活动,不能编辑');
  574. }
  575. Db::startTrans();
  576. try {
  577. //是否采用模型验证
  578. if ($this->modelValidate) {
  579. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  580. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  581. // 添加规格数据到验证参数中
  582. if (isset($params['skus']) && isset($params['spec'])) {
  583. $params['spec_data'] = json_decode($params['spec'], true);
  584. $params['sku_data'] = json_decode($params['skus'], true);
  585. }
  586. $row->validateFailException(true)->validate($validate);
  587. }
  588. // 备份上架类型,因为status字段将被覆盖为最终状态
  589. $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
  590. // 将online_type映射到status字段用于计算
  591. if (isset($params['online_type'])) {
  592. $params['status'] = $params['online_type'];
  593. unset($params['online_type']);
  594. }
  595. // 先保存商品基础信息(暂时不保存status字段)
  596. $statusBackup = $params['status'] ?? null;
  597. unset($params['status']); // 临时移除status避免冲突
  598. $result = $row->allowField(true)->save($params);
  599. // 根据上下架时间自动计算商品状态并更新
  600. $params['status'] = $statusBackup; // 恢复用于计算
  601. $calculatedStatus = $this->calculateGoodsStatus($params);
  602. $this->model->where('id', $row->id)->update([
  603. 'status' => $calculatedStatus,
  604. 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
  605. ]);
  606. // 调试输出
  607. \think\Log::write('商品编辑 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
  608. //商品规格处理
  609. if (isset($params['skus']) && isset($params['spec'])) {
  610. $skus = (array)json_decode($params['skus'], true);
  611. $spec = (array)json_decode($params['spec'], true);
  612. // 只对多规格进行checkSku验证
  613. if (!empty($spec)) {
  614. $this->checkSku($skus, $spec);
  615. }
  616. // 统一处理SKU
  617. $this->processGoodsSku($params, $row->id);
  618. } else {
  619. throw new \Exception('商品规格数据不能为空');
  620. }
  621. //商品属性
  622. if (isset($params['attribute_ids'])) {
  623. GoodsAttr::addGoodsAttr($params['attribute_ids'], $row->id);
  624. }
  625. Db::commit();
  626. } catch (ValidateException $e) {
  627. Db::rollback();
  628. $this->error($e->getMessage());
  629. } catch (PDOException $e) {
  630. Db::rollback();
  631. $this->error($e->getMessage());
  632. } catch (Exception $e) {
  633. Db::rollback();
  634. $this->error($e->getMessage());
  635. }
  636. if ($result !== false) {
  637. $this->success();
  638. } else {
  639. $this->error(__('No rows were updated'));
  640. }
  641. }
  642. $this->error(__('Parameter %s can not be empty', ''));
  643. }
  644. // 查询SKU数据
  645. $list = $this->sku_model->where('goods_id', $row->id)->select();
  646. // 构造规格数据结构
  647. $spec_data = [];
  648. $spec_values = []; // 用于传递给前端的规格值完整数据
  649. if ($row->spec_type == 1) { // 多规格商品
  650. // 查询规格和规格值,包含规格类型
  651. $specs = Db::name('shop_goods_sku_spec')
  652. ->alias('gss')
  653. ->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')
  654. ->join('shop_spec sp', 'sp.id = gss.spec_id', 'LEFT')
  655. ->join('shop_spec_value sv', 'sv.id = gss.spec_value_id', 'LEFT')
  656. ->where('gss.goods_id', $row->id)
  657. ->order('sp.id asc, sv.id asc')
  658. ->select();
  659. // 按规格分组
  660. $spec_groups = [];
  661. foreach ($specs as $spec) {
  662. if (!isset($spec_groups[$spec['spec_id']])) {
  663. $spec_groups[$spec['spec_id']]['name'] = $spec['spec_name'];
  664. $spec_groups[$spec['spec_id']]['type'] = $spec['spec_type'] == 2 ? 'custom' : 'basic';
  665. $spec_groups[$spec['spec_id']]['value'] = [];
  666. }
  667. $spec_groups[$spec['spec_id']]['value'][] = [
  668. 'id' => $spec['spec_value_id'],
  669. 'name' => $spec['value'],
  670. 'image' => $spec['image'] ?: '',
  671. 'description' => $spec['desc'] ?: ''
  672. ];
  673. // 构造规格值数据,用于前端初始化
  674. $spec_values[] = [
  675. 'spec_name' => $spec['spec_name'],
  676. 'spec_type' => $spec['spec_type'],
  677. 'value' => $spec['value'],
  678. 'image' => $spec['image'] ?: '',
  679. 'description' => $spec['desc'] ?: ''
  680. ];
  681. }
  682. // 转换为前端需要的格式
  683. foreach ($spec_groups as $spec_id => $spec_info) {
  684. $spec_data[] = [
  685. 'id' => $spec_id,
  686. 'name' => $spec_info['name'],
  687. 'type' => $spec_info['type'],
  688. 'value' => $spec_info['value']
  689. ];
  690. }
  691. }
  692. $this->view->assign("row", $row);
  693. $this->assignconfig('goods', $row);
  694. $this->assignconfig('goods_skus', $list);
  695. $this->assignconfig('spec_data', $spec_data); // 传递规格数据结构
  696. $this->assignconfig('spec_values', $spec_values); // 传递规格值完整数据
  697. return $this->view->fetch();
  698. }
  699. /**
  700. * 获取多个商品信息
  701. */
  702. public function getGoodsByIds()
  703. {
  704. $ids = $this->request->request('ids');
  705. if (!$ids) {
  706. $this->error('请选择商品');
  707. }
  708. $ids = explode(',', $ids);
  709. $list = $this->model
  710. ->with(['Category'])
  711. ->where('id', 'in', $ids)
  712. ->select();
  713. // 处理图片URL和SKU信息
  714. foreach ($list as &$item) {
  715. if ($item['image']) {
  716. $item['image'] = cdnurl($item['image'], true);
  717. }
  718. // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
  719. $sku = \app\common\model\Sku::where('goods_id', $item['id'])->find();
  720. $item['sku_id'] = $sku ? $sku['id'] : 0;
  721. }
  722. $this->success('获取成功', null, $list);
  723. }
  724. /**
  725. * 根据ID批量获取商品信息
  726. */
  727. public function get_goods_by_ids()
  728. {
  729. $ids = $this->request->request('ids');
  730. if (!$ids) {
  731. $this->error('请选择商品');
  732. }
  733. $ids = explode(',', $ids);
  734. $list = $this->model
  735. ->where('id', 'in', $ids)
  736. ->select();
  737. // 转换商品结果为数组
  738. $goodsData = [];
  739. if ($list) {
  740. foreach ($list as $item) {
  741. $goodsData[] = is_array($item) ? $item : $item->toArray();
  742. }
  743. }
  744. // 如果没有商品数据,直接返回空数组
  745. if (empty($goodsData)) {
  746. return json([]);
  747. }
  748. // 一次性查询所有商品的SKU信息
  749. $allSkusResult = Db::name('shop_goods_sku')
  750. ->where('goods_id', 'in', $ids)
  751. ->order('is_default desc, id asc')
  752. ->select();
  753. // 按商品ID分组SKU数据
  754. $skusByGoods = [];
  755. foreach ($allSkusResult as $sku) {
  756. $skuArray = is_array($sku) ? $sku : $sku->toArray();
  757. $skusByGoods[$skuArray['goods_id']][] = $skuArray;
  758. }
  759. // 找出多规格商品ID
  760. $multiSpecGoodsIds = [];
  761. foreach ($goodsData as $item) {
  762. if ($item['spec_type'] == 1) {
  763. $multiSpecGoodsIds[] = $item['id'];
  764. }
  765. }
  766. // 一次性查询所有多规格商品的规格信息
  767. $specsByGoods = [];
  768. if (!empty($multiSpecGoodsIds)) {
  769. $allSpecsResult = Db::name('shop_goods_sku_spec')
  770. ->alias('gss')
  771. ->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')
  772. ->join('shop_spec sp', 'sp.id=gss.spec_id', 'LEFT')
  773. ->join('shop_spec_value sv', 'sv.id=gss.spec_value_id', 'LEFT')
  774. ->where('gss.goods_id', 'in', $multiSpecGoodsIds)
  775. ->order('gss.goods_id asc, sp.id asc, sv.id asc')
  776. ->select();
  777. // 按商品ID分组规格数据
  778. foreach ($allSpecsResult as $spec) {
  779. $specArray = is_array($spec) ? $spec : $spec->toArray();
  780. $specsByGoods[$specArray['goods_id']][] = $specArray;
  781. }
  782. }
  783. // 一次性查询所有SKU的规格属性文本
  784. $allSkuIds = [];
  785. foreach ($skusByGoods as $skus) {
  786. foreach ($skus as $sku) {
  787. $allSkuIds[] = $sku['id'];
  788. }
  789. }
  790. $skuSpecTexts = [];
  791. if (!empty($allSkuIds)) {
  792. $skuSpecResults = Db::name('shop_goods_sku')
  793. ->alias('sku')
  794. ->field('sku.id, GROUP_CONCAT(sp.name,":",sv.value ORDER BY sp.id asc) as specs_text')
  795. ->join('shop_goods_sku_spec gss', "FIND_IN_SET(gss.id, sku.spec_value_ids)", 'LEFT')
  796. ->join('shop_spec sp', 'sp.id=gss.spec_id', 'LEFT')
  797. ->join('shop_spec_value sv', 'sv.id=gss.spec_value_id', 'LEFT')
  798. ->where('sku.id', 'in', $allSkuIds)
  799. ->group('sku.id')
  800. ->select();
  801. foreach ($skuSpecResults as $result) {
  802. $resultArray = is_array($result) ? $result : $result->toArray();
  803. $skuSpecTexts[$resultArray['id']] = $resultArray['specs_text'] ?: '';
  804. }
  805. }
  806. // 处理每个商品的详细信息(纯数据组装,无数据库查询)
  807. foreach ($goodsData as &$item) {
  808. if ($item['image']) {
  809. $item['image'] = cdnurl($item['image'], true);
  810. }
  811. // 获取商品的SKU信息
  812. $skus = $skusByGoods[$item['id']] ?? [];
  813. if ($skus) {
  814. // 获取第一个SKU ID(单规格商品通常只有一个SKU)
  815. $item['sku_id'] = $skus[0]['id'];
  816. // 为每个SKU添加规格属性文本
  817. foreach ($skus as &$sku) {
  818. $sku['specs_text'] = $skuSpecTexts[$sku['id']] ?? '';
  819. }
  820. $item['skus'] = $skus;
  821. // 如果是多规格商品,添加规格数据
  822. if ($item['spec_type'] == 1) {
  823. $specs = $specsByGoods[$item['id']] ?? [];
  824. // 按规格分组构建规格数据结构
  825. $spec_groups = [];
  826. foreach ($specs as $spec) {
  827. if (!isset($spec_groups[$spec['spec_id']])) {
  828. $spec_groups[$spec['spec_id']]['id'] = $spec['spec_id'];
  829. $spec_groups[$spec['spec_id']]['name'] = $spec['spec_name'];
  830. $spec_groups[$spec['spec_id']]['type'] = $spec['spec_type'] == 2 ? 'custom' : 'basic';
  831. $spec_groups[$spec['spec_id']]['value'] = [];
  832. }
  833. $spec_groups[$spec['spec_id']]['value'][] = [
  834. 'id' => $spec['spec_value_id'],
  835. 'name' => $spec['value'],
  836. 'image' => $spec['image'] ?: '',
  837. 'description' => $spec['desc'] ?: ''
  838. ];
  839. }
  840. // 转换为数组格式,与前端渲染一致
  841. $item['spec'] = array_values($spec_groups);
  842. } else {
  843. // 单规格商品,没有spec数据
  844. $item['spec'] = [];
  845. }
  846. } else {
  847. $item['sku_id'] = 0;
  848. $item['skus'] = [];
  849. $item['spec'] = [];
  850. }
  851. }
  852. return json($goodsData);
  853. }
  854. /**
  855. * 复制商品
  856. */
  857. public function copy($ids = null)
  858. {
  859. $row = $this->model->find($ids);
  860. if (!$row) {
  861. $this->error(__('No Results were found'));
  862. }
  863. $adminIds = $this->getDataLimitAdminIds();
  864. if (is_array($adminIds)) {
  865. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  866. $this->error(__('You have no permission'));
  867. }
  868. }
  869. Db::startTrans();
  870. try {
  871. // 复制商品基本信息
  872. $goodsData = $row->toArray();
  873. // 调试输出
  874. \think\Log::write('开始复制商品,原商品ID: ' . $row->id, 'info');
  875. // 移除不需要复制的字段
  876. unset($goodsData['id'], $goodsData['createtime'], $goodsData['updatetime']);
  877. // 修改商品名称和编码,添加"复制"标识
  878. $goodsData['title'] = $goodsData['title'] . ' (复制)';
  879. $goodsData['goods_sn'] = $goodsData['goods_sn'] . '_copy_' . date('YmdHis');
  880. $goodsData['status'] = \app\common\Enum\GoodsEnum::STATUS_IN_STORAGE; // 复制的商品默认为仓库中状态
  881. $goodsData['online_type'] = \app\common\Enum\GoodsEnum::ONLINE_TYPE_NOT_NOW; // 暂不上架
  882. $goodsData['sales'] = 0; // 重置销量
  883. $goodsData['views'] = 0; // 重置浏览量
  884. // 创建新商品
  885. $newGoods = $this->model->create($goodsData);
  886. $newGoodsId = $newGoods->id;
  887. // 复制商品SKU信息
  888. $skuList = $this->sku_model->where('goods_id', $row->id)->select();
  889. \think\Log::write('查询到SKU数量: ' . ($skuList ? count($skuList) : 0), 'info');
  890. $newSkuData = [];
  891. $defaultSkuId = 0;
  892. if ($skuList && !$skuList->isEmpty()) {
  893. foreach ($skuList as $sku) {
  894. $skuData = $sku->toArray();
  895. unset($skuData['id'], $skuData['createtime'], $skuData['updatetime']);
  896. $skuData['goods_id'] = $newGoodsId;
  897. $skuData['sales'] = 0; // 重置销量
  898. $skuData['sku_sn'] = $skuData['sku_sn'] . '_copy_' . date('YmdHis');
  899. $newSkuData[] = $skuData;
  900. }
  901. }
  902. if (!empty($newSkuData)) {
  903. $newSkus = $this->sku_model->saveAll($newSkuData);
  904. // 获取第一个SKU作为默认SKU
  905. if (!empty($newSkus)) {
  906. $defaultSkuId = $newSkus[0]->id;
  907. }
  908. } else {
  909. // 如果没有SKU数据,创建一个默认的SKU
  910. \think\Log::write('没有找到SKU数据,创建默认SKU', 'info');
  911. $defaultSkuData = [
  912. 'goods_id' => $newGoodsId,
  913. 'spec_value_ids' => '',
  914. 'sku_attr' => '', // 单规格无规格属性
  915. 'sku_sn' => $goodsData['goods_sn'] ?? 'SKU_' . date('YmdHis'),
  916. 'image' => $goodsData['image'] ?? '',
  917. 'price' => isset($goodsData['price']) ? $goodsData['price'] : 0.01,
  918. 'lineation_price' => isset($goodsData['lineation_price']) ? $goodsData['lineation_price'] : 0,
  919. 'cost_price' => 0,
  920. 'weight' => 0,
  921. 'volume' => 0,
  922. 'stocks' => 1,
  923. 'sales' => 0,
  924. 'status' => 1,
  925. 'is_default' => 1,
  926. ];
  927. $newSku = $this->sku_model->create($defaultSkuData);
  928. $defaultSkuId = $newSku->id;
  929. }
  930. // 更新商品默认SKU
  931. if ($defaultSkuId > 0) {
  932. $newGoods->save(['default_sku_id' => $defaultSkuId]);
  933. }
  934. // 复制商品规格信息(如果是多规格商品)
  935. if ($row->spec_type == 1) {
  936. // 复制商品规格关联
  937. $goodsSpecList = Db::name('shop_goods_sku_spec')
  938. ->where('goods_id', $row->id)
  939. ->select();
  940. $newGoodsSpecData = [];
  941. if ($goodsSpecList && is_array($goodsSpecList) && !empty($goodsSpecList)) {
  942. foreach ($goodsSpecList as $goodsSpec) {
  943. $newGoodsSpecData[] = [
  944. 'goods_id' => $newGoodsId,
  945. 'spec_id' => $goodsSpec['spec_id'],
  946. 'spec_value_id' => $goodsSpec['spec_value_id'],
  947. 'createtime' => time(),
  948. 'updatetime' => time()
  949. ];
  950. }
  951. }
  952. if (!empty($newGoodsSpecData)) {
  953. Db::name('shop_goods_sku_spec')->insertAll($newGoodsSpecData);
  954. }
  955. }
  956. // 复制商品属性信息
  957. $goodsAttrList = Db::name('shop_goods_attr')
  958. ->where('goods_id', $row->id)
  959. ->select();
  960. $newGoodsAttrData = [];
  961. if ($goodsAttrList && is_array($goodsAttrList) && !empty($goodsAttrList)) {
  962. foreach ($goodsAttrList as $goodsAttr) {
  963. $newGoodsAttrData[] = [
  964. 'goods_id' => $newGoodsId,
  965. 'attr_id' => $goodsAttr['attr_id'],
  966. 'attr_value' => $goodsAttr['attr_value'],
  967. 'createtime' => time(),
  968. 'updatetime' => time()
  969. ];
  970. }
  971. }
  972. if (!empty($newGoodsAttrData)) {
  973. Db::name('shop_goods_attr')->insertAll($newGoodsAttrData);
  974. }
  975. Db::commit();
  976. \think\Log::write('商品复制成功,新商品ID: ' . $newGoodsId, 'info');
  977. $this->success('商品复制成功', null, ['goods_id' => $newGoodsId]);
  978. } catch (Exception $e) {
  979. Db::rollback();
  980. \think\Log::write('商品复制失败: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行: ' . $e->getLine(), 'error');
  981. $this->error('复制失败:' . $e->getMessage());
  982. } catch (\Throwable $e) {
  983. Db::rollback();
  984. \think\Log::write('商品复制出现严重错误: ' . $e->getMessage() . ' 文件: ' . $e->getFile() . ' 行: ' . $e->getLine(), 'error');
  985. $this->error('复制失败:系统错误');
  986. }
  987. }
  988. }