Goods.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. /**
  14. * 商品管理
  15. *
  16. * @icon fa fa-circle-o
  17. */
  18. class Goods extends Backend
  19. {
  20. /**
  21. * 快速搜索时执行查找的字段
  22. */
  23. protected $searchFields = 'id,goods_sn,title,subtitle';
  24. /**
  25. * Goods模型对象
  26. * @var \app\admin\model\shop\Goods
  27. */
  28. protected $model = null;
  29. protected $sku_model = null;
  30. public function _initialize()
  31. {
  32. parent::_initialize();
  33. $this->model = new \app\admin\model\shop\Goods;
  34. $this->sku_model = new \app\admin\model\shop\GoodsSku;
  35. // $this->view->assign("flagList", $this->model->getFlagList());
  36. // $this->view->assign("statusList", $this->model->getStatusList());
  37. $this->view->assign("goodsTypeList", GoodsEnum::getGoodsTypeMap());
  38. $this->assignconfig("goodsTypeList", json_encode(GoodsEnum::getGoodsTypeMap()));
  39. $this->view->assign("statusList", GoodsEnum::getGoodsStatusMap());
  40. $this->assignconfig("statusList", json_encode(GoodsEnum::getGoodsStatusMap()));
  41. $this->view->assign("specTypeList", GoodsEnum::getSpecTypeMap());
  42. $this->assignconfig("specTypeList", json_encode(GoodsEnum::getSpecTypeMap()));
  43. $this->view->assign("deliveryTypeList", GoodsEnum::getDeliveryTypeMap());
  44. $this->view->assign("onlineTypeList", GoodsEnum::getOnlineTypeMap());
  45. $this->view->assign("expressTypeList", GoodsEnum::getExpressTypeMap());
  46. $this->view->assign("stockShowTypeList", GoodsEnum::getStockShowTypeMap());
  47. $this->view->assign("salesShowTypeList", GoodsEnum::getSalesShowTypeMap());
  48. }
  49. /**
  50. * 检查商品编码是否重复
  51. */
  52. public function checkGoodsSn()
  53. {
  54. $goods_sn = $this->request->param('goods_sn');
  55. $id = $this->request->param('id', 0);
  56. if (empty($goods_sn)) {
  57. $this->error('商品编码不能为空');
  58. }
  59. $where = [['goods_sn', '=', $goods_sn]];
  60. if ($id > 0) {
  61. $where[] = ['id', '<>', $id];
  62. }
  63. $exists = $this->model->where($where)->find();
  64. if ($exists) {
  65. $this->error('商品编码已存在');
  66. }
  67. $this->success('商品编码可用');
  68. }
  69. /**
  70. * 查看
  71. */
  72. public function index()
  73. {
  74. //设置过滤方法
  75. $this->request->filter(['strip_tags', 'trim']);
  76. if ($this->request->isAjax()) {
  77. //如果发送的来源是Selectpage,则转发到Selectpage
  78. if ($this->request->request('keyField')) {
  79. return $this->selectpage();
  80. }
  81. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  82. $list = $this->model
  83. ->with(['Freight', 'Brand', 'Category'])
  84. ->where($where)
  85. ->order($sort, $order)
  86. ->paginate($limit);
  87. $result = array("total" => $list->total(), "rows" => $list->items());
  88. return json($result);
  89. }
  90. return $this->view->fetch();
  91. }
  92. /**
  93. * 查看
  94. */
  95. public function select()
  96. {
  97. //设置过滤方法
  98. $this->request->filter(['strip_tags', 'trim']);
  99. if ($this->request->isAjax()) {
  100. //如果发送的来源是Selectpage,则转发到Selectpage
  101. if ($this->request->request('keyField')) {
  102. return $this->selectpage();
  103. }
  104. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  105. $list = $this->model
  106. ->with(['Freight', 'Brand', 'Category'])
  107. ->where($where)
  108. ->order($sort, $order)
  109. ->paginate($limit);
  110. // 为每个商品添加SKU信息
  111. $items = $list->items();
  112. foreach ($items as &$item) {
  113. // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
  114. $sku = \app\common\model\Sku::where('goods_id', $item['id'])->find();
  115. $item['sku_id'] = $sku ? $sku['id'] : 0;
  116. }
  117. $result = array("total" => $list->total(), "rows" => $items);
  118. return json($result);
  119. }
  120. return $this->view->fetch();
  121. }
  122. //检查属性skus 和 spec 是否对上
  123. protected function checkSku($skus, $spec)
  124. {
  125. foreach ($skus as $item) {
  126. if (!isset($item['skus']) || !is_array($item['skus']) || empty($item['skus'])) {
  127. throw new Exception('规格属性不能为空');
  128. }
  129. if (!isset($item['price'])) {
  130. throw new Exception('请录入价格');
  131. }
  132. foreach ($item['skus'] as $k => $v) {
  133. if (empty($v) && !is_numeric($v)) {
  134. throw new Exception('规格【' . $v . '】属性值不能为空');
  135. }
  136. if (!isset($spec[$k]['value']) || (empty($spec[$k]['name']) && !is_numeric($spec[$k]['name']))) {
  137. throw new Exception('规格【' . $v . '】名称不能为空');
  138. }
  139. foreach ($spec[$k]['value'] as $m => $n) {
  140. // 兼容新格式(对象)和旧格式(字符串)
  141. $valueText = is_array($n) ? $n['name'] : $n;
  142. if (stripos($valueText, ',') !== false) {
  143. throw new Exception('规格【' . $v . '】属性值中不能包含,');
  144. }
  145. }
  146. // 检查重复值(提取name字段进行比较)
  147. $valueNames = array_map(function($n) {
  148. return is_array($n) ? $n['name'] : $n;
  149. }, $spec[$k]['value']);
  150. if (count($valueNames) != count(array_unique($valueNames))) {
  151. throw new Exception('规格【' . $v . '】属性值中不能有重复值');
  152. }
  153. // 检查规格值是否匹配(支持新旧格式)
  154. $valueNames = array_map(function($n) {
  155. return is_array($n) ? $n['name'] : $n;
  156. }, $spec[$k]['value']);
  157. if (empty($spec[$k]['value']) || !in_array($v, $valueNames)) {
  158. throw new Exception('规格【' . $v . '】属性不匹配');
  159. }
  160. }
  161. }
  162. }
  163. protected function getSkuId($skus, $newSpec, $spec)
  164. {
  165. $arr = [];
  166. foreach ($skus as $index => $item) {
  167. $specArr = $spec[$index];
  168. foreach ($newSpec as $subindex => $subitem) {
  169. if ($subitem['spec_name'] == $specArr['name'] && $subitem['spec_value_value'] == $item) {
  170. $arr[] = $subitem['id'];
  171. }
  172. }
  173. }
  174. sort($arr);
  175. return implode(',', $arr);
  176. }
  177. /**
  178. * 根据上下架时间计算商品状态
  179. * @param array $params 商品参数
  180. * @return int 商品状态
  181. */
  182. protected function calculateGoodsStatus($params)
  183. {
  184. $currentTime = time();
  185. // 获取上架时间设置 - 前端传递的上架类型字段(使用status字段)
  186. $onlineType = isset($params['status']) ? intval($params['status']) : GoodsEnum::ONLINE_TYPE_NOT_NOW;
  187. $scheduledOnlineTime = isset($params['scheduled_online_time']) ? strtotime($params['scheduled_online_time']) : 0;
  188. // 获取下架时间设置
  189. $isAutoOffline = isset($params['is_auto_offline']) ? intval($params['is_auto_offline']) : 0;
  190. $scheduledOfflineTime = isset($params['scheduled_offline_time']) ? strtotime($params['scheduled_offline_time']) : 0;
  191. // 根据上架类型判断状态
  192. switch ($onlineType) {
  193. case GoodsEnum::ONLINE_TYPE_IMMEDIATE: // 立即上架
  194. // 检查是否需要自动下架
  195. if ($isAutoOffline && $scheduledOfflineTime > 0) {
  196. if ($currentTime >= $scheduledOfflineTime) {
  197. return GoodsEnum::STATUS_OFF_SALE; // 已下架
  198. }
  199. }
  200. return GoodsEnum::STATUS_ON_SALE; // 销售中
  201. case GoodsEnum::ONLINE_TYPE_NOT_NOW: // 暂不上架
  202. return GoodsEnum::STATUS_IN_STORAGE; // 仓库中
  203. case GoodsEnum::ONLINE_TYPE_SCHEDULED: // 定时上架
  204. if ($scheduledOnlineTime <= 0) {
  205. return GoodsEnum::STATUS_IN_STORAGE; // 未设置上架时间,保持仓库中
  206. }
  207. if ($currentTime < $scheduledOnlineTime) {
  208. return GoodsEnum::STATUS_IN_STORAGE; // 未到上架时间,仓库中
  209. }
  210. // 已到上架时间,检查下架时间
  211. if ($isAutoOffline && $scheduledOfflineTime > 0) {
  212. if ($currentTime >= $scheduledOfflineTime) {
  213. return GoodsEnum::STATUS_OFF_SALE; // 已下架
  214. }
  215. }
  216. return GoodsEnum::STATUS_ON_SALE; // 销售中
  217. default:
  218. return GoodsEnum::STATUS_IN_STORAGE; // 默认仓库中
  219. }
  220. }
  221. //处理商品SKU(统一处理单规格和多规格)
  222. protected function processGoodsSku($params, $goods_id)
  223. {
  224. // 统一通过skus和spec字段处理
  225. if (isset($params['skus']) && isset($params['spec'])) {
  226. $skus = (array)json_decode($params['skus'], true);
  227. $spec = (array)json_decode($params['spec'], true);
  228. // 判断是单规格还是多规格
  229. if (empty($spec) && count($skus) === 1) {
  230. // 单规格处理
  231. $this->addSingleSpecSku($skus[0], $goods_id);
  232. } else {
  233. // 多规格处理
  234. $this->addMultiSpecSku($skus, $spec, $goods_id);
  235. }
  236. } else {
  237. throw new \Exception('SKU数据格式错误');
  238. }
  239. }
  240. //添加单规格商品SKU
  241. protected function addSingleSpecSku($skuData, $goods_id)
  242. {
  243. // 如果原来是多规格,先清理多余的SKU记录
  244. $existingSkuCount = $this->sku_model->where('goods_id', $goods_id)->count();
  245. if ($existingSkuCount > 1) {
  246. // 从多规格改为单规格,删除所有旧记录
  247. $this->sku_model->where('goods_id', $goods_id)->delete();
  248. }
  249. // 查询现有的SKU记录
  250. $existingSku = $this->sku_model->where('goods_id', $goods_id)->find();
  251. // 创建单规格SKU数据
  252. $newSkuData = [
  253. 'goods_id' => $goods_id,
  254. 'spec_value_ids' => '', // 单规格无规格值ID
  255. 'sku_attr' => '', // 单规格无规格属性
  256. 'sku_sn' => $skuData['sku_sn'] ?? '',
  257. 'image' => $skuData['image'] ?? '',
  258. 'price' => $skuData['price'] ?? 0,
  259. 'lineation_price'=> $skuData['lineation_price'] ?? 0,
  260. 'cost_price' => $skuData['cost_price'] ?? 0,
  261. 'weight' => $skuData['weight'] ?? 0,
  262. 'volume' => $skuData['volume'] ?? 0,
  263. 'stocks' => $skuData['stocks'] ?? 0,
  264. 'status' => 1,
  265. 'is_default' => 1, // 单规格默认为默认SKU
  266. ];
  267. $defaultSkuId = 0;
  268. if ($existingSku) {
  269. // 单规格商品已存在SKU记录,直接更新(保持ID和销量不变)
  270. $newSkuData['sales'] = $existingSku->sales; // 保持原有销量
  271. $existingSku->save($newSkuData);
  272. $defaultSkuId = $existingSku->id;
  273. } else {
  274. // 新商品,创建SKU记录
  275. $newSkuData['sales'] = 0;
  276. $newSku = $this->sku_model->create($newSkuData);
  277. $defaultSkuId = $newSku->id;
  278. }
  279. // 更新商品主表信息
  280. $updateData = [
  281. 'spec_type' => 0, // 单规格
  282. 'stocks' => $skuData['stocks'] ?? 0,
  283. 'min_price' => $skuData['price'] ?? 0,
  284. 'max_price' => $skuData['price'] ?? 0,
  285. 'price' => $skuData['price'] ?? 0,
  286. 'min_lineation_price'=> $skuData['lineation_price'] ?? 0,
  287. 'max_lineation_price'=> $skuData['lineation_price'] ?? 0,
  288. 'lineation_price' => $skuData['lineation_price'] ?? 0,
  289. 'default_sku_id' => $defaultSkuId,
  290. ];
  291. $this->model->where('id', $goods_id)->update($updateData);
  292. }
  293. //添加商品多规格
  294. protected function addMultiSpecSku($skus, $spec, $goods_id)
  295. {
  296. //属性入库
  297. $specList = Spec::push($spec);
  298. $newSpec = GoodsSkuSpec::push($specList, $goods_id);
  299. //匹配属性
  300. $list = $this->sku_model->where('goods_id', $goods_id)->select();
  301. $newData = [];
  302. $stocks = 0;
  303. foreach ($skus as $k => $sk) {
  304. $newSkuId = $this->getSkuId($sk['skus'], $newSpec, $spec);
  305. // 生成规格属性JSON,格式:[{"name":"规格名","value":"规格值"}]
  306. $skuAttr = '';
  307. if (!empty($sk['skus'])) {
  308. $attrArray = [];
  309. foreach ($sk['skus'] as $index => $value) {
  310. if (isset($spec[$index]['name']) && !empty($value)) {
  311. $attrArray[] = [
  312. 'name' => $spec[$index]['name'],
  313. 'value' => $value
  314. ];
  315. }
  316. }
  317. $skuAttr = !empty($attrArray) ? json_encode($attrArray, JSON_UNESCAPED_UNICODE) : '';
  318. }
  319. $newSkuData = [
  320. 'goods_id' => $goods_id,
  321. 'spec_value_ids' => $newSkuId,
  322. 'sku_attr' => $skuAttr, // 冗余存储规格信息
  323. 'sku_sn' => $sk['sku_sn'] ?? '',
  324. 'image' => $sk['image'] ?? '',
  325. 'price' => $sk['price'] ?? 0,
  326. 'lineation_price' => $sk['lineation_price'] ?? 0,
  327. 'cost_price' => $sk['cost_price'] ?? 0,
  328. 'weight' => $sk['weight'] ?? 0,
  329. 'volume' => $sk['volume'] ?? 0,
  330. 'stocks' => $sk['stocks'] ?? 0,
  331. 'status' => isset($sk['status']) ? intval($sk['status']) : 1,
  332. 'is_default' => isset($sk['is_default']) ? intval($sk['is_default']) : 0,
  333. ];
  334. if (isset($list[$k])) {
  335. $row = $list[$k];
  336. $oldSkuIdsArr = explode(',', $row['spec_value_ids']);
  337. sort($oldSkuIdsArr);
  338. $oldSkuId = implode(',', $oldSkuIdsArr);
  339. if ($oldSkuId == $newSkuId) {
  340. //相等的更新
  341. $row->save($newSkuData);
  342. } else {
  343. //不等的
  344. $row->save(array_merge($newSkuData, ['sales' => 0]));
  345. }
  346. unset($list[$k]);
  347. } else { //多余的
  348. $newData[] = array_merge($newSkuData, ['sales' => 0]);
  349. }
  350. $stocks = bcadd($stocks, $sk['stocks'] ?? 0);
  351. }
  352. if (!empty($newData)) {
  353. $this->sku_model->saveAll($newData);
  354. }
  355. // 处理默认SKU
  356. $defaultSkuId = 0;
  357. $hasDefault = false;
  358. foreach ($skus as $k => $sk) {
  359. if (isset($sk['is_default']) && $sk['is_default']) {
  360. $hasDefault = true;
  361. break;
  362. }
  363. }
  364. // 如果没有明确设置默认SKU,则使用第一个SKU作为默认
  365. if (!$hasDefault && !empty($skus)) {
  366. $firstSku = $this->sku_model->where('goods_id', $goods_id)->order('id', 'asc')->find();
  367. if ($firstSku) {
  368. $firstSku->save(['is_default' => 1]);
  369. $defaultSkuId = $firstSku->id;
  370. }
  371. } else {
  372. // 查找默认SKU的ID
  373. $defaultSku = $this->sku_model->where('goods_id', $goods_id)->where('is_default', 1)->find();
  374. if ($defaultSku) {
  375. $defaultSkuId = $defaultSku->id;
  376. }
  377. }
  378. //更新库存和默认SKU,计算价格范围
  379. if (!empty($skus)) {
  380. $prices = array_column($skus, 'price');
  381. $lineationPrices = array_column($skus, 'lineation_price');
  382. // 使用bc函数计算平均价格,保证精度
  383. $totalPrice = '0';
  384. $validPriceCount = 0;
  385. foreach ($prices as $price) {
  386. if ($price > 0) {
  387. $totalPrice = bcadd($totalPrice, (string)$price, 2);
  388. $validPriceCount++;
  389. }
  390. }
  391. // 计算平均价格
  392. $avgPrice = $validPriceCount > 0 ? bcdiv($totalPrice, (string)$validPriceCount, 2) : '0.00';
  393. // 使用bc函数计算平均划线价格
  394. $totalLineationPrice = '0';
  395. $validLineationPriceCount = 0;
  396. foreach ($lineationPrices as $lineationPrice) {
  397. if ($lineationPrice > 0) {
  398. $totalLineationPrice = bcadd($totalLineationPrice, (string)$lineationPrice, 2);
  399. $validLineationPriceCount++;
  400. }
  401. }
  402. // 计算平均划线价格
  403. $avgLineationPrice = $validLineationPriceCount > 0 ? bcdiv($totalLineationPrice, (string)$validLineationPriceCount, 2) : '0.00';
  404. // 过滤掉0值的划线价格来计算最大最小值
  405. $validLineationPrices = array_filter($lineationPrices, function($price) {
  406. return $price > 0;
  407. });
  408. $updateData = [
  409. 'stocks' => $stocks,
  410. 'spec_type' => 1,
  411. 'min_price' => min($prices),
  412. 'max_price' => max($prices),
  413. 'price' => $avgPrice,
  414. 'min_lineation_price' => !empty($validLineationPrices) ? min($validLineationPrices) : '0.00',
  415. 'max_lineation_price' => !empty($validLineationPrices) ? max($validLineationPrices) : '0.00',
  416. 'lineation_price' => $avgLineationPrice
  417. ];
  418. if ($defaultSkuId > 0) {
  419. $updateData['default_sku_id'] = $defaultSkuId;
  420. }
  421. $this->model->where('id', $goods_id)->update($updateData);
  422. } else {
  423. $this->model->where('id', $goods_id)->update(['spec_type' => 0]);
  424. }
  425. //原来多的删除
  426. foreach ($list as $it) {
  427. $it->delete();
  428. }
  429. }
  430. /**
  431. * 添加
  432. */
  433. public function add()
  434. {
  435. if ($this->request->isPost()) {
  436. $params = $this->request->post("row/a");
  437. if ($params) {
  438. $params = $this->preExcludeFields($params);
  439. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  440. $params[$this->dataLimitField] = $this->auth->id;
  441. }
  442. $result = false;
  443. Db::startTrans();
  444. try {
  445. //是否采用模型验证
  446. if ($this->modelValidate) {
  447. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  448. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  449. // 添加规格数据到验证参数中
  450. if (isset($params['skus']) && isset($params['spec'])) {
  451. $params['spec_data'] = json_decode($params['spec'], true);
  452. $params['sku_data'] = json_decode($params['skus'], true);
  453. }
  454. $this->model->validateFailException(true)->validate($validate);
  455. }
  456. // 备份上架类型,因为status字段将被覆盖为最终状态
  457. $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
  458. // 将online_type映射到status字段用于计算
  459. if (isset($params['online_type'])) {
  460. $params['status'] = $params['online_type'];
  461. unset($params['online_type']);
  462. }
  463. // 先保存商品基础信息(暂时不保存status字段)
  464. $statusBackup = $params['status'] ?? null;
  465. unset($params['status']); // 临时移除status避免冲突
  466. $result = $this->model->allowField(true)->save($params);
  467. // 根据上下架时间自动计算商品状态并更新
  468. $params['status'] = $statusBackup; // 恢复用于计算
  469. $calculatedStatus = $this->calculateGoodsStatus($params);
  470. $this->model->where('id', $this->model->id)->update([
  471. 'status' => $calculatedStatus,
  472. 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
  473. ]);
  474. // 调试输出
  475. \think\Log::write('商品添加 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
  476. //商品规格处理
  477. if (isset($params['skus']) && isset($params['spec'])) {
  478. $skus = (array)json_decode($params['skus'], true);
  479. $spec = (array)json_decode($params['spec'], true);
  480. // 只对多规格进行checkSku验证
  481. if (!empty($spec)) {
  482. $this->checkSku($skus, $spec);
  483. }
  484. // 统一处理SKU
  485. $this->processGoodsSku($params, $this->model->id);
  486. } else {
  487. throw new \Exception('商品规格数据不能为空');
  488. }
  489. //商品属性
  490. if (isset($params['attribute_ids'])) {
  491. GoodsAttr::addGoodsAttr($params['attribute_ids'], $this->model->id);
  492. }
  493. Db::commit();
  494. } catch (ValidateException $e) {
  495. Db::rollback();
  496. $this->error($e->getMessage());
  497. } catch (PDOException $e) {
  498. Db::rollback();
  499. $this->error($e->getMessage());
  500. } catch (Exception $e) {
  501. Db::rollback();
  502. $this->error($e->getMessage());
  503. }
  504. if ($result !== false) {
  505. $this->success();
  506. } else {
  507. $this->error(__('No rows were inserted'));
  508. }
  509. }
  510. $this->error(__('Parameter %s can not be empty', ''));
  511. }
  512. return $this->view->fetch();
  513. }
  514. /**
  515. * 编辑
  516. */
  517. public function edit($ids = null)
  518. {
  519. $row = $this->model->get($ids);
  520. if (!$row) {
  521. $this->error(__('No Results were found'));
  522. }
  523. $adminIds = $this->getDataLimitAdminIds();
  524. if (is_array($adminIds)) {
  525. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  526. $this->error(__('You have no permission'));
  527. }
  528. }
  529. if ($this->request->isPost()) {
  530. $params = $this->request->post("row/a");
  531. if ($params) {
  532. $params = $this->preExcludeFields($params);
  533. $result = false;
  534. Db::startTrans();
  535. try {
  536. //是否采用模型验证
  537. if ($this->modelValidate) {
  538. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  539. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  540. // 添加规格数据到验证参数中
  541. if (isset($params['skus']) && isset($params['spec'])) {
  542. $params['spec_data'] = json_decode($params['spec'], true);
  543. $params['sku_data'] = json_decode($params['skus'], true);
  544. }
  545. $row->validateFailException(true)->validate($validate);
  546. }
  547. // 备份上架类型,因为status字段将被覆盖为最终状态
  548. $originalOnlineType = $params['online_type'] ?? GoodsEnum::ONLINE_TYPE_NOT_NOW;
  549. // 将online_type映射到status字段用于计算
  550. if (isset($params['online_type'])) {
  551. $params['status'] = $params['online_type'];
  552. unset($params['online_type']);
  553. }
  554. // 先保存商品基础信息(暂时不保存status字段)
  555. $statusBackup = $params['status'] ?? null;
  556. unset($params['status']); // 临时移除status避免冲突
  557. $result = $row->allowField(true)->save($params);
  558. // 根据上下架时间自动计算商品状态并更新
  559. $params['status'] = $statusBackup; // 恢复用于计算
  560. $calculatedStatus = $this->calculateGoodsStatus($params);
  561. $this->model->where('id', $row->id)->update([
  562. 'status' => $calculatedStatus,
  563. 'online_type' => $originalOnlineType // 保存原始上架类型用于编辑时回显
  564. ]);
  565. // 调试输出
  566. \think\Log::write('商品编辑 - 上架类型: ' . $originalOnlineType . ', 计算状态: ' . $calculatedStatus, 'info');
  567. //商品规格处理
  568. if (isset($params['skus']) && isset($params['spec'])) {
  569. $skus = (array)json_decode($params['skus'], true);
  570. $spec = (array)json_decode($params['spec'], true);
  571. // 只对多规格进行checkSku验证
  572. if (!empty($spec)) {
  573. $this->checkSku($skus, $spec);
  574. }
  575. // 统一处理SKU
  576. $this->processGoodsSku($params, $row->id);
  577. } else {
  578. throw new \Exception('商品规格数据不能为空');
  579. }
  580. //商品属性
  581. if (isset($params['attribute_ids'])) {
  582. GoodsAttr::addGoodsAttr($params['attribute_ids'], $row->id);
  583. }
  584. Db::commit();
  585. } catch (ValidateException $e) {
  586. Db::rollback();
  587. $this->error($e->getMessage());
  588. } catch (PDOException $e) {
  589. Db::rollback();
  590. $this->error($e->getMessage());
  591. } catch (Exception $e) {
  592. Db::rollback();
  593. $this->error($e->getMessage());
  594. }
  595. if ($result !== false) {
  596. $this->success();
  597. } else {
  598. $this->error(__('No rows were updated'));
  599. }
  600. }
  601. $this->error(__('Parameter %s can not be empty', ''));
  602. }
  603. // 简化查询SKU数据,直接使用冗余的 sku_attr 字段
  604. $list = $this->sku_model->where('goods_id', $row->id)->select();
  605. // 查询规格值的详细信息(包含图片等扩展字段)
  606. $spec_values = [];
  607. if ($row->spec_type == 1) { // 多规格商品
  608. $spec_values = Db::name('shop_goods_sku_spec')
  609. ->alias('gss')
  610. ->field('sp.name as spec_name, sv.value, sv.image, sv.desc')
  611. ->join('shop_spec sp', 'sp.id = gss.spec_id', 'LEFT')
  612. ->join('shop_spec_value sv', 'sv.id = gss.spec_value_id', 'LEFT')
  613. ->where('gss.goods_id', $row->id)
  614. ->group('gss.spec_id, gss.spec_value_id')
  615. ->order('sp.id asc, sv.id asc')
  616. ->select();
  617. }
  618. $this->view->assign("row", $row);
  619. $this->assignconfig('goods', $row);
  620. $this->assignconfig('goods_skus', $list);
  621. $this->assignconfig('spec_values', $spec_values); // 传递规格值详细信息
  622. return $this->view->fetch();
  623. }
  624. /**
  625. * 获取单个商品信息
  626. */
  627. public function info()
  628. {
  629. $id = $this->request->request('id');
  630. if (!$id) {
  631. $this->error('商品ID不能为空');
  632. }
  633. $goods = $this->model
  634. ->with(['Brand'])
  635. ->where('id', $id)
  636. ->find();
  637. if (!$goods) {
  638. $this->error('商品不存在');
  639. }
  640. // 处理图片URL和SKU信息
  641. if ($goods['image']) {
  642. $goods['image'] = cdnurl($goods['image'], true);
  643. }
  644. // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
  645. $sku = \app\common\model\Sku::where('goods_id', $goods['id'])->find();
  646. $goods['sku_id'] = $sku ? $sku['id'] : 0;
  647. // 添加商品类型文本
  648. $goodsTypeMap = GoodsEnum::getGoodsTypeMap();
  649. $goods['type_text'] = isset($goodsTypeMap[$goods['type']]) ? $goodsTypeMap[$goods['type']] : '';
  650. $this->success('获取成功', null, $goods);
  651. }
  652. /**
  653. * 根据ID批量获取商品信息
  654. */
  655. public function get_goods_by_ids()
  656. {
  657. $ids = $this->request->request('ids');
  658. if (!$ids) {
  659. $this->error('请选择商品');
  660. }
  661. $ids = explode(',', $ids);
  662. $list = $this->model
  663. ->with(['Category'])
  664. ->where('id', 'in', $ids)
  665. ->select();
  666. // 处理图片URL和SKU信息
  667. foreach ($list as &$item) {
  668. if ($item['image']) {
  669. $item['image'] = cdnurl($item['image'], true);
  670. }
  671. // 获取商品的第一个SKU ID(单规格商品通常只有一个SKU)
  672. $sku = \app\common\model\Sku::where('goods_id', $item['id'])->find();
  673. $item['sku_id'] = $sku ? $sku['id'] : 0;
  674. }
  675. return json($list);
  676. }
  677. }