FormService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php
  2. namespace App\JsonRpc;
  3. use Hyperf\RpcServer\Annotation\RpcService;
  4. use App\Tools\Result;
  5. use App\Model\GlobalTable;
  6. use Hyperf\DbConnection\Db;
  7. use App\Model\GlobalTableField;
  8. use App\Model\GlobalTableFieldType;
  9. use App\Model\GlobalTableFieldValue;
  10. use Hyperf\Di\Annotation\Inject;
  11. use Hyperf\Redis\Redis;
  12. #[RpcService(name: "FormService", protocol: "jsonrpc-http", server: "jsonrpc-http")]
  13. class FormService implements FormServiceInterface
  14. {
  15. #[Inject]
  16. protected Redis $redis;
  17. /**
  18. * 添加全局表单
  19. * @param array $data
  20. * @return array|mixed
  21. */
  22. public function addGlobalTable(array $data): array
  23. {
  24. // 过滤掉空值
  25. $data = array_filter($data, function($value) {
  26. return !empty($value);
  27. });
  28. // 检查是否已存在相同名称的记录
  29. $globalTable = GlobalTable::on('global')->where(['table'=> $data['table'],'website_id'=>$data['website_id']])->first();
  30. if (empty($globalTable)) {
  31. $id = GlobalTable::on('global')->insertGetId($data);
  32. //给global库创建表 表名为$data['table'] 的值,并初始化一个字段id,类型为int,自增,主键,再初始化一个字段title,类型为varchar,长度为255
  33. Db::connection('global')->statement("CREATE TABLE IF NOT EXISTS `{$data['table']}` (
  34. `id` int(11) NOT NULL AUTO_INCREMENT,
  35. `title` varchar(255) DEFAULT NULL,
  36. `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
  37. `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  38. PRIMARY KEY (`id`)
  39. )");
  40. //给GlobalTableField表初始化数据
  41. GlobalTableField::on('global')->insert([
  42. [
  43. 'table_id' => $id,
  44. 'field_name' => 'id',
  45. 'title' => '编号',
  46. 'field_type' => '1',
  47. 'length' => 255,
  48. 'sort' => 0,
  49. 'is_check' => 1,
  50. 'admin_display' => 1,
  51. 'home_display' => 1,
  52. 'disable_del' => 1,
  53. ],
  54. [
  55. 'table_id' => $id,
  56. 'field_name' => 'title',
  57. 'title' => '标题',
  58. 'field_type' => '1',
  59. 'length' => 255,
  60. 'sort' => 0,
  61. 'is_check' => 1,
  62. 'admin_display' => 1,
  63. 'home_display' => 1,
  64. 'disable_del' => 1,
  65. ],
  66. [
  67. 'table_id' => $id,
  68. 'field_name' => 'updated_at',
  69. 'title' => '更新时间',
  70. 'field_type' => '1',
  71. 'length' => 255,
  72. 'sort' => 999,
  73. 'is_check' => 1,
  74. 'admin_display' => 1,
  75. 'home_display' => 0,
  76. 'disable_del' => 1,
  77. ],
  78. [
  79. 'table_id' => $id,
  80. 'field_name' => 'created_at',
  81. 'title' => '创建时间',
  82. 'field_type' => '1',
  83. 'length' => 255,
  84. 'sort' => 1000,
  85. 'is_check' => 1,
  86. 'admin_display' => 1,
  87. 'home_display' => 0,
  88. 'disable_del' => 1,
  89. ],
  90. ]);
  91. return Result::success('添加成功');
  92. }
  93. return Result::error('表单已存在');
  94. }
  95. /**
  96. * 获取全局表单列表
  97. * @param array $data
  98. * @return array
  99. */
  100. public function getGlobalTableList(array $data): array
  101. {
  102. try {
  103. // 构建查询
  104. $query = GlobalTable::query()
  105. ->when(!empty($data['website_id']), function($q) use ($data) {
  106. return $q->where('website_id', $data['website_id']);
  107. })
  108. ->when(!empty($data['name']), function($q) use ($data) {
  109. return $q->where('name', 'like', '%' . $data['name'] . '%');
  110. });
  111. // 分页参数
  112. $page = (int)($data['page'] ?? 1);
  113. $pageSize = (int)($data['pageSize'] ?? 10);
  114. // 先获取总数
  115. $total = $query->count();
  116. // 获取数据
  117. $list = $query->orderBy('updated_at', 'desc')
  118. ->offset(($page - 1) * $pageSize)
  119. ->limit($pageSize)
  120. ->get();
  121. // 如果没有数据,直接返回空结果
  122. if ($list->isEmpty()) {
  123. return Result::success([
  124. 'list' => [],
  125. 'total' => $total,
  126. 'page' => $page,
  127. 'pageSize' => $pageSize
  128. ]);
  129. }
  130. // 获取并合并 website 数据
  131. $websites = Db::connection('secondary')
  132. ->table('website')
  133. ->whereIn('id', $list->pluck('website_id'))
  134. ->pluck('website_name', 'id');
  135. // 合并数据并返回
  136. return Result::success([
  137. 'list' => $list->map(function($item) use ($websites) {
  138. $item->website_name = $websites[$item->website_id] ?? '';
  139. return $item;
  140. }),
  141. 'total' => $total,
  142. 'page' => $page,
  143. 'pageSize' => $pageSize
  144. ]);
  145. } catch (\Throwable $e) {
  146. return Result::error('查询失败:' . $e->getMessage());
  147. }
  148. }
  149. /**
  150. * 获取全局表单
  151. * @param array $data
  152. * @return array
  153. */
  154. public function getGlobalTable(array $data): array
  155. {
  156. $globalTable = GlobalTable::where('id',$data['id'])->first();
  157. return Result::success($globalTable);
  158. }
  159. /**
  160. * 修改全局表单
  161. * @param array $data
  162. * @return array
  163. */
  164. public function upGlobalTable(array $data): array
  165. {
  166. $globalTable = GlobalTable::where('id',$data['id'])->first();
  167. if(empty($globalTable)){
  168. return Result::error('表单不存在');
  169. }
  170. $data = array_filter($data,function($value){
  171. return !empty($value);
  172. });
  173. GlobalTable::where(['id'=>$data['id']])->update($data);
  174. return Result::success('修改成功');
  175. }
  176. /**
  177. * 删除全局表单
  178. * @param array $data
  179. * @return array
  180. */
  181. public function delGlobalTable(array $data): array
  182. {
  183. $globalTable = GlobalTable::where('id', $data['id'])->first();
  184. if(empty($globalTable)){
  185. return Result::error('表单不存在');
  186. }
  187. //删除global库的表
  188. Db::connection('global')->statement("DROP TABLE IF EXISTS `{$globalTable->table}`");
  189. //删除GlobalTableField表中table_id为$data['id']的数据
  190. GlobalTableField::where('table_id', $data['id'])->delete();
  191. GlobalTable::where('id', $data['id'])->delete();
  192. return Result::success('删除成功');
  193. }
  194. /**
  195. * 获取表单字段列表
  196. * @param array $data
  197. * @return array
  198. */
  199. public function getGlobalTableFieldList(array $data): array
  200. {
  201. $fields = GlobalTableField::from('global_table_field as a')
  202. ->join('global_table_field_type as b', 'a.field_type', '=', 'b.id')
  203. ->where('a.table_id', $data['id'])
  204. ->whereNotIn('a.field_name',['id','created_at','updated_at'])
  205. ->orderBy('a.sort', 'asc')
  206. ->select(
  207. // global_table_field 所有字段
  208. 'a.*',
  209. // global_table_field_type 字段
  210. 'b.type_name',
  211. 'b.type_name_alias',
  212. 'b.field_type as type_definition'
  213. )
  214. ->get();
  215. return Result::success($fields);
  216. }
  217. /**
  218. * 获取表单字段
  219. * @param array $data
  220. * @return array
  221. */
  222. public function getGlobalTableField(array $data): array
  223. {
  224. $globalTableField = GlobalTableField::where('id',$data['id'])->first();
  225. return Result::success($globalTableField);
  226. }
  227. /**
  228. * 添加表单字段
  229. * @param array $data
  230. * @return array
  231. * @throws \Throwable
  232. */
  233. public function addGlobalTableField(array $data): array
  234. {
  235. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  236. if(empty($globalTable)){
  237. return Result::error('表单不存在');
  238. }
  239. //检查是否已存在相同名称的记录
  240. $globalTableField = GlobalTableField::where(['table_id'=>$data['table_id'],'field_name'=>$data['field_name']])->first();
  241. if(!empty($globalTableField)){
  242. return Result::error('字段已存在');
  243. }
  244. // 检查表中是否已存在该列
  245. try {
  246. $columns = Db::connection('global')->select("SHOW COLUMNS FROM `{$globalTable->table}`");
  247. $columnNames = array_column($columns, 'Field');
  248. if (in_array($data['field_name'], $columnNames)) {
  249. return Result::error('字段名已存在于数据表中');
  250. }
  251. } catch (\Throwable $e) {
  252. return Result::error('检查字段是否存在时出错:' . $e->getMessage());
  253. }
  254. $globalTableFieldTypeInfo = GlobalTableFieldType::where('id',$data['field_type'])->first();
  255. //给global库的表添加字段
  256. Db::connection('global')->statement("ALTER TABLE `{$globalTable->table}` ADD COLUMN `{$data['field_name']}` {$globalTableFieldTypeInfo['field_type']}({$data['length']}) COMMENT '{$data['title']}'");
  257. //给GlobalTableField表添加数据
  258. GlobalTableField::create($data);
  259. return Result::success('添加成功');
  260. }
  261. /**
  262. * 修改表单字段
  263. * @param array $data
  264. * @return array
  265. * @throws \Throwable
  266. */
  267. public function upGlobalTableField(array $data): array
  268. {
  269. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  270. if(empty($globalTable)){
  271. return Result::error('表单不存在');
  272. }
  273. //检查是否已存在相同名称的记录
  274. $globalTableField = GlobalTableField::where(['table_id'=>$data['table_id'],'field_name'=>$data['field_name']])->first();
  275. if(!empty($globalTableField) && $globalTableField->id != $data['id']){
  276. return Result::error('字段已存在');
  277. }
  278. $globalTableFieldTypeInfo = GlobalTableFieldType::where('id',$data['field_type'])->first();
  279. //给global库的表修改字段
  280. Db::connection('global')->statement("ALTER TABLE `{$globalTable->table}` CHANGE COLUMN `{$data['field_name']}` `{$data['field_name']}` {$globalTableFieldTypeInfo['field_type']}({$data['length']}) COMMENT '{$data['title']}'");
  281. //给GlobalTableField表修改数据
  282. GlobalTableField::where('id',$data['id'])->update($data);
  283. return Result::success('修改成功');
  284. }
  285. /**
  286. * 删除表单字段
  287. * @param array $data
  288. * @return array
  289. * @throws \Throwable
  290. */
  291. public function delGlobalTableField(array $data): array
  292. {
  293. $tableFieldInfo = GlobalTableField::where('id',$data['id'])->first();
  294. if(empty($tableFieldInfo)){
  295. return Result::error('字段不存在');
  296. }
  297. $globalTable = GlobalTable::where('id',$tableFieldInfo['table_id'])->first();
  298. if(empty($globalTable)){
  299. return Result::error('表单不存在');
  300. }
  301. //给global库的表删除字段
  302. Db::connection('global')->statement("ALTER TABLE `{$globalTable->table}` DROP COLUMN `{$tableFieldInfo['field_name']}`");
  303. //给GlobalTableField表删除数据
  304. GlobalTableField::where('id',$data['id'])->delete();
  305. return Result::success('删除成功');
  306. }
  307. /**
  308. * 获取自定义生成表里面的数据
  309. */
  310. public function getGlobalTableData(array $data): array
  311. {
  312. try {
  313. //查询global库的表GlobalTableField模型中table_id为$data['id']的数据条件为admin_display=1的数据
  314. $globalTableFields = GlobalTableField::where(['table_id'=>$data['id'],'admin_display'=>1])->get();
  315. $globalTableFields->transform(function ($field) {
  316. $optionValue = [];
  317. $optionStr = trim((string) $field->option);
  318. if (!empty($optionStr)) {
  319. $options = explode("\n", $optionStr);
  320. foreach ($options as $option) {
  321. $parts = explode('|', $option);
  322. if (count($parts) === 2) {
  323. $optionValue[$parts[1]] = $parts[0];
  324. }
  325. }
  326. }
  327. $field->option_value = $optionValue;
  328. return $field;
  329. });
  330. //查询global库的表GlobalTable模型中id为$data['id']的数据
  331. $globalTable = GlobalTable::where('id',$data['id'])->first();
  332. if(empty($globalTable)){
  333. return Result::error('表单不存在');
  334. }
  335. // 构建查询
  336. $query = Db::connection('global')->table($globalTable->table);
  337. // 添加title模糊搜索
  338. if (!empty($data['title'])) {
  339. $query->where('title', 'like', '%' . $data['title'] . '%');
  340. }
  341. // 分页参数
  342. $page = (int)($data['page'] ?? 1);
  343. $pageSize = (int)($data['pageSize'] ?? 10);
  344. // 先获取总数
  345. $total = $query->count();
  346. // 获取分页数据
  347. $list = $query->select($globalTableFields->pluck('field_name')->toArray())
  348. ->orderBy('id', 'desc')
  349. ->offset(($page - 1) * $pageSize)
  350. ->limit($pageSize)
  351. ->get();
  352. // 处理返回数据,将field_name替换为title
  353. // $list = $list->map(function($item) use ($globalTableFields) {
  354. // $newItem = new \stdClass();
  355. // foreach ($globalTableFields as $field) {
  356. // $fieldName = $field->field_name;
  357. // if (isset($item->$fieldName)) {
  358. // $newItem->{$field->title} = $item->$fieldName;
  359. // }
  360. // }
  361. // return $newItem;
  362. // });
  363. return Result::success([
  364. 'tableFields' => $globalTableFields,
  365. 'list' => $list,
  366. 'total' => $total,
  367. 'page' => $page,
  368. 'pageSize' => $pageSize
  369. ]);
  370. } catch (\Throwable $e) {
  371. return Result::error('查询失败:' . $e->getMessage());
  372. }
  373. }
  374. /**
  375. * 获取字段类型列表
  376. */
  377. public function getGlobalTableFieldTypeList(array $data): array
  378. {
  379. try {
  380. $list = Db::connection('global')->table("global_table_field_type")->get();
  381. return Result::success($list);
  382. }catch (\Throwable $e){
  383. return Result::error('查询失败:' . $e->getMessage());
  384. }
  385. }
  386. /**
  387. * 删除自定义表里面的某一条数据
  388. */
  389. public function delGlobalTableData(array $data): array
  390. {
  391. try {
  392. //查询global库的表GlobalTable模型中id为$data['id']的数据
  393. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  394. if(empty($globalTable)){
  395. return Result::error('表单不存在');
  396. }
  397. // 构建查询
  398. $query = Db::connection('global')->table($globalTable->table);
  399. $query->where('id',$data['id']);
  400. $query->delete();
  401. return Result::success('删除成功');
  402. }catch (\Throwable $e){
  403. return Result::error('删除失败:' . $e->getMessage());
  404. }
  405. }
  406. /**
  407. * 修改自定义表里面的某一条数据
  408. */
  409. public function updateGlobalTableData(array $data): array
  410. {
  411. try {
  412. //查询global库的表GlobalTable模型中id为$data['id']的数据
  413. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  414. if(empty($globalTable)){
  415. return Result::error('表单不存在');
  416. }
  417. unset($data['table_id']);
  418. // 构建查询
  419. $query = Db::connection('global')->table($globalTable->table);
  420. $query->where('id',$data['id']);
  421. $query->update($data);
  422. return Result::success('修改成功');
  423. }catch (\Throwable $e){
  424. return Result::error('修改失败:' . $e->getMessage());
  425. }
  426. }
  427. /**
  428. * 查看自定义表里面的某条数据
  429. */
  430. public function getGlobalTableDataById(array $data): array
  431. {
  432. try {
  433. //查询
  434. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  435. if(empty($globalTable)){
  436. return Result::error('表单不存在');
  437. }
  438. $query = Db::connection('global')->table($globalTable->table);
  439. $query->where('id',$data['id']);
  440. $dataInfo = $query->first();
  441. $globalTableField = GlobalTableField::where(['table_id'=>$data['table_id']])->get();
  442. $globalTableField->transform(function ($field) {
  443. $optionValue = [];
  444. $optionStr = trim((string) $field->option);
  445. if (!empty($optionStr)) {
  446. $options = explode("\n", $optionStr);
  447. foreach ($options as $option) {
  448. $parts = explode('|', $option);
  449. if (count($parts) === 2) {
  450. $optionValue[$parts[1]] = $parts[0];
  451. }
  452. }
  453. }
  454. $field->option_value = $optionValue;
  455. return $field;
  456. });
  457. $return = [
  458. 'data'=>$dataInfo,
  459. 'tableFields'=>$globalTableField->toArray(),
  460. ];
  461. return Result::success($return);
  462. }catch (\Throwable $e){
  463. return Result::error('查询失败:' . $e->getMessage());
  464. }
  465. }
  466. /**
  467. * 查询网站下表单自定义字段
  468. */
  469. public function getWebGlobalTableFieldList(array $data): array
  470. {
  471. try {
  472. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  473. $fields = GlobalTableField::from('global_table_field as a')
  474. ->join('global_table_field_type as b', 'a.field_type', '=', 'b.id')
  475. ->where('a.table_id', $data['table_id'])
  476. ->where('a.field_name',"<>",'id')
  477. ->where('a.home_display', 1)
  478. ->orderBy('a.sort', 'asc')
  479. ->select(
  480. // global_table_field 所有字段
  481. 'a.*',
  482. // global_table_field_type 字段
  483. 'b.type_name',
  484. 'b.type_name_alias',
  485. 'b.field_type as type_definition'
  486. )
  487. ->get();
  488. $config = new \EasySwoole\VerifyCode\Config();
  489. $code = new \EasySwoole\VerifyCode\VerifyCode($config);
  490. $img_code = '';
  491. $characters = '0123456789';
  492. $charLength = strlen($characters);
  493. for ($i = 0; $i < 4; $i++) {
  494. $img_code .= $characters[rand(0, $charLength - 1)];
  495. }
  496. //重写验证码
  497. $result = $code->DrawCode((string)$img_code);
  498. $img_code = $result->getImageCode();
  499. var_dump("验证码:",$img_code);
  500. $code_uniqid = uniqid("code");
  501. //写入缓存 用于其他方法验证 并且设置过期时间
  502. $this->redis->set($code_uniqid,$img_code,60000);
  503. $rep = [
  504. 'fields' => $fields,
  505. 'table'=>$globalTable,
  506. ];
  507. if($globalTable->is_code){
  508. $rep['code']['code_uniqid'] = $code_uniqid;
  509. $rep['code']['img'] = $result->getImageBase64();
  510. }
  511. return Result::success($rep);
  512. }catch (\Throwable $e){
  513. return Result::error('查询失败:' . $e->getMessage());
  514. }
  515. }
  516. /**
  517. * web端创建数据
  518. * @param array $data
  519. * @return array
  520. */
  521. public function addWebGlobalTableData(array $data): array
  522. {
  523. try {
  524. $globalTable = GlobalTable::where('id',$data['otherData']['table_id'])->first();
  525. if($globalTable->is_code){
  526. if(empty($data['otherData']['code'])){
  527. return Result::error('请输入验证码');
  528. }
  529. $code = $this->redis->get($data['otherData']['code_uniqid']);
  530. if(empty($code)){
  531. return Result::error('验证码已过期');
  532. }
  533. if($data['otherData']['code'] != $code){
  534. return Result::error('验证码错误');
  535. }
  536. }
  537. if(empty($globalTable)){
  538. return Result::error('表单不存在');
  539. }
  540. $query = Db::connection('global')->table($globalTable->table);
  541. $query->insert($data['data']);
  542. return Result::success([]);
  543. }catch (\Throwable $e){
  544. return Result::error('添加失败:' . $e->getMessage());
  545. }
  546. }
  547. }