SystemCrud.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  7. * +----------------------------------------------------------------------
  8. * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  9. * +----------------------------------------------------------------------
  10. * | Author: CRMEB Team <admin@crmeb.com>
  11. * +----------------------------------------------------------------------
  12. */
  13. namespace app\adminapi\controller\v1\setting;
  14. use app\adminapi\controller\AuthController;
  15. use app\Request;
  16. use app\services\system\log\SystemFileServices;
  17. use app\services\system\SystemCrudServices;
  18. use app\services\system\SystemMenusServices;
  19. use crmeb\services\CacheService;
  20. use crmeb\services\crud\Make;
  21. use crmeb\services\FileService;
  22. use crmeb\utils\Terminal;
  23. use think\facade\App;
  24. use think\helper\Str;
  25. use think\Response;
  26. /**
  27. * Class SystemCrud
  28. * @author 等风来
  29. * @email 136327134@qq.com
  30. * @date 2023/4/6
  31. * @package app\adminapi\controller\v1\setting
  32. */
  33. class SystemCrud extends AuthController
  34. {
  35. /**
  36. * SystemCrud constructor.
  37. * @param App $app
  38. * @param SystemCrudServices $services
  39. */
  40. public function __construct(App $app, SystemCrudServices $services)
  41. {
  42. parent::__construct($app);
  43. $this->services = $services;
  44. }
  45. /**
  46. * @return \think\Response
  47. * @author 等风来
  48. * @email 136327134@qq.com
  49. * @date 2023/4/11
  50. */
  51. public function index()
  52. {
  53. return app('json')->success($this->services->getList());
  54. }
  55. /**
  56. * @return \think\Response
  57. * @author 等风来
  58. * @email 136327134@qq.com
  59. * @date 2023/4/11
  60. */
  61. public function save($id = 0)
  62. {
  63. $data = $this->request->postMore([
  64. ['pid', 0],//上级菜单id
  65. ['menuName', ''],//菜单名
  66. ['tableName', ''],//表名
  67. ['modelName', ''],//模块名称
  68. ['tableComment', ''],//表备注
  69. ['tableField', []],//表字段
  70. ['tableIndex', []],//索引
  71. ['filePath', []],//生成文件位置
  72. ['isTable', 0],//是否生成表
  73. ['deleteField', []],//删除的表字段
  74. ]);
  75. $fromField = $columnField = [];
  76. foreach ($data['tableField'] as $item) {
  77. //判断字段长度
  78. if (in_array($item['field_type'], ['datetime', 'timestamp', 'time', 'date', 'year']) && $item['limit'] > 6) {
  79. return app('json')->fail('字段' . $item['field'] . '长度不能大于6');
  80. }
  81. //收集列表展示数据
  82. if ($item['is_table'] && !in_array($item['field_type'], ['primaryKey', 'addSoftDelete', 'addSoftDelete'])) {
  83. $columnField[] = [
  84. 'field' => $item['field'],
  85. 'name' => $item['table_name'],
  86. 'type' => $item['from_type'],
  87. ];
  88. }
  89. //收集表单展示数据
  90. if ($item['from_type']) {
  91. $name = $item['table_name'] ?: $item['comment'];
  92. $option = $item['options'] ?? [];
  93. if (!$name) {
  94. return app('json')->fail(500056, [], ['field' => $item['field']]);
  95. }
  96. if (!$option && in_array($item['from_type'], ['radio', 'select'])) {
  97. return app('json')->fail('表单类型为radio或select时,options字段不能为空');
  98. }
  99. $fromField[] = [
  100. 'field' => $item['field'],
  101. 'type' => $item['from_type'],
  102. 'name' => $name,
  103. 'required' => $item['required'],
  104. 'option' => $option,
  105. ];
  106. }
  107. }
  108. if (!$fromField) {
  109. return app('json')->fail(500054);
  110. }
  111. if (!$columnField) {
  112. return app('json')->fail(500055);
  113. }
  114. $data['fromField'] = $fromField;
  115. $data['columnField'] = $columnField;
  116. if (!$data['tableName']) {
  117. return app('json')->fail(500045);
  118. }
  119. $this->services->createCrud($id, $data);
  120. return app('json')->success(500046);
  121. }
  122. /**
  123. * 获取创建文件的目录存放位置
  124. * @return \think\Response
  125. * @author 等风来
  126. * @email 136327134@qq.com
  127. * @date 2023/4/11
  128. */
  129. public function getFilePath()
  130. {
  131. [$tableName] = $this->request->postMore([
  132. ['tableName', ''],
  133. ], true);
  134. if (!$tableName) {
  135. return app('json')->fail(500045);
  136. }
  137. if (in_array($tableName, SystemCrudServices::NOT_CRUD_TABANAME)) {
  138. return app('json')->fail(500044);
  139. }
  140. $routeName = 'crud/' . Str::snake($tableName);
  141. $key = 'id';
  142. $tableField = [];
  143. $field = $this->services->getColumnNamesList($tableName);
  144. foreach ($field as $item) {
  145. if ($item['primaryKey']) {
  146. $key = $item['name'];
  147. }
  148. $tableField[] = [
  149. 'field' => $item['name'],
  150. 'field_type' => $item['type'],
  151. 'primaryKey' => (bool)$item['primaryKey'],
  152. 'default' => $item['default'],
  153. 'limit' => $item['limit'],
  154. 'comment' => $item['comment'],
  155. 'required' => false,
  156. 'is_table' => false,
  157. 'table_name' => '',
  158. 'from_type' => '',
  159. ];
  160. }
  161. $make = $this->services->makeFile($tableName, $routeName, false, [
  162. 'menuName' => '',
  163. 'key' => $key,
  164. 'fromField' => [],
  165. 'columnField' => [],
  166. ]);
  167. $makePath = [];
  168. foreach ($make as $k => $item) {
  169. $makePath[$k] = $item['path'];
  170. }
  171. return app('json')->success(compact('makePath', 'tableField'));
  172. }
  173. /**
  174. * @param $id
  175. * @return \think\Response
  176. * @author 等风来
  177. * @email 136327134@qq.com
  178. * @date 2023/4/12
  179. */
  180. public function read($id)
  181. {
  182. if (!$id) {
  183. return app('json')->fail(500035);
  184. }
  185. $info = $this->services->get($id);
  186. if (!$info) {
  187. return app('json')->fail(500043);
  188. }
  189. $routeName = 'crud/' . Str::snake($info->table_name);
  190. $column = $this->services->getColumnNamesList($info->table_name);
  191. $key = 'id';
  192. foreach ($column as $value) {
  193. if ($value['primaryKey']) {
  194. $key = $value['name'];
  195. break;
  196. }
  197. }
  198. $softDelete = false;
  199. foreach ((array)$info->field['tableField'] as $item) {
  200. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  201. $softDelete = true;
  202. break;
  203. }
  204. }
  205. $make = $this->services->makeFile($info->table_name, $routeName, false, [
  206. 'menuName' => $info->name,
  207. 'modelName' => $info->model_name,
  208. 'key' => $key,
  209. 'softDelete' => $softDelete,
  210. 'fromField' => $info->field['fromField'] ?? [],
  211. 'columnField' => $info->field['columnField'] ?? [],
  212. ]);
  213. $data = [];
  214. foreach ($make as $item) {
  215. if (in_array($item['path'], ['pages', 'router', 'api'])) {
  216. $path = Make::adminTemplatePath() . $item['path'];
  217. } else {
  218. $path = app()->getRootPath() . $item['path'];
  219. }
  220. $item['name'] = $item['path'];
  221. try {
  222. $item['content'] = file_get_contents($path, LOCK_EX);
  223. $data[] = $item;
  224. } catch (\Throwable $e) {
  225. }
  226. }
  227. $info = $info->toArray();
  228. //记录没有修改之前的数据
  229. foreach ((array)$info['field']['tableField'] as $key => $item) {
  230. $item['default_field'] = $item['field'];
  231. $item['default_limit'] = $item['limit'];
  232. $item['default_field_type'] = $item['field_type'];
  233. $item['default_comment'] = $item['comment'];
  234. $item['default_default'] = $item['default'];
  235. $item['is_table'] = !!$item['is_table'];
  236. $item['primaryKey'] = isset($item['primaryKey']) ? (int)$item['primaryKey'] : 0;
  237. $info['field']['tableField'][$key] = $item;
  238. }
  239. //对比数据库,是否有新增字段
  240. $newColumn = [];
  241. $fieldAll = array_column($info['field']['tableField'], 'field');
  242. foreach ($column as $value) {
  243. if (!in_array($value['name'], $fieldAll)) {
  244. $newColumn[] = [
  245. 'field' => $value['name'],
  246. 'field_type' => $value['type'],
  247. 'primaryKey' => $value['primaryKey'] ? 1 : 0,
  248. 'default' => $value['default'],
  249. 'limit' => $value['limit'],
  250. 'comment' => $value['comment'],
  251. 'required' => '',
  252. 'is_table' => '',
  253. 'table_name' => '',
  254. 'from_type' => '',
  255. 'default_field' => $value['name'],
  256. 'default_limit' => $value['limit'],
  257. 'default_field_type' => $value['type'],
  258. 'default_comment' => $value['comment'],
  259. 'default_default' => $value['default'],
  260. ];
  261. }
  262. }
  263. if ($newColumn) {
  264. $info['field']['tableField'] = array_merge($newColumn, $info['field']['tableField']);
  265. }
  266. $keyInfo = [];
  267. $deleteInfo = [];
  268. foreach ($info['field']['tableField'] as $key => $item) {
  269. if ($item['primaryKey']) {
  270. $keyInfo = $item;
  271. unset($info['field']['tableField'][$key]);
  272. }
  273. if ($item['field_type'] == 'addSoftDelete') {
  274. $deleteInfo = $item;
  275. unset($info['field']['tableField'][$key]);
  276. }
  277. }
  278. if ($keyInfo) {
  279. array_unshift($info['field']['tableField'], $keyInfo);
  280. }
  281. if ($deleteInfo) {
  282. array_push($info['field']['tableField'], $deleteInfo);
  283. }
  284. $info['field']['pid'] = (int)$info['field']['pid'];
  285. return app('json')->success(['file' => $data, 'crudInfo' => $info]);
  286. }
  287. /**
  288. * @param Request $request
  289. * @param SystemFileServices $service
  290. * @param $id
  291. * @return Response
  292. * @author 等风来
  293. * @email 136327134@qq.com
  294. * @date 2023/4/24
  295. */
  296. public function savefile(Request $request, SystemFileServices $service, $id)
  297. {
  298. $comment = $request->param('comment');
  299. $filepath = $request->param('filepath');
  300. if (empty($filepath) || !$id) {
  301. return app('json')->fail(410087);
  302. }
  303. $crudInfo = $this->services->get($id, ['make_path']);
  304. if (!$crudInfo) {
  305. return app('json')->fail('修改的CRUD文件不存在');
  306. }
  307. $makeFilepath = '';
  308. foreach ($crudInfo->make_path as $key => $item) {
  309. $path = $item;
  310. if (in_array($key, ['pages', 'router', 'api'])) {
  311. $item = Make::adminTemplatePath() . $item;
  312. } else {
  313. $item = app()->getRootPath() . $item;
  314. }
  315. if ($filepath == $path) {
  316. $makeFilepath = $item;
  317. break;
  318. }
  319. }
  320. if (!$makeFilepath || !in_array($filepath, $crudInfo->make_path)) {
  321. return app('json')->fail('您没有权限修改此文件');
  322. }
  323. $res = $service->savefile($makeFilepath, $comment);
  324. if ($res) {
  325. return app('json')->success(100000);
  326. } else {
  327. return app('json')->fail(100006);
  328. }
  329. }
  330. /**
  331. * 获取tree菜单
  332. * @return \think\Response
  333. * @author 等风来
  334. * @email 136327134@qq.com
  335. * @date 2023/4/11
  336. */
  337. public function getMenus()
  338. {
  339. return app('json')->success(app()->make(SystemMenusServices::class)
  340. ->getList(['auth_type' => 1, 'is_show' => 1], ['auth_type', 'pid', 'id', 'menu_name as label', 'id as value']));
  341. }
  342. /**
  343. * 获取创建表数据类型
  344. * @return \think\Response
  345. * @author 等风来
  346. * @email 136327134@qq.com
  347. * @date 2023/4/11
  348. */
  349. public function columnType()
  350. {
  351. return app('json')->success($this->services->getTabelRule());
  352. }
  353. /**
  354. * @param SystemMenusServices $services
  355. * @param $id
  356. * @return \think\Response
  357. * @author 等风来
  358. * @email 136327134@qq.com
  359. * @date 2023/4/11
  360. */
  361. public function delete(SystemMenusServices $services, $id)
  362. {
  363. if (!$id) {
  364. return app('json')->fail(500035);
  365. }
  366. $info = $this->services->get($id);
  367. if (!$info) {
  368. return app('json')->fail(500042);
  369. }
  370. $services->transaction(function () use ($services, $info) {
  371. if ($info->menu_ids) {
  372. $services->deleteMenus($info->menu_ids);
  373. }
  374. $info->delete();
  375. });
  376. if ($info->make_path) {
  377. try {
  378. foreach ($info->make_path as $key => $item) {
  379. if (in_array($key, ['pages', 'router', 'api'])) {
  380. $item = Make::adminTemplatePath() . $item;
  381. } else {
  382. $item = app()->getRootPath() . $item;
  383. }
  384. unlink($item);
  385. }
  386. } catch (\Throwable $e) {
  387. return app('json')->success(500041, [], ['message' => $e->getMessage()]);
  388. }
  389. }
  390. return app('json')->success(100002);
  391. }
  392. /**
  393. * 下载文件
  394. * @param $id
  395. * @return Response
  396. * @author 等风来
  397. * @email 136327134@qq.com
  398. * @date 2023/4/15
  399. */
  400. public function download($id)
  401. {
  402. if (!$id) {
  403. return app('json')->fail(500035);
  404. }
  405. $info = $this->services->get($id);
  406. if (!$info) {
  407. return app('json')->fail(500039);
  408. }
  409. $zipPath = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name);
  410. $zipName = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name) . '.zip';
  411. if (is_file($zipName)) {
  412. unlink($zipName);
  413. }
  414. $makePath = $info->make_path ?? [];
  415. foreach ($makePath as $key => $item) {
  416. if (in_array($key, ['pages', 'router', 'api'])) {
  417. $item = $zipPath . str_replace(dirname(app()->getRootPath()), '', Make::adminTemplatePath()) . $item;
  418. } else {
  419. $item = $zipPath . DS . $item;
  420. }
  421. $makePath[$key] = $item;
  422. }
  423. $routeName = 'crud/' . Str::snake($info->table_name);
  424. $column = $this->services->getColumnNamesList($info->table_name);
  425. $key = 'id';
  426. foreach ($column as $value) {
  427. if ($value['primaryKey']) {
  428. $key = $value['name'];
  429. break;
  430. }
  431. }
  432. $softDelete = false;
  433. foreach ((array)$info->field['tableField'] as $item) {
  434. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  435. $softDelete = true;
  436. break;
  437. }
  438. }
  439. $this->services->makeFile($info->table_name, $routeName, true, [
  440. 'menuName' => $info->name,
  441. 'key' => $key,
  442. 'softDelete' => $softDelete,
  443. 'fromField' => $info->field['fromField'] ?? [],
  444. 'columnField' => $info->field['columnField'] ?? [],
  445. ], $makePath, $zipPath);
  446. if (!extension_loaded('zip')) {
  447. return app('json')->fail(500040);
  448. }
  449. $fileService = new FileService();
  450. $fileService->addZip($zipPath, $zipName, app()->getRootPath() . 'backup');
  451. $key = md5($zipName);
  452. CacheService::set($key, [
  453. 'path' => $zipName,
  454. 'fileName' => Str::camel($info->table_name) . '.zip',
  455. ], 300);
  456. return app('json')->success(['download_url' => sys_config('site_url') . '/adminapi/download/' . $key]);
  457. }
  458. /**
  459. * 获取权限路由
  460. * @param $tableName
  461. * @return Response
  462. * @author 等风来
  463. * @email 136327134@qq.com
  464. * @date 2023/4/20
  465. */
  466. public function getRouteList($tableName)
  467. {
  468. $info = $this->services->get(['table_name' => $tableName]);
  469. if (!$info) {
  470. return app('json')->fail('crud详情查询失败');
  471. }
  472. $routeList = app()->make(SystemMenusServices::class)->getColumn([
  473. ['id', 'in', $info->menu_ids],
  474. ['auth_type', '=', 2]
  475. ], 'methods,api_url');
  476. $newRoute = [];
  477. foreach ($routeList as $item) {
  478. if ($item['methods'] == 'GET') {
  479. if (strstr($item['api_url'], 'create')) {
  480. $newRoute['create'] = $item['api_url'];
  481. } else if (strstr($item['api_url'], 'edit')) {
  482. $newRoute['edit'] = $item['api_url'];
  483. } else {
  484. $newRoute['index'] = $item['api_url'];
  485. }
  486. } else if ($item['methods'] == 'DELETE') {
  487. $newRoute['delete'] = $item['api_url'];
  488. }
  489. }
  490. $column = $this->services->getColumnNamesList($info->table_name);
  491. $key = 'id';
  492. foreach ($column as $value) {
  493. if ($value['primaryKey']) {
  494. $key = $value['name'];
  495. break;
  496. }
  497. }
  498. $columns = [
  499. [
  500. 'title' => 'ID',
  501. 'key' => $key,
  502. 'from_type' => '',
  503. ]
  504. ];
  505. foreach ((array)$info->field['tableField'] as $item) {
  506. if (isset($item['is_table']) && $item['is_table']) {
  507. $columns[] = [
  508. 'title' => $item['table_name'] ?: $item['comment'],
  509. 'key' => $item['field'],
  510. 'from_type' => $item['from_type'],
  511. ];
  512. }
  513. }
  514. $route = $newRoute;
  515. return app('json')->success(compact('key', 'route', 'columns'));
  516. }
  517. /**
  518. * @return string
  519. * @author 等风来
  520. * @email 136327134@qq.com
  521. * @date 2023/4/14
  522. */
  523. public function npm()
  524. {
  525. $terminal = new Terminal();
  526. $adminPath = $terminal->adminTemplatePath();
  527. $adminPath = dirname($adminPath);
  528. try {
  529. $dir = $adminPath . DS . 'node_modules';
  530. if (!is_dir($dir)) {
  531. // $terminal->run('npm-install');
  532. }
  533. // $res = $terminal->run('npm-build');
  534. } catch (\Throwable $e) {
  535. $terminal->echoOutputFlag($e->getMessage());
  536. }
  537. if (!is_dir($adminPath . DS . 'dist')) {
  538. echo Response::create([
  539. 'message' => '打包失败',
  540. ], 'json')->getContent();
  541. }
  542. $build = public_path() . config('app.admin_prefix');
  543. // $this->app->make(FileService::class)->copyDir($adminPath . DS . 'dist', $build);
  544. // echo $res;
  545. }
  546. }