FormService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. // 转换字符串数组为实际数组
  353. $list->transform(function ($item) use ($globalTableFields) {
  354. foreach ($globalTableFields as $field) {
  355. $fieldName = $field->field_name;
  356. if (isset($item->$fieldName) && is_string($item->$fieldName)) {
  357. // 尝试解析JSON格式的字符串
  358. $decoded = json_decode($item->$fieldName, true);
  359. if (json_last_error() === JSON_ERROR_NONE) {
  360. $item->$fieldName = $decoded;
  361. }
  362. // 如果是简单的逗号分隔字符串,也可以转换为数组
  363. elseif (strpos($item->$fieldName, ',') !== false) {
  364. $item->$fieldName = array_map('trim', explode(',', $item->$fieldName));
  365. }
  366. }
  367. }
  368. return $item;
  369. });
  370. return Result::success([
  371. 'tableFields' => $globalTableFields,
  372. 'list' => $list,
  373. 'total' => $total,
  374. 'page' => $page,
  375. 'pageSize' => $pageSize
  376. ]);
  377. } catch (\Throwable $e) {
  378. return Result::error('查询失败:' . $e->getMessage());
  379. }
  380. }
  381. /**
  382. * 获取字段类型列表
  383. */
  384. public function getGlobalTableFieldTypeList(array $data): array
  385. {
  386. try {
  387. $list = Db::connection('global')->table("global_table_field_type")->get();
  388. return Result::success($list);
  389. }catch (\Throwable $e){
  390. return Result::error('查询失败:' . $e->getMessage());
  391. }
  392. }
  393. /**
  394. * 删除自定义表里面的某一条数据
  395. */
  396. public function delGlobalTableData(array $data): array
  397. {
  398. try {
  399. //查询global库的表GlobalTable模型中id为$data['id']的数据
  400. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  401. if(empty($globalTable)){
  402. return Result::error('表单不存在');
  403. }
  404. // 构建查询
  405. $query = Db::connection('global')->table($globalTable->table);
  406. $query->where('id',$data['id']);
  407. $query->delete();
  408. return Result::success('删除成功');
  409. }catch (\Throwable $e){
  410. return Result::error('删除失败:' . $e->getMessage());
  411. }
  412. }
  413. /**
  414. * 修改自定义表里面的某一条数据
  415. */
  416. public function updateGlobalTableData(array $data): array
  417. {
  418. try {
  419. $globalTable = GlobalTable::where('id', $data['table_id'])->first();
  420. if (empty($globalTable)) {
  421. return Result::error('表单不存在');
  422. }
  423. unset($data['table_id']);
  424. // 转换数组字段为字符串
  425. $data = array_map(function ($value) {
  426. if (is_array($value)) {
  427. return json_encode($value, JSON_UNESCAPED_UNICODE);
  428. }
  429. return $value;
  430. }, $data);
  431. $query = Db::connection('global')->table($globalTable->table);
  432. $query->where('id', $data['id'])->update($data);
  433. return Result::success('修改成功');
  434. } catch (\Throwable $e) {
  435. return Result::error('修改失败:' . $e->getMessage());
  436. }
  437. }
  438. /**
  439. * 查看自定义表里面的某条数据
  440. */
  441. public function getGlobalTableDataById(array $data): array
  442. {
  443. try {
  444. //查询
  445. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  446. if(empty($globalTable)){
  447. return Result::error('表单不存在');
  448. }
  449. $query = Db::connection('global')->table($globalTable->table);
  450. $query->where('id',$data['id']);
  451. $dataInfo = $query->first();
  452. $globalTableField = GlobalTableField::where(['table_id'=>$data['table_id']])->get();
  453. $globalTableField->transform(function ($field) {
  454. $optionValue = [];
  455. $optionStr = trim((string) $field->option);
  456. if (!empty($optionStr)) {
  457. $options = explode("\n", $optionStr);
  458. foreach ($options as $option) {
  459. $parts = explode('|', $option);
  460. if (count($parts) === 2) {
  461. $optionValue[$parts[1]] = $parts[0];
  462. }
  463. }
  464. }
  465. $field->option_value = $optionValue;
  466. return $field;
  467. });
  468. $return = [
  469. 'data'=>$dataInfo,
  470. 'tableFields'=>$globalTableField->toArray(),
  471. ];
  472. return Result::success($return);
  473. }catch (\Throwable $e){
  474. return Result::error('查询失败:' . $e->getMessage());
  475. }
  476. }
  477. /**
  478. * 查询网站下表单自定义字段
  479. */
  480. public function getWebGlobalTableFieldList(array $data): array
  481. {
  482. try {
  483. $globalTable = GlobalTable::where('id',$data['table_id'])->first();
  484. $fields = GlobalTableField::from('global_table_field as a')
  485. ->join('global_table_field_type as b', 'a.field_type', '=', 'b.id')
  486. ->where('a.table_id', $data['table_id'])
  487. ->where('a.field_name',"<>",'id')
  488. ->where('a.home_display', 1)
  489. ->orderBy('a.sort', 'asc')
  490. ->select(
  491. // global_table_field 所有字段
  492. 'a.*',
  493. // global_table_field_type 字段
  494. 'b.type_name',
  495. 'b.type_name_alias',
  496. 'b.field_type as type_definition'
  497. )
  498. ->get();
  499. $config = new \EasySwoole\VerifyCode\Config();
  500. $code = new \EasySwoole\VerifyCode\VerifyCode($config);
  501. $img_code = '';
  502. $characters = '0123456789';
  503. $charLength = strlen($characters);
  504. for ($i = 0; $i < 4; $i++) {
  505. $img_code .= $characters[rand(0, $charLength - 1)];
  506. }
  507. //重写验证码
  508. $result = $code->DrawCode((string)$img_code);
  509. $img_code = $result->getImageCode();
  510. var_dump("验证码:",$img_code);
  511. $code_uniqid = uniqid("code");
  512. //写入缓存 用于其他方法验证 并且设置过期时间
  513. $this->redis->set($code_uniqid,$img_code,60000);
  514. $rep = [
  515. 'fields' => $fields,
  516. 'table'=>$globalTable,
  517. ];
  518. if($globalTable->is_code){
  519. $rep['code']['code_uniqid'] = $code_uniqid;
  520. $rep['code']['img'] = $result->getImageBase64();
  521. }
  522. return Result::success($rep);
  523. }catch (\Throwable $e){
  524. return Result::error('查询失败:' . $e->getMessage());
  525. }
  526. }
  527. /**
  528. * web端创建数据
  529. * @param array $data
  530. * @return array
  531. */
  532. public function addWebGlobalTableData(array $data): array
  533. {
  534. try {
  535. $globalTable = GlobalTable::where('id',$data['otherData']['table_id'])->first();
  536. if($globalTable->is_code){
  537. if(empty($data['otherData']['code'])){
  538. return Result::error('请输入验证码');
  539. }
  540. $code = $this->redis->get($data['otherData']['code_uniqid']);
  541. if(empty($code)){
  542. return Result::error('验证码已过期');
  543. }
  544. if($data['otherData']['code'] != $code){
  545. return Result::error('验证码错误');
  546. }
  547. }
  548. if(empty($globalTable)){
  549. return Result::error('表单不存在');
  550. }
  551. $query = Db::connection('global')->table($globalTable->table);
  552. $query->insert($data['data']);
  553. return Result::success([]);
  554. }catch (\Throwable $e){
  555. return Result::error('添加失败:' . $e->getMessage());
  556. }
  557. }
  558. }