OrderGoods.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <?php
  2. namespace app\admin\controller\order;
  3. use app\admin\library\Auth;
  4. use app\admin\model\books\Books;
  5. use app\admin\model\video\Video;
  6. use app\common\controller\Backend;
  7. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  8. use PhpOffice\PhpSpreadsheet\Reader\Csv;
  9. use PhpOffice\PhpSpreadsheet\Reader\Xls;
  10. use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
  11. use think\Db;
  12. use think\db\exception\BindParamException;
  13. use think\db\exception\DataNotFoundException;
  14. use think\db\exception\ModelNotFoundException;
  15. use think\exception\DbException;
  16. use think\exception\PDOException;
  17. use think\exception\ValidateException;
  18. use think\response\Json;
  19. /**
  20. * 订单商品管理
  21. *
  22. * @icon fa fa-circle-o
  23. */
  24. class OrderGoods extends Backend
  25. {
  26. /**
  27. * OrderGoods模型对象
  28. * @var \app\admin\model\order\OrderGoods
  29. */
  30. protected $model = null;
  31. public function _initialize()
  32. {
  33. parent::_initialize();
  34. $this->model = new \app\admin\model\order\OrderGoods;
  35. $this->view->assign("goodsTypeList", $this->model->getGoodsTypeList());
  36. }
  37. /**
  38. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  39. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  40. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  41. */
  42. /**
  43. * 查看
  44. *
  45. * @return string|Json
  46. * @throws \think\Exception
  47. * @throws DbException
  48. */
  49. public function index()
  50. {
  51. //设置过滤方法
  52. $this->request->filter(['strip_tags', 'trim']);
  53. if (false === $this->request->isAjax()) {
  54. return $this->view->fetch();
  55. }
  56. //如果发送的来源是 Selectpage,则转发到 Selectpage
  57. if ($this->request->request('keyField')) {
  58. return $this->selectpage();
  59. }
  60. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  61. $data = input();
  62. $where_e = [];
  63. if(isset($data['order_id']) && $data['order_id'] != '' && $data['order_id'] != null){
  64. $where_e['order_id'] = $data['order_id'];
  65. }
  66. $list = $this->model
  67. ->where($where)
  68. ->where($where_e)
  69. ->order($sort, $order)
  70. ->paginate($limit);
  71. $item = $list->items();
  72. foreach ($item as $k => $v){
  73. if($v['goods_type'] == '0'){
  74. $books = new Books();
  75. //书籍
  76. $item[$k]['goods'] = $books->where('id',$v['goods_id'])->find();
  77. }else if($v['goods_type'] == '1'){
  78. //视频
  79. $video = new Video();
  80. $item[$k]['goods'] = $video->where('id',$v['goods_id'])->find();
  81. }
  82. }
  83. $result = ['total' => $list->total(), 'rows' => $item];
  84. return json($result);
  85. }
  86. /**
  87. * 回收站
  88. *
  89. * @return string|Json
  90. * @throws \think\Exception
  91. */
  92. public function recyclebin()
  93. {
  94. //设置过滤方法
  95. $this->request->filter(['strip_tags', 'trim']);
  96. if (false === $this->request->isAjax()) {
  97. return $this->view->fetch();
  98. }
  99. [$where, $sort, $order, $offset, $limit] = $this->buildparams();
  100. $list = $this->model
  101. ->onlyTrashed()
  102. ->where($where)
  103. ->order($sort, $order)
  104. ->paginate($limit);
  105. $result = ['total' => $list->total(), 'rows' => $list->items()];
  106. return json($result);
  107. }
  108. /**
  109. * 添加
  110. *
  111. * @return string
  112. * @throws \think\Exception
  113. */
  114. public function add()
  115. {
  116. if (false === $this->request->isPost()) {
  117. return $this->view->fetch();
  118. }
  119. $params = $this->request->post('row/a');
  120. if (empty($params)) {
  121. $this->error(__('Parameter %s can not be empty', ''));
  122. }
  123. $params = $this->preExcludeFields($params);
  124. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  125. $params[$this->dataLimitField] = $this->auth->id;
  126. }
  127. $result = false;
  128. Db::startTrans();
  129. try {
  130. //是否采用模型验证
  131. if ($this->modelValidate) {
  132. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  133. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  134. $this->model->validateFailException()->validate($validate);
  135. }
  136. $result = $this->model->allowField(true)->save($params);
  137. Db::commit();
  138. } catch (ValidateException|PDOException|Exception $e) {
  139. Db::rollback();
  140. $this->error($e->getMessage());
  141. }
  142. if ($result === false) {
  143. $this->error(__('No rows were inserted'));
  144. }
  145. $this->success();
  146. }
  147. /**
  148. * 编辑
  149. *
  150. * @param $ids
  151. * @return string
  152. * @throws DbException
  153. * @throws \think\Exception
  154. */
  155. public function edit($ids = null)
  156. {
  157. $row = $this->model->get($ids);
  158. if (!$row) {
  159. $this->error(__('No Results were found'));
  160. }
  161. $adminIds = $this->getDataLimitAdminIds();
  162. if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
  163. $this->error(__('You have no permission'));
  164. }
  165. if (false === $this->request->isPost()) {
  166. $this->view->assign('row', $row);
  167. return $this->view->fetch();
  168. }
  169. $params = $this->request->post('row/a');
  170. if (empty($params)) {
  171. $this->error(__('Parameter %s can not be empty', ''));
  172. }
  173. $params = $this->preExcludeFields($params);
  174. $result = false;
  175. Db::startTrans();
  176. try {
  177. //是否采用模型验证
  178. if ($this->modelValidate) {
  179. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  180. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  181. $row->validateFailException()->validate($validate);
  182. }
  183. $result = $row->allowField(true)->save($params);
  184. Db::commit();
  185. } catch (ValidateException|PDOException|Exception $e) {
  186. Db::rollback();
  187. $this->error($e->getMessage());
  188. }
  189. if (false === $result) {
  190. $this->error(__('No rows were updated'));
  191. }
  192. $this->success();
  193. }
  194. /**
  195. * 删除
  196. *
  197. * @param $ids
  198. * @return void
  199. * @throws DbException
  200. * @throws DataNotFoundException
  201. * @throws ModelNotFoundException
  202. */
  203. public function del($ids = null)
  204. {
  205. if (false === $this->request->isPost()) {
  206. $this->error(__("Invalid parameters"));
  207. }
  208. $ids = $ids ?: $this->request->post("ids");
  209. if (empty($ids)) {
  210. $this->error(__('Parameter %s can not be empty', 'ids'));
  211. }
  212. $pk = $this->model->getPk();
  213. $adminIds = $this->getDataLimitAdminIds();
  214. if (is_array($adminIds)) {
  215. $this->model->where($this->dataLimitField, 'in', $adminIds);
  216. }
  217. $list = $this->model->where($pk, 'in', $ids)->select();
  218. $count = 0;
  219. Db::startTrans();
  220. try {
  221. foreach ($list as $item) {
  222. $count += $item->delete();
  223. }
  224. Db::commit();
  225. } catch (PDOException|Exception $e) {
  226. Db::rollback();
  227. $this->error($e->getMessage());
  228. }
  229. if ($count) {
  230. $this->success();
  231. }
  232. $this->error(__('No rows were deleted'));
  233. }
  234. /**
  235. * 真实删除
  236. *
  237. * @param $ids
  238. * @return void
  239. */
  240. public function destroy($ids = null)
  241. {
  242. if (false === $this->request->isPost()) {
  243. $this->error(__("Invalid parameters"));
  244. }
  245. $ids = $ids ?: $this->request->post('ids');
  246. $pk = $this->model->getPk();
  247. $adminIds = $this->getDataLimitAdminIds();
  248. if (is_array($adminIds)) {
  249. $this->model->where($this->dataLimitField, 'in', $adminIds);
  250. }
  251. if ($ids) {
  252. $this->model->where($pk, 'in', $ids);
  253. }
  254. $count = 0;
  255. Db::startTrans();
  256. try {
  257. $list = $this->model->onlyTrashed()->select();
  258. foreach ($list as $item) {
  259. $count += $item->delete(true);
  260. }
  261. Db::commit();
  262. } catch (PDOException|Exception $e) {
  263. Db::rollback();
  264. $this->error($e->getMessage());
  265. }
  266. if ($count) {
  267. $this->success();
  268. }
  269. $this->error(__('No rows were deleted'));
  270. }
  271. /**
  272. * 还原
  273. *
  274. * @param $ids
  275. * @return void
  276. */
  277. public function restore($ids = null)
  278. {
  279. if (false === $this->request->isPost()) {
  280. $this->error(__('Invalid parameters'));
  281. }
  282. $ids = $ids ?: $this->request->post('ids');
  283. $pk = $this->model->getPk();
  284. $adminIds = $this->getDataLimitAdminIds();
  285. if (is_array($adminIds)) {
  286. $this->model->where($this->dataLimitField, 'in', $adminIds);
  287. }
  288. if ($ids) {
  289. $this->model->where($pk, 'in', $ids);
  290. }
  291. $count = 0;
  292. Db::startTrans();
  293. try {
  294. $list = $this->model->onlyTrashed()->select();
  295. foreach ($list as $item) {
  296. $count += $item->restore();
  297. }
  298. Db::commit();
  299. } catch (PDOException|Exception $e) {
  300. Db::rollback();
  301. $this->error($e->getMessage());
  302. }
  303. if ($count) {
  304. $this->success();
  305. }
  306. $this->error(__('No rows were updated'));
  307. }
  308. /**
  309. * 批量更新
  310. *
  311. * @param $ids
  312. * @return void
  313. */
  314. public function multi($ids = null)
  315. {
  316. if (false === $this->request->isPost()) {
  317. $this->error(__('Invalid parameters'));
  318. }
  319. $ids = $ids ?: $this->request->post('ids');
  320. if (empty($ids)) {
  321. $this->error(__('Parameter %s can not be empty', 'ids'));
  322. }
  323. if (false === $this->request->has('params')) {
  324. $this->error(__('No rows were updated'));
  325. }
  326. parse_str($this->request->post('params'), $values);
  327. $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
  328. if (empty($values)) {
  329. $this->error(__('You have no permission'));
  330. }
  331. $adminIds = $this->getDataLimitAdminIds();
  332. if (is_array($adminIds)) {
  333. $this->model->where($this->dataLimitField, 'in', $adminIds);
  334. }
  335. $count = 0;
  336. Db::startTrans();
  337. try {
  338. $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
  339. foreach ($list as $item) {
  340. $count += $item->allowField(true)->isUpdate(true)->save($values);
  341. }
  342. Db::commit();
  343. } catch (PDOException|Exception $e) {
  344. Db::rollback();
  345. $this->error($e->getMessage());
  346. }
  347. if ($count) {
  348. $this->success();
  349. }
  350. $this->error(__('No rows were updated'));
  351. }
  352. /**
  353. * 导入
  354. *
  355. * @return void
  356. * @throws PDOException
  357. * @throws BindParamException
  358. */
  359. protected function import()
  360. {
  361. $file = $this->request->request('file');
  362. if (!$file) {
  363. $this->error(__('Parameter %s can not be empty', 'file'));
  364. }
  365. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  366. if (!is_file($filePath)) {
  367. $this->error(__('No results were found'));
  368. }
  369. //实例化reader
  370. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  371. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  372. $this->error(__('Unknown data format'));
  373. }
  374. if ($ext === 'csv') {
  375. $file = fopen($filePath, 'r');
  376. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  377. $fp = fopen($filePath, 'w');
  378. $n = 0;
  379. while ($line = fgets($file)) {
  380. $line = rtrim($line, "\n\r\0");
  381. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  382. if ($encoding !== 'utf-8') {
  383. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  384. }
  385. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  386. fwrite($fp, $line . "\n");
  387. } else {
  388. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  389. }
  390. $n++;
  391. }
  392. fclose($file) || fclose($fp);
  393. $reader = new Csv();
  394. } elseif ($ext === 'xls') {
  395. $reader = new Xls();
  396. } else {
  397. $reader = new Xlsx();
  398. }
  399. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  400. $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  401. $table = $this->model->getQuery()->getTable();
  402. $database = \think\Config::get('database.database');
  403. $fieldArr = [];
  404. $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  405. foreach ($list as $k => $v) {
  406. if ($importHeadType == 'comment') {
  407. $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
  408. $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  409. } else {
  410. $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  411. }
  412. }
  413. //加载文件
  414. $insert = [];
  415. try {
  416. if (!$PHPExcel = $reader->load($filePath)) {
  417. $this->error(__('Unknown data format'));
  418. }
  419. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  420. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  421. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  422. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  423. $fields = [];
  424. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  425. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  426. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  427. $fields[] = $val;
  428. }
  429. }
  430. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  431. $values = [];
  432. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  433. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  434. $values[] = is_null($val) ? '' : $val;
  435. }
  436. $row = [];
  437. $temp = array_combine($fields, $values);
  438. foreach ($temp as $k => $v) {
  439. if (isset($fieldArr[$k]) && $k !== '') {
  440. $row[$fieldArr[$k]] = $v;
  441. }
  442. }
  443. if ($row) {
  444. $insert[] = $row;
  445. }
  446. }
  447. } catch (Exception $exception) {
  448. $this->error($exception->getMessage());
  449. }
  450. if (!$insert) {
  451. $this->error(__('No rows were updated'));
  452. }
  453. try {
  454. //是否包含admin_id字段
  455. $has_admin_id = false;
  456. foreach ($fieldArr as $name => $key) {
  457. if ($key == 'admin_id') {
  458. $has_admin_id = true;
  459. break;
  460. }
  461. }
  462. if ($has_admin_id) {
  463. $auth = Auth::instance();
  464. foreach ($insert as &$val) {
  465. if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  466. $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  467. }
  468. }
  469. }
  470. $this->model->saveAll($insert);
  471. } catch (PDOException $exception) {
  472. $msg = $exception->getMessage();
  473. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  474. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  475. };
  476. $this->error($msg);
  477. } catch (Exception $e) {
  478. $this->error($e->getMessage());
  479. }
  480. $this->success();
  481. }
  482. }