Goods.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. <?php
  2. namespace app\admin\controller\qingdong\product;
  3. use addons\qingdong\model\Product;
  4. use addons\qingdong\model\Producttype;
  5. use addons\qingdong\model\Staff;
  6. use app\admin\controller\qingdong\Base;
  7. use addons\qingdong\model\Specs;
  8. use addons\qingdong\model\GoodsUnit;
  9. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  10. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  11. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  12. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  13. use PhpOffice\PhpSpreadsheet\RichText\RichText;
  14. use think\Db;
  15. use think\Exception;
  16. /**
  17. * 商品管理
  18. * @icon fa fa-pied-piper-pp
  19. */
  20. class Goods extends Base
  21. {
  22. /**
  23. * Goods模型对象
  24. * @var \addons\qingdong\model\Goods
  25. */
  26. protected $model = null;
  27. public function _initialize()
  28. {
  29. parent::_initialize();
  30. $this->model = new \addons\qingdong\model\Goods();
  31. }
  32. /**
  33. * 查看
  34. */
  35. public function index()
  36. {
  37. //当前是否为关联查询
  38. $this->relationSearch = false;
  39. //设置过滤方法
  40. $this->request->filter(['strip_tags', 'trim']);
  41. if ($this->request->isAjax()) {
  42. //如果发送的来源是Selectpage,则转发到Selectpage
  43. if ($this->request->request('keyField')) {
  44. return $this->selectpage();
  45. }
  46. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  47. $list = $this->model
  48. ->with(['type','product'])
  49. ->where($where)
  50. ->order($sort, $order)
  51. ->paginate($limit);
  52. $result = array("total" => $list->total(), "rows" => $list->items());
  53. return json($result);
  54. }
  55. return $this->view->fetch();
  56. }
  57. /**
  58. * 新增
  59. * @return string|void
  60. */
  61. public function add()
  62. {
  63. if ($this->request->isPost()) {
  64. $params = $this->request->post("row/a");
  65. if ($params) {
  66. $params = $this->preExcludeFields($params);
  67. $productModel = new Product();
  68. if($params['is_specs'] ==1){ //有规格
  69. $product = json_decode($params['product'], true);
  70. if(!$product){
  71. $this->error('请选择规格');
  72. }
  73. foreach ($product as $k=>$v) {
  74. if(!$v['price']){
  75. $this->error('零销价必须大于0');
  76. }
  77. if(!$v['wholesale']){
  78. $this->error('批发价必须大于0');
  79. }
  80. }
  81. $addProduct = [];
  82. foreach ($product as $k=>$v) {
  83. $addProduct[] = [
  84. 'num' => 'P'.time().$k,
  85. 'type_id' => $params['type_id'],
  86. 'type' => $v['type'],
  87. 'name' => $params['name'] . $v['name'],
  88. 'price' => $v['price'],
  89. 'wholesale' => $v['wholesale'],
  90. 'cost_price' => $v['cost_price'],
  91. 'img' => $v['avatar'],
  92. 'unit' => $params['unit'],
  93. 'status' => '上架',
  94. 'description' => $v['remarks'],
  95. 'createtime' => time(),
  96. 'updatetime' => time()
  97. ];
  98. }
  99. $result = false;
  100. Db::startTrans();
  101. try {
  102. $params['price'] = 0;
  103. $params['wholesale']=0;
  104. $result = $this->model->allowField(true)->save($params);
  105. foreach ($addProduct as $k => $v) {
  106. $v['goods_id'] = $this->model->id;
  107. $addProduct[$k] = $v;
  108. }
  109. $productResult = $productModel->allowField(true)->saveAll($addProduct);
  110. if(!$result || !$productResult){
  111. throw new Exception('添加失败');
  112. }
  113. Db::commit();
  114. } catch (Exception $e) {
  115. Db::rollback();
  116. $this->error($e->getMessage());
  117. }
  118. }else{
  119. Db::startTrans();
  120. try {
  121. $result = $this->model->allowField(true)->save($params);
  122. $addProduct = [
  123. 'goods_id' => $this->model->id,
  124. 'num' => 'P'.time(),
  125. 'type_id' => $params['type_id'],
  126. 'name' => $params['name'],
  127. 'price' => $params['price'],
  128. 'wholesale' => $params['wholesale'],
  129. 'cost_price' => $params['cost_price'],
  130. 'img' => $params['img'],
  131. 'unit' => $params['unit'],
  132. 'description' => $params['description'],
  133. 'status' => '上架',
  134. 'createtime' => time(),
  135. 'updatetime' => time()
  136. ];
  137. $productResult = $productModel->allowField(true)->save($addProduct);
  138. if(!$result || !$productResult){
  139. throw new Exception('添加失败');
  140. }
  141. Db::commit();
  142. } catch (Exception $e) {
  143. Db::rollback();
  144. $this->error($e->getMessage());
  145. }
  146. }
  147. $this->success();
  148. }
  149. $this->error(__('Parameter %s can not be empty', ''));
  150. }
  151. $unit = GoodsUnit::where(['status'=>1])->order('sort desc')->select();
  152. $num = 'G'.genRandomString(10,2);
  153. $this->assign('num', $num);
  154. $this->assign('unit', $unit);
  155. return $this->view->fetch();
  156. }
  157. /**
  158. * 编辑
  159. * @return string|void
  160. */
  161. public function edit($ids=null)
  162. {
  163. if ($this->request->isPost()) {
  164. $params = $this->request->post("row/a");
  165. if ($params) {
  166. $params = $this->preExcludeFields($params);
  167. $productModel = new Product();
  168. if($params['is_specs'] ==1) { //有规格
  169. $product = json_decode($params['product'], true);
  170. if(!$product){
  171. $this->error('请选择规格');
  172. }
  173. foreach ($product as $k=>$v) {
  174. if(!$v['price']){
  175. $this->error('零销价必须大于0');
  176. }
  177. if(!$v['wholesale']){
  178. $this->error('批发价必须大于0');
  179. }
  180. }
  181. $result = false;
  182. $productId = [];
  183. Db::startTrans();
  184. try {
  185. foreach ($product as $k=>$v) {
  186. $addProduct = [
  187. 'type_id' => $params['type_id'],
  188. 'type' => $v['type'],
  189. 'name' => $params['name'] . $v['name'],
  190. 'price' => $v['price'],
  191. 'wholesale' => $v['wholesale'],
  192. 'cost_price' => $v['cost_price'],
  193. 'img' => $v['avatar'],
  194. 'unit' => $params['unit'],
  195. 'status' => '上架',
  196. 'description' => $v['remarks'],
  197. 'createtime' => time(),
  198. 'updatetime' => time()
  199. ];
  200. $productData = $productModel->where(array('goods_id'=>$ids,'type'=>$v['type']))->find();
  201. if($productData){
  202. $addProduct['name'] = $v['name'];
  203. $productRes = $productModel->where(array('id'=>$productData['id']))->update($addProduct);
  204. $productIds = $productData['id'];
  205. }else{
  206. $addProduct['goods_id']=$ids;
  207. $addProduct['num']= 'P'.time().$k;
  208. $addProduct['createtime'] =time();
  209. $productRes = $productModel->allowField(true)->create($addProduct);
  210. $productIds = (int)$productModel->getLastInsID();
  211. }
  212. if(!$productRes){
  213. throw new Exception('修改失败');
  214. }
  215. $productId[] =$productIds;
  216. }
  217. $productModel->where(['id'=>['not in',$productId],'goods_id'=>$ids])->update(['updatetime'=>time(),'deletetime'=>time()]);
  218. $params['price'] = 0;
  219. $params['wholesale']=0;
  220. $result = $this->model->allowField(true)->save($params,['id'=>$ids]);
  221. if(!$result){
  222. throw new Exception('修改失败');
  223. }
  224. Db::commit();
  225. } catch (Exception $e) {
  226. Db::rollback();
  227. $this->error($e->getMessage());
  228. }
  229. }else{
  230. try {
  231. $addProduct = [
  232. 'goods_id' => $ids,
  233. 'num' => 'P'.time(),
  234. 'type_id' => $params['type_id'],
  235. 'name' => $params['name'],
  236. 'price' => $params['price'],
  237. 'wholesale' => $params['wholesale'],
  238. 'cost_price' => $params['cost_price'],
  239. 'img' => $params['img'],
  240. 'unit' => $params['unit'],
  241. 'description' => $params['description'],
  242. 'status' => '上架',
  243. 'createtime' => time(),
  244. 'updatetime' => time()
  245. ];
  246. $productinfo = $productModel->where(['goods_id'=>$ids])->find();
  247. if($productinfo){
  248. $productModel->allowField(true)->save($addProduct,['goods_id'=>$ids]);
  249. }else{
  250. $productModel->allowField(true)->save($addProduct);
  251. }
  252. $result = $this->model->allowField(true)->save($params,['id'=>$ids]);
  253. if(!$result){
  254. throw new Exception('修改失败');
  255. }
  256. Db::commit();
  257. } catch (Exception $e) {
  258. Db::rollback();
  259. $this->error($e->getMessage());
  260. }
  261. }
  262. $this->success();
  263. }
  264. $this->error(__('Parameter %s can not be empty', ''));
  265. }
  266. $row = $this->model->with(['type'])->where(['id'=>$ids])->find()->toArray();
  267. $product=Product::where(['goods_id'=>$ids])->select();
  268. $row['product']=json_encode($product,true);
  269. $unit = GoodsUnit::where(['status'=>1])->order('sort desc')->select();
  270. $this->assign('unit', $unit);
  271. $this->assign('row', $row);
  272. return $this->view->fetch();
  273. }
  274. //导入
  275. public function import()
  276. {
  277. set_time_limit(0);
  278. if ($this->request->isPost()) {
  279. $file = $this->request->request('file');
  280. $staff_id = $this->request->request('staff_id', 0);
  281. if (!$file) {
  282. $this->error(__('Parameter %s can not be empty', 'file'));
  283. }
  284. $filePath = ROOT_PATH . 'public' . $file;
  285. if (!is_file($filePath)) {
  286. $this->error(__('No results were found'));
  287. }
  288. //实例化reader
  289. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  290. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  291. $this->error(__('Unknown data format'));
  292. }
  293. if ($ext === 'csv') {
  294. $file = fopen($filePath, 'r');
  295. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  296. $fp = fopen($filePath, "w");
  297. $n = 0;
  298. while ($line = fgets($file)) {
  299. $line = rtrim($line, "\n\r\0");
  300. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  301. if ($encoding != 'utf-8') {
  302. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  303. }
  304. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  305. fwrite($fp, $line . "\n");
  306. } else {
  307. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  308. }
  309. $n++;
  310. }
  311. fclose($file) || fclose($fp);
  312. $reader = new Csv();
  313. } elseif ($ext === 'xls') {
  314. $reader = new Xls();
  315. } else {
  316. $reader = new Xlsx();
  317. }
  318. if (!$PHPExcel = $reader->load($filePath)) {
  319. $this->error(__('Unknown data format'));
  320. }
  321. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  322. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  323. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  324. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  325. //开始读取数据
  326. $fields = [];
  327. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  328. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  329. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  330. $fields[$currentRow][] = $val;
  331. if($val instanceof RichText) {//富文本转换字符串
  332. $val = $val->__toString();
  333. }
  334. $values[] = is_null($val) ? '' : trim($val);
  335. }
  336. }
  337. if (!isset($fields[1])) {
  338. $this->error('导入文件第一行没有数据');
  339. }
  340. $types=Producttype::withTrashed()->where([])->column('id','name');
  341. $addShop=[];
  342. $errorInfo=[];
  343. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  344. $values = [];
  345. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  346. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  347. if($val instanceof RichText) {//富文本转换字符串
  348. $val = $val->__toString();
  349. }
  350. $values[] = is_null($val) ? '' : trim($val);
  351. }
  352. if(!$values[0]){
  353. continue;
  354. }
  355. $params=[
  356. 'name'=>$values[0],
  357. 'type_id'=>$types[$values[1]]??0,
  358. 'price'=>$values[2],
  359. 'unit'=>$values[3],
  360. 'wholesale'=>$values[4],
  361. 'cost_price'=>$values[5],
  362. 'status'=>'上架',
  363. 'createtime'=>time(),
  364. 'updatetime'=>time()
  365. ];
  366. Db::startTrans();
  367. try {
  368. $goodsRe = $this->model->allowField(true)->save($params);
  369. if(!$goodsRe){
  370. throw new Exception('商品导入失败');
  371. }
  372. $addProduct = [
  373. 'goods_id' => $this->model->getLastInsID(),
  374. 'num' => 'P'.time(),
  375. 'type_id' => $types[$values[1]]??0,
  376. 'name' => $values[0],
  377. 'price' => $values[2],
  378. 'unit'=>$values[3],
  379. 'wholesale'=>$values[4],
  380. 'cost_price'=>$values[5],
  381. 'status' => '上架',
  382. 'createtime' => time(),
  383. 'updatetime' => time()
  384. ];
  385. $productModel = new Product();
  386. $productResult = $productModel->allowField(true)->save($addProduct);
  387. if(!$productResult){
  388. throw new Exception('商品导入失败');
  389. }
  390. Db::commit();
  391. } catch (Exception $e) {
  392. Db::rollback();
  393. $this->error($e->getMessage());
  394. }
  395. }
  396. if (!empty($errorInfo)) {
  397. $this->error(implode(',', $errorInfo));
  398. }
  399. $this->success('导入成功');
  400. }
  401. $this->assign('staffs', Staff::getList());
  402. return $this->view->fetch();
  403. }
  404. /**
  405. * 商品详情
  406. */
  407. public function detail($ids = null)
  408. {
  409. $row = $this->model->with(['type'])->where(['id'=>$ids])->find();
  410. $this->assign('row', $row);
  411. $this->assign('ids', $ids);
  412. return $this->view->fetch();
  413. }
  414. /**
  415. * 获取商品 产品列表
  416. */
  417. public function get_product()
  418. {
  419. $goods_id = input('goods_id');
  420. $where = [];
  421. if ($keyValue = $this->request->request("keyValue")) {
  422. $where['id'] = $keyValue;
  423. }
  424. $name = input('name');
  425. if (!empty($name)) {
  426. $where['name'] = ['like', '%' . $name . '%'];
  427. }
  428. if ($goods_id) {
  429. $where['goods_id'] = $goods_id;
  430. }
  431. $product = Product::where($where)->with(['producttype'])->order('id desc')->paginate();
  432. $result = array("total" => $product->total(), "rows" => $product->items());
  433. return json($result);
  434. }
  435. /**
  436. * 获取产品分类
  437. */
  438. public function get_product_type()
  439. {
  440. $pageSize = input('pageSize');
  441. $pageNumber = input('pageNumber');
  442. $where = [];
  443. if ($keyValue = $this->request->request("keyValue")) {
  444. $where['id'] = $keyValue;
  445. }
  446. if(empty($pageSize) && empty($keyValue)){
  447. return json(Producttype::where($where)->field('id,name')->select());
  448. }
  449. $name = input('name');
  450. if (!empty($name)) {
  451. $where['name'] = ['like', '%' . $name . '%'];
  452. }
  453. $producttype = Producttype::where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
  454. return json(['list' => $producttype->items(), 'total' => $producttype->total()]);
  455. }
  456. /**
  457. * 获取规格
  458. */
  459. public function get_specs()
  460. {
  461. $where = [];
  462. if ($keyValue = $this->request->request("keyValue")) {
  463. $where['id'] = $keyValue;
  464. }
  465. $name = input('name');
  466. if (!empty($name)) {
  467. $where['name'] = ['like', '%' . $name . '%'];
  468. }
  469. $countrys = Specs::where($where)->field('id,name')->order('id desc')->select();
  470. return json(['list' => $countrys, 'total' => count($countrys)]);
  471. }
  472. /**
  473. * 获取规格详情
  474. */
  475. public function get_specs_detail()
  476. {
  477. $ids = input('ids');
  478. $specs_id = input('specs_id');
  479. $good = [];
  480. if($ids){
  481. $where['goods_id'] = $ids;
  482. $product = Product::where($where)->column('type');
  483. if($product){
  484. foreach($product as $k=>$v){
  485. $good[$v] = $v;
  486. }
  487. }
  488. }
  489. $specs = Specs::where(['id' => $specs_id])->find();
  490. $content = json_decode($specs['content'], true);
  491. if($content && is_array($content)){
  492. foreach($content as $k=>$v){
  493. $content[$k]['check'] =0;
  494. if($good){
  495. if(key_exists($v['name'],$good)){
  496. $content[$k]['check'] =1;
  497. }
  498. }
  499. }
  500. }
  501. $this->success('请求成功', '', $content);
  502. }
  503. /**
  504. * 删除商品
  505. */
  506. public function del($ids = "")
  507. {
  508. if (!$this->request->isPost()) {
  509. $this->error(__("Invalid parameters"));
  510. }
  511. $ids = $ids ? $ids : $this->request->post("ids");
  512. $row = $this->model->get($ids);
  513. $this->modelValidate = true;
  514. if (!$row) {
  515. $this->error(__('No Results were found'));
  516. }
  517. $model=new Product();
  518. $model->where(['goods_id'=>$ids])->delete();
  519. $row->delete();
  520. $this->success();
  521. }
  522. }