SystemCrud.php 19 KB

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