Archive.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. namespace app\admin\controller\equipment;
  3. use app\admin\model\equipment\Equipment;
  4. use app\admin\model\equipment\Staff;
  5. use app\admin\model\equipment\Supplier;
  6. use app\common\controller\Backend;
  7. use app\common\model\Attachment;
  8. use PhpOffice\PhpSpreadsheet\IOFactory;
  9. use PhpOffice\PhpSpreadsheet\Reader;
  10. use PhpOffice\PhpSpreadsheet\Shared\Date;
  11. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  12. use think\Db;
  13. use think\Exception;
  14. /**
  15. * 设备档案管理
  16. *
  17. * @icon fa fa-circle-o
  18. */
  19. class Archive extends Backend
  20. {
  21. /**
  22. * Archive模型对象
  23. * @var \app\admin\model\equipment\Archive
  24. */
  25. protected $model = null;
  26. public function _initialize()
  27. {
  28. parent::_initialize();
  29. $this->model = new \app\admin\model\equipment\Archive;
  30. $this->view->assign("statusList", $this->model->getStatusList());
  31. }
  32. public function import()
  33. {
  34. $requestFile = $this->request->request('file');
  35. if (!$requestFile) {
  36. $this->error(__('Parameter %s can not be empty', 'file'));
  37. }
  38. $filePath = ROOT_PATH . DS . 'public' . DS . $requestFile;
  39. if (!is_file($filePath)) {
  40. $this->error(__('No results were found'));
  41. }
  42. //实例化reader
  43. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  44. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  45. $this->error(__('Unknown data format'));
  46. }
  47. if ($ext === 'csv') {
  48. $file = fopen($filePath, 'r');
  49. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  50. $fp = fopen($filePath, "w");
  51. $n = 0;
  52. while ($line = fgets($file)) {
  53. $line = rtrim($line, "\n\r\0");
  54. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  55. if ($encoding != 'utf-8') {
  56. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  57. }
  58. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  59. fwrite($fp, $line . "\n");
  60. } else {
  61. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  62. }
  63. $n++;
  64. }
  65. fclose($file) || fclose($fp);
  66. $reader = new Reader\Csv();
  67. } elseif ($ext === 'xls') {
  68. $reader = new Reader\Xls();
  69. } else {
  70. $reader = new Reader\Xlsx();
  71. }
  72. //加载文件
  73. $insert = [];
  74. try {
  75. if (!$PHPExcel = $reader->load($filePath)) {
  76. $this->error(__('Unknown data format'));
  77. }
  78. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  79. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  80. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  81. $row = [];
  82. for ($currentColumn = 1; $currentColumn <= 9; $currentColumn++) {
  83. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  84. $row[] = is_null($val) ? '' : $val;
  85. }
  86. // 解析excel日期格式
  87. $toTimestamp = Date::excelToTimestamp($row[5]);
  88. $purchasetime = date("Y年m月d日", $toTimestamp);
  89. $insert[] = ['model' => trim($row[0]), 'name' => trim($row[1]), 'parameter' => trim($row[2]), 'amount' => trim($row[3]), 'supplier_code' => trim($row[4]), 'purchasetime' => $purchasetime, 'region' => trim($row[6]), 'responsible_name' => trim($row[7]), 'responsible_mobile' => trim($row[8])];
  90. }
  91. } catch (\Exception $exception) {
  92. $this->error($exception->getMessage());
  93. }
  94. if (empty($insert)) {
  95. $this->error(__('No rows were updated'));
  96. }
  97. // 设备型号是否已存在
  98. $models = array_unique(array_column($insert, 'model'));
  99. $issetModels = $this->model->whereIn('model', $models)->where('status', 'normal')->column('model');
  100. if ($issetModels) {
  101. $this->error('设备型号:' . implode('、', array_unique($issetModels)) . ' 已存在');
  102. }
  103. // 供应商编号是否有效
  104. $supplierCodes = array_filter(array_unique(array_column($insert, 'supplier_code')));
  105. $supplierModel = new Supplier();
  106. $supplierIds = $supplierModel->whereIn('supplier_code', $supplierCodes)->where('status', 'normal')->column('id, supplier_code');
  107. $supplierDiff = array_unique(array_diff($supplierCodes, $supplierIds));
  108. if (count($supplierDiff) > 0) {
  109. $this->error('供应商编号:' . implode('、', $supplierDiff) . ' 不存在');
  110. }
  111. Db::startTrans();
  112. try {
  113. // 新增不存在的员工
  114. $responsibleUsers = array_column($insert, 'responsible_name', 'responsible_mobile');
  115. $responsibleMobiles = array_unique(array_column($insert, 'responsible_mobile'));
  116. $staffModel = new Staff();
  117. $userIds = $staffModel->with('user')->whereIn('user.mobile', $responsibleMobiles)->where('staff.status', 'normal')->column('user.id, mobile');
  118. $responsibleDiff = array_unique(array_diff($responsibleMobiles, $userIds));
  119. if (count($responsibleDiff) > 0) {
  120. foreach ($responsibleDiff as $mobile) {
  121. $data = [
  122. 'nickname' => $responsibleUsers[$mobile],
  123. 'mobile' => $mobile,
  124. 'password' => $mobile
  125. ];
  126. $staffResult = $staffModel->addStaff($data);
  127. if ($staffResult > 0) {
  128. $userIds[$staffResult] = $mobile;
  129. } else {
  130. throw new Exception('手机号码:' . $mobile . ' 员工添加失败。' . __($staffResult));
  131. }
  132. }
  133. }
  134. $userIds = array_flip($userIds);
  135. $supplierIds = array_flip($supplierIds);
  136. foreach ($insert as $key => $params) {
  137. $params['supplier_id'] = !empty($params['supplier_code']) ? $supplierIds[$params['supplier_code']] : 0;
  138. $params['responsible_uid'] = $userIds[$params['responsible_mobile']];
  139. unset($params['supplier_code'], $params['responsible_name'], $params['responsible_mobile']);
  140. $result = $this->model->addArchive($params);
  141. if ($result !== true) {
  142. throw new Exception($params['model'] . ':' . $result);
  143. }
  144. }
  145. Db::commit();
  146. // 删除文件
  147. Attachment::destroy(['url' => $requestFile]);
  148. unlink($filePath);
  149. $this->success();
  150. } catch (Exception $exception) {
  151. Db::rollback();
  152. $this->error($exception->getMessage());
  153. }
  154. }
  155. /**
  156. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
  157. * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
  158. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  159. */
  160. /**
  161. * 查看
  162. */
  163. public function index()
  164. {
  165. $this->relationSearch = true;
  166. //设置过滤方法
  167. $this->request->filter(['strip_tags', 'trim']);
  168. if ($this->request->isAjax()) {
  169. //如果发送的来源是Selectpage,则转发到Selectpage
  170. if ($this->request->request('keyField')) {
  171. return $this->selectpage();
  172. }
  173. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  174. $list = $this->model
  175. ->with(['supplier', 'responsible_user'])
  176. ->where($where)
  177. ->order($sort, $order)
  178. ->paginate($limit);
  179. $result = array("total" => $list->total(), "rows" => $list->items());
  180. return json($result);
  181. }
  182. return $this->view->fetch();
  183. }
  184. /**
  185. * 添加
  186. */
  187. public function add()
  188. {
  189. if ($this->request->isPost()) {
  190. $this->token();
  191. $params = $this->request->post("row/a");
  192. if ($params) {
  193. if (!($params['amount'] > 0)) {
  194. $this->error(__("Number must be greater than 0"));
  195. }
  196. $result = $this->model->addArchive($params);
  197. if ($result === true) {
  198. $this->success();
  199. } else {
  200. $this->error($result);
  201. }
  202. }
  203. $this->error(__('Parameter %s can not be empty', ''));
  204. }
  205. $staffModel = new Staff;
  206. $staffList = $staffModel->getSelectpicker();
  207. $supplierModel = new Supplier;
  208. $supplierList = $supplierModel->getSelectpicker();
  209. $supplierList[0] = __('Please select Supplier_id');
  210. ksort($supplierList);
  211. $this->assignconfig('staffList', $staffList);
  212. $this->view->assign('supplierList', build_select('row[supplier_id]', $supplierList, '', ['class' => 'form-control selectpicker', 'data-rule' => 'required']));
  213. return parent::add();
  214. }
  215. /**
  216. * 编辑
  217. */
  218. public function edit($ids = null)
  219. {
  220. if ($this->request->isPost()) {
  221. $this->token();
  222. $params = $this->request->post("row/a");
  223. $result = $this->model->editArchive($params, $ids);
  224. if ($result === true) {
  225. $this->success();
  226. } else {
  227. $this->error($result);
  228. }
  229. }
  230. $row = $this->model->get($ids);
  231. // $this->modelValidate = true;
  232. if (!$row) {
  233. $this->error(__('No Results were found'));
  234. }
  235. $staffModel = new Staff;
  236. $staffList = $staffModel->getSelectpicker();
  237. $supplierModel = new Supplier;
  238. $supplierList[0] = '请选择供应商';
  239. $supplierList = $supplierModel->getSelectpicker();
  240. ksort($supplierList);
  241. $this->assignconfig('staffList', $staffList);
  242. $this->view->assign('responsibleName', $staffList[$row['responsible_uid']]);
  243. $this->view->assign('supplierList', build_select('row[supplier_id]', $supplierList, $row['supplier_id'], ['class' => 'form-control selectpicker', 'data-rule' => 'required']));
  244. return parent::edit($ids);
  245. }
  246. /**
  247. * 删除
  248. */
  249. public function del($ids = "")
  250. {
  251. if (!$this->request->isPost()) {
  252. $this->error(__("Invalid parameters"));
  253. }
  254. $ids = $ids ? $ids : $this->request->post("ids");
  255. $row = $this->model->get($ids);
  256. $this->modelValidate = true;
  257. if (!$row) {
  258. $this->error(__('No Results were found'));
  259. }
  260. Db::startTrans();
  261. try {
  262. $result = $this->model->destroy($ids);
  263. if (!$result) {
  264. throw new Exception($this->model->getError());
  265. }
  266. // 删除设备
  267. $equipmentModel = new Equipment();
  268. $equipmentIds = $equipmentModel->whereIn('archive_id', $ids)->column('id');
  269. if (count($equipmentIds) > 0) {
  270. $equipmentResult = $equipmentModel->delEquipment($equipmentIds);
  271. if ($equipmentResult !== true) {
  272. throw new Exception($equipmentResult);
  273. }
  274. }
  275. Db::commit();
  276. } catch (Exception $exception) {
  277. Db::rollback();
  278. $this->error($exception->getMessage());
  279. }
  280. $this->success();
  281. }
  282. /**
  283. * 导出设备标签数据
  284. */
  285. public function exportTag($ids = '')
  286. {
  287. $ids = $ids ? $ids : $this->request->post('ids');
  288. $equipmentModel = new Equipment();
  289. $equipments = $equipmentModel->whereIn('archive_id', $ids)->column('archive_id, coding, equipment_code', 'id');
  290. if (!$equipments) {
  291. $this->error(__('No Results were found'));
  292. }
  293. $archives = $this->model->whereIn('id', $ids)->column('*', 'id');
  294. $SupplierModel = new Supplier();
  295. $suppliers = $SupplierModel->whereIn('id', array_unique(array_column($archives, 'supplier_id')))->column('name', 'id');
  296. $userModel = new \app\admin\model\User();
  297. $responsibleUsers = $userModel->whereIn('id', array_unique(array_column($archives, 'responsible_uid')))->column('nickname, mobile', 'id');
  298. $config = get_addon_config('equipment');
  299. if ($config && $config['shorturl']) {
  300. $shorturl = $config['shorturl'];
  301. if (substr($shorturl, -1) != '/') {
  302. $shorturl .= '/';
  303. }
  304. } else {
  305. $shorturl = '';
  306. }
  307. $number = 1;
  308. $columns = [
  309. ['序号', '设备名称', '设备型号', '设备编号', '所在区域', '供应商', '负责人员', '联系电话', '采购时间', '二维码内容']
  310. ];
  311. foreach ($equipments as $equipment) {
  312. $archive = $archives[$equipment['archive_id']];
  313. $columns[] = [
  314. $number,
  315. $archive['name'],
  316. $archive['model'],
  317. $equipment['equipment_code'],
  318. $archive['region'],
  319. $archive['supplier_id'] > 0 ? $suppliers[$archive['supplier_id']] : '',
  320. $responsibleUsers[$archive['responsible_uid']]['nickname'],
  321. $responsibleUsers[$archive['responsible_uid']]['mobile'],
  322. date('Y年m月d日', $archive['purchasetime']),
  323. $shorturl . $equipment['coding']
  324. ];
  325. $number++;
  326. }
  327. $spreadsheet = new Spreadsheet();
  328. $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
  329. $spreadsheet->getDefaultStyle()->getFont()->setSize(12);
  330. $worksheet = $spreadsheet->setActiveSheetIndex(0);
  331. $line = 0;
  332. foreach ($columns as $column) {
  333. $line++;
  334. $col = 0;
  335. foreach ($column as $value) {
  336. $worksheet->setCellValueByColumnAndRow($col, $line, $value);
  337. $col++;
  338. }
  339. }
  340. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  341. header('Content-Disposition: attachment;filename="设备标签数据_' . date('YmdHis') . '.xlsx"');
  342. header('Cache-Control: max-age=0');
  343. // If you're serving to IE 9, then the following may be needed
  344. header('Cache-Control: max-age=1');
  345. // If you're serving to IE over SSL, then the following may be needed
  346. header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  347. header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
  348. header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  349. header('Pragma: public'); // HTTP/1.0
  350. $objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
  351. $objWriter->save('php://output');
  352. exit;
  353. }
  354. }