SystemCrud.php 18 KB

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