SystemCrud.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. $info['field']['tableField'][$key] = $item;
  230. }
  231. //对比数据库,是否有新增字段
  232. $newColumn = [];
  233. $fieldAll = array_column($info['field']['tableField'], 'field');
  234. foreach ($column as $value) {
  235. if (!in_array($value['name'], $fieldAll)) {
  236. $newColumn[] = [
  237. 'field' => $value['name'],
  238. 'field_type' => $value['type'],
  239. 'primaryKey' => $value['primaryKey'] ? 1 : 0,
  240. 'default' => $value['default'],
  241. 'limit' => $value['limit'],
  242. 'comment' => $value['comment'],
  243. 'required' => '',
  244. 'is_table' => '',
  245. 'table_name' => '',
  246. 'from_type' => '',
  247. 'default_field' => $value['name'],
  248. 'default_limit' => $value['limit'],
  249. 'default_field_type' => $value['type'],
  250. 'default_comment' => $value['comment'],
  251. 'default_default' => $value['default'],
  252. ];
  253. }
  254. }
  255. if ($newColumn) {
  256. $info['field']['tableField'] = array_merge($info['field']['tableField'], $newColumn);
  257. }
  258. return app('json')->success(['file' => $data, 'crudInfo' => $info]);
  259. }
  260. /**
  261. * @param Request $request
  262. * @param SystemFileServices $service
  263. * @param $id
  264. * @return Response
  265. * @author 等风来
  266. * @email 136327134@qq.com
  267. * @date 2023/4/24
  268. */
  269. public function savefile(Request $request, SystemFileServices $service, $id)
  270. {
  271. $comment = $request->param('comment');
  272. $filepath = $request->param('filepath');
  273. if (empty($filepath) || !$id) {
  274. return app('json')->fail(410087);
  275. }
  276. $crudInfo = $this->services->get($id, ['make_path']);
  277. if (!$crudInfo) {
  278. return app('json')->fail('修改的CRUD文件不存在');
  279. }
  280. $makePath = [];
  281. foreach ($crudInfo->make_path as $key => $item) {
  282. if (in_array($key, ['pages', 'router', 'api'])) {
  283. $item = Make::adminTemplatePath() . $item;
  284. } else {
  285. $item = app()->getRootPath() . $item;
  286. }
  287. $makePath[$key] = $item;
  288. }
  289. if (!in_array($filepath, $makePath)) {
  290. return app('json')->fail('您没有权限修改此文件');
  291. }
  292. $res = $service->savefile($filepath, $comment);
  293. if ($res) {
  294. return app('json')->success(100000);
  295. } else {
  296. return app('json')->fail(100006);
  297. }
  298. }
  299. /**
  300. * 获取tree菜单
  301. * @return \think\Response
  302. * @author 等风来
  303. * @email 136327134@qq.com
  304. * @date 2023/4/11
  305. */
  306. public function getMenus()
  307. {
  308. return app('json')->success(app()->make(SystemMenusServices::class)
  309. ->getList(['auth_type' => 1, 'is_show' => 1], ['auth_type', 'pid', 'id', 'menu_name as label', 'id as value']));
  310. }
  311. /**
  312. * 获取创建表数据类型
  313. * @return \think\Response
  314. * @author 等风来
  315. * @email 136327134@qq.com
  316. * @date 2023/4/11
  317. */
  318. public function columnType()
  319. {
  320. return app('json')->success($this->services->getTabelRule());
  321. }
  322. /**
  323. * @param SystemMenusServices $services
  324. * @param $id
  325. * @return \think\Response
  326. * @author 等风来
  327. * @email 136327134@qq.com
  328. * @date 2023/4/11
  329. */
  330. public function delete(SystemMenusServices $services, $id)
  331. {
  332. if (!$id) {
  333. return app('json')->fail(500035);
  334. }
  335. $info = $this->services->get($id);
  336. if (!$info) {
  337. return app('json')->fail(500042);
  338. }
  339. $services->transaction(function () use ($services, $info) {
  340. if ($info->menu_ids) {
  341. $services->deleteMenus($info->menu_ids);
  342. }
  343. $info->delete();
  344. });
  345. if ($info->make_path) {
  346. try {
  347. foreach ($info->make_path as $key => $item) {
  348. if (in_array($key, ['pages', 'router', 'api'])) {
  349. $item = Make::adminTemplatePath() . $item;
  350. } else {
  351. $item = app()->getRootPath() . $item;
  352. }
  353. unlink($item);
  354. }
  355. } catch (\Throwable $e) {
  356. return app('json')->success(500041, [], ['message' => $e->getMessage()]);
  357. }
  358. }
  359. return app('json')->success(100002);
  360. }
  361. /**
  362. * 下载文件
  363. * @param $id
  364. * @return Response
  365. * @author 等风来
  366. * @email 136327134@qq.com
  367. * @date 2023/4/15
  368. */
  369. public function download($id)
  370. {
  371. if (!$id) {
  372. return app('json')->fail(500035);
  373. }
  374. $info = $this->services->get($id);
  375. if (!$info) {
  376. return app('json')->fail(500039);
  377. }
  378. $zipPath = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name);
  379. $zipName = app()->getRootPath() . 'backup' . DS . Str::camel($info->table_name) . '.zip';
  380. if (is_file($zipName)) {
  381. unlink($zipName);
  382. }
  383. $makePath = $info->make_path ?? [];
  384. foreach ($makePath as $key => $item) {
  385. if (in_array($key, ['pages', 'router', 'api'])) {
  386. $item = $zipPath . str_replace(dirname(app()->getRootPath()), '', Make::adminTemplatePath()) . $item;
  387. } else {
  388. $item = $zipPath . DS . $item;
  389. }
  390. $makePath[$key] = $item;
  391. }
  392. $routeName = 'crud/' . Str::snake($info->table_name);
  393. $column = $this->services->getColumnNamesList($info->table_name);
  394. $key = 'id';
  395. foreach ($column as $value) {
  396. if ($value['primaryKey']) {
  397. $key = $value['name'];
  398. break;
  399. }
  400. }
  401. $softDelete = false;
  402. foreach ((array)$info->field['tableField'] as $item) {
  403. if (isset($item['field_type']) && $item['field_type'] === 'addSoftDelete') {
  404. $softDelete = true;
  405. break;
  406. }
  407. }
  408. $this->services->makeFile($info->table_name, $routeName, true, [
  409. 'menuName' => $info->name,
  410. 'key' => $key,
  411. 'softDelete' => $softDelete,
  412. 'fromField' => $info->field['fromField'] ?? [],
  413. 'columnField' => $info->field['columnField'] ?? [],
  414. ], $makePath, $zipPath);
  415. if (!extension_loaded('zip')) {
  416. return app('json')->fail(500040);
  417. }
  418. $fileService = new FileService();
  419. $fileService->addZip($zipPath, $zipName, app()->getRootPath() . 'backup');
  420. $key = md5($zipName);
  421. CacheService::set($key, [
  422. 'path' => $zipName,
  423. 'fileName' => Str::camel($info->table_name) . '.zip',
  424. ], 300);
  425. return app('json')->success(['download_url' => sys_config('site_url') . '/adminapi/download/' . $key]);
  426. }
  427. /**
  428. * 获取权限路由
  429. * @param $tableName
  430. * @return Response
  431. * @author 等风来
  432. * @email 136327134@qq.com
  433. * @date 2023/4/20
  434. */
  435. public function getRouteList($tableName)
  436. {
  437. $info = $this->services->get(['table_name' => $tableName]);
  438. if (!$info) {
  439. return app('json')->fail('crud详情查询失败');
  440. }
  441. $routeList = app()->make(SystemMenusServices::class)->getColumn([
  442. ['id', 'in', $info->menu_ids],
  443. ['auth_type', '=', 2]
  444. ], 'methods,api_url');
  445. $newRoute = [];
  446. foreach ($routeList as $item) {
  447. if ($item['methods'] == 'GET') {
  448. if (strstr($item['api_url'], 'create')) {
  449. $newRoute['create'] = $item['api_url'];
  450. } else if (strstr($item['api_url'], 'edit')) {
  451. $newRoute['edit'] = $item['api_url'];
  452. } else {
  453. $newRoute['index'] = $item['api_url'];
  454. }
  455. } else if ($item['methods'] == 'DELETE') {
  456. $newRoute['delete'] = $item['api_url'];
  457. }
  458. }
  459. $column = $this->services->getColumnNamesList($info->table_name);
  460. $key = 'id';
  461. foreach ($column as $value) {
  462. if ($value['primaryKey']) {
  463. $key = $value['name'];
  464. break;
  465. }
  466. }
  467. $columns = [
  468. [
  469. 'title' => 'ID',
  470. 'key' => $key,
  471. 'from_type' => '',
  472. ]
  473. ];
  474. foreach ((array)$info->field['tableField'] as $item) {
  475. if (isset($item['is_table']) && $item['is_table']) {
  476. $columns[] = [
  477. 'title' => $item['table_name'] ?: $item['comment'],
  478. 'key' => $item['field'],
  479. 'from_type' => $item['from_type'],
  480. ];
  481. }
  482. }
  483. $route = $newRoute;
  484. return app('json')->success(compact('key', 'route', 'columns'));
  485. }
  486. /**
  487. * @return string
  488. * @author 等风来
  489. * @email 136327134@qq.com
  490. * @date 2023/4/14
  491. */
  492. public function npm()
  493. {
  494. $terminal = new Terminal();
  495. $adminPath = $terminal->adminTemplatePath();
  496. $adminPath = dirname($adminPath);
  497. try {
  498. $dir = $adminPath . DS . 'node_modules';
  499. if (!is_dir($dir)) {
  500. // $terminal->run('npm-install');
  501. }
  502. // $res = $terminal->run('npm-build');
  503. } catch (\Throwable $e) {
  504. $terminal->echoOutputFlag($e->getMessage());
  505. }
  506. if (!is_dir($adminPath . DS . 'dist')) {
  507. echo Response::create([
  508. 'message' => '打包失败',
  509. ], 'json')->getContent();
  510. }
  511. $build = public_path() . config('app.admin_prefix');
  512. // $this->app->make(FileService::class)->copyDir($adminPath . DS . 'dist', $build);
  513. // echo $res;
  514. }
  515. }