Goods.php 39 KB

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