Goods.php 40 KB

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