代码下载接口

This commit is contained in:
2025-05-13 13:16:59 +08:00
parent 636fc411d2
commit a764794a5f
8 changed files with 206 additions and 183 deletions

View File

@@ -86,4 +86,18 @@ class AdminController extends BaseController
'获取成功'
);
}
/**
* 获取菜单列表
* @Method GET
* @return JsonResponse
* @throws Exception
*/
public function codes(): JsonResponse
{
return jok(
[],
'获取成功'
);
}
}

View File

@@ -19,23 +19,31 @@ class CodeGenerationController extends BaseController
public function generation()
{
// $this->insertField = [
// 'class_name',
// 'class_comment',
// 'sort',
// 'icon',
// 'pid',
// 'field',
// ];
//
// $params = $this->checkRequiredFields(request()->post());
$this->insertField = [
'class_name',
'class_comment',
'sort',
'icon',
'pid',
'field',
];
$params = json_decode('{"class_name":"testTemplate","class_comment":"测试代码生成","sort":"9999999","icon":"ant-design:api-outlined","pid":14,"field":[{"name":"name","type":"VARCHAR","type_number":"32","default":null,"comment":"测试名称","null":true,"formShow":true,"tableShow":true,"search":true,"searchValue":"like","formType":"VbenInput"},{"name":"test_name_1","type":"VARCHAR","type_number":"32","default":null,"comment":"测试名称","null":true,"formShow":true,"tableShow":true,"search":true,"searchValue":"like","formType":"VbenInput"}]}', true);
// ds($params);
return $this->service->generate($params);
// return jok(
// $this->service->generate([])
// );
$params = $this->checkRequiredFields(request()->post());
return jok(
$this->service->generate($params),
'生成成功!'
);
}
public function download()
{
// $id = request()->post('id');
$id = request()->get('id');
if (!$id) {
return jerr('参数错误!');
}
return $this->service->download($id);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Models;
use App\BaseApp\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasOne;
class CodeGenerationModel extends BaseModel
{
protected $table = 'code_generation';
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $guarded = [];
}

View File

@@ -2,7 +2,9 @@
namespace App\Service\core;
use App\Models\CodeGenerationModel;
use App\Service\common\UtilsService;
use App\Service\MenuService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
@@ -75,10 +77,20 @@ class CodeGenerationService
return self::$_instance[$name];
}
public function download($id)
{
$model = CodeGenerationModel::find($id);
if (!$model) {
$this->utils->errorThrow('文件不存在');
}
// 返回下载 $path 文件流
return response()->download($model['path'], $model['file_name'], ['Content-Type' => 'application/zip']);
}
/**
* 创建临时文件夹,复制模板文件,压缩并返回文件流
*/
public function download(): BinaryFileResponse|JsonResponse
public function downloadUrl()
{
try {
// 将后端模板文件内容写入临时目录中
@@ -98,8 +110,15 @@ class CodeGenerationService
// 执行文件压缩
$zip->zip($zipFile, $path);
// 返回下载 $path 文件流
return response()->download($zipFile, "{$this->classComment}-{$this->uniqid}.zip", ['Content-Type' => 'application/zip']);
CodeGenerationModel::create([
'title' => $this->classComment,
'file_name' => "{$this->classComment}-{$this->uniqid}.zip",
'path' => $zipFile,
'params' => json_encode($this->param),
'created_at' => time(),
'updated_at' => time(),
]);
return $zipFile;
} catch (\Exception $e) {
return response()->json([
'error' => '生成模板文件失败',
@@ -134,9 +153,10 @@ class CodeGenerationService
* 代码生成主逻辑
*
* @param $params
* @return mixed
* @throws Exception
*/
public function generate($params)
public function generate($params): mixed
{
$this->param = $params;
DB::beginTransaction();
@@ -157,24 +177,19 @@ class CodeGenerationService
$this->querySql();
// 生成视图
$this->genViews();
// // 生成菜单
// $this->genMenu();
return $this->download();
// // 生成导出层
// $this->genExport();
// // 生成导入层
// $this->genImport();
// 生成菜单
$this->genMenu();
} catch (Exception $e) {
DB::rollBack();
ds([
'error' => '生成代码失败',
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile(),
]);
// ds([
// 'error' => '生成代码失败',
// 'message' => $e->getMessage(),
// 'line' => $e->getLine(),
// 'file' => $e->getFile(),
// ]);
$this->utils->errorThrow($e->getMessage());
}
return $this->download();
return $this->downloadUrl();
}
@@ -240,7 +255,7 @@ class CodeGenerationService
$apiPath = app_path('../routes/api.php');
$apiFile = file_get_contents($apiPath, 'y');
$newApi =
"'{$this->dashCase}' => \App\Http\Controllers\Api\CodeGeneration\\{$this->upperCamelCase}Controller::class, // {$this->classComment}} \r\n // 需要登录的路由生成地址";
"'{$this->dashCase}' => \App\Http\Controllers\Api\CodeGeneration\\{$this->upperCamelCase}Controller::class, // {$this->classComment} \r\n // 需要登录的路由生成地址";
$updateNewFile = str_replace('// 需要登录的路由生成地址', $newApi, $apiFile);
@@ -289,35 +304,7 @@ class CodeGenerationService
'model'
);
}
//
// /**
// * 生成导出层文件
// * @return void
// */
// private function genExport(): void
// {
// $this->strReplaceTmp(
// $this->basePath . $this->tmpPath['server']['export'],
// $this->basePath . $this->newPath['server']['export'],
// 'server',
// 'export'
// );
// }
//
// /**
// * 生成导入层文件
// * @return void
// */
// private function genImport(): void
// {
// $this->strReplaceTmp(
// $this->basePath . $this->tmpPath['server']['import'],
// $this->basePath . $this->newPath['server']['import'],
// 'server',
// 'import'
// );
// }
//
/**
* 生成前端部分文件
* @return void
@@ -343,16 +330,24 @@ class CodeGenerationService
}
}
// /**
// * 生成菜单/授权
// *
// * @return void
// * @throws Exception
// */
// private function genMenu(): void
// {
// RoleService::getInstance()->createRoleMenuRelation(UsersEnum::ADMIN_ID, MenuService::getInstance()->save($this->menu));
// }
/**
* 生成菜单/授权
*
* @return void
* @throws Exception
*/
private function genMenu(): void
{
MenuService::getInstance()->create([
'title' => $this->classComment,
'icon' => $this->param['icon']?? '',
'name' => $this->upperCamelCase,
'path' => "/{$this->dashCase}",
'component' => "/my-gen/{$this->dashCase}/index",
'pid' => $this->param['pid'],
'sort' => $this->param['sort'],
]);
}
/**
* 模板内容替换
@@ -425,15 +420,15 @@ class CodeGenerationService
}
// 设置表单字段
if ($item['formShow']) {
$isNull = $item['null'] == 1 ? 'required' : '';
$isNull = $item['null'] == 1 ? "'required'" : "''";
$this->insertField .= !empty($this->insertField) ? '","' . $item['name'] : $item['name'];
$this->updateField .= !empty($this->updateField) ? '","' . $item['name'] : 'id","' . $item['name'];
$this->viewForm .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n rules: " . $isNull . ",\n },\n ";
$this->viewForm .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n rules: " . $isNull . ",\n },\n";
}
// 设置搜索字段
if ($item['search']) {
$this->viewSearch .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n },\n ";
$this->searchField .= !empty($this->searchField) ? ',' . $item['name'] . '\' => \'' . $item['searchValue'] : $item['name'] . '\' => \'' . $item['searchValue'];
$this->viewSearch .= "{\n fieldName: '" . $item['name'] . "',\n label: '" . $item['comment'] . "',\n component: '" . $item['formType'] . "',\n },\n ";
$this->searchField .= !empty($this->searchField) ? "','" . $item['name'] . '\' => \'' . $item['searchValue'] : $item['name'] . '\' => \'' . $item['searchValue'];
}
// // 设置导出字段
// $this->exportField .= !empty($this->exportField) ? ',"' . $item['comment'] . '"' : '"' . $item['comment'] . '"';
@@ -441,7 +436,7 @@ class CodeGenerationService
// // 设置导入字段
// $this->importField .= "'" . $item['name'] . "' => \$row['" . $item['comment'] . "'],\n ";
// 设置视图数据字段
$this->viewData .= "{ field: '{$item['name']}', title: '{$item['comment']}' },\n ";
$this->viewData .= "{ field: '{$item['name']}', title: '{$item['comment']}' },\n ";
}
/**

View File

@@ -2,10 +2,10 @@ import { requestClient } from '#/api/request';
const prefix = 'dashCase/';
/**
* 分页查询用户列表
* 分页查询模板名称列表
* @param data
*/
export async function getupperCamelCaseList(data: any) {
export async function getupperCamelCaseListApi(data: any) {
return requestClient.get<any>(`${prefix}list`, { params: data });
}
@@ -13,7 +13,7 @@ export async function getupperCamelCaseList(data: any) {
* 获取模板名称详情
* @param id
*/
export async function getupperCamelCaseInfo(id: number) {
export async function getupperCamelCaseInfoApi(id: number) {
return requestClient.get<any>(`${prefix}detail`, { params: { id } });
}
@@ -21,7 +21,7 @@ export async function getupperCamelCaseInfo(id: number) {
* 新增模板名称
* @param data
*/
export async function createupperCamelCase(data: Record<string, any>) {
export async function createupperCamelCaseApi(data: Record<string, any>) {
return requestClient.post<any>(`${prefix}create`, data);
}
@@ -29,7 +29,7 @@ export async function createupperCamelCase(data: Record<string, any>) {
* 编辑模板名称
* @param data
*/
export async function updateupperCamelCase(data: Record<string, any>) {
export async function updateupperCamelCaseApi(data: Record<string, any>) {
return requestClient.post<any>(`${prefix}update`, data);
}
@@ -37,6 +37,6 @@ export async function updateupperCamelCase(data: Record<string, any>) {
* 删除模板名称
* @param data
*/
export async function deleteupperCamelCase(data: Record<string, any>) {
export async function deleteupperCamelCaseApi(data: Record<string, any>) {
return requestClient.post<any>(`${prefix}delete`, data);
}

View File

@@ -6,7 +6,7 @@ import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { createupperCamelCase, updateupperCamelCase } from '../api';
import {createupperCamelCaseApi, updateupperCamelCaseApi} from '../api';
import { modalFormProps } from '../config/form';
defineOptions({
@@ -29,7 +29,7 @@ const [Modal, modalApi] = useVbenModal({
if (e.valid) {
const values = await formApi.getValues();
modalApi.setState({ loading: true, confirmLoading: true });
const submitApi = isUpdate.value ? updateupperCamelCase : createupperCamelCase;
const submitApi = isUpdate.value ? updateupperCamelCaseApi : createupperCamelCaseApi;
submitApi(values)
.then(() => {
message.success('保存成功');

View File

@@ -1,6 +1,6 @@
import type { VxeGridProps } from '#/adapter/vxe-table';
import { getupperCamelCaseList } from '../api';
import { getupperCamelCaseListApi } from '../api';
interface RowType {
id: string;
@@ -35,7 +35,7 @@ export const gridOptions: VxeGridProps<RowType> = {
ajax: {
// 请求后端接口方法
query: async ({ page }, formValues) => {
return await getupperCamelCaseList({
return await getupperCamelCaseListApi({
page: page.currentPage,
pageSize: page.pageSize,
...formValues,

View File

@@ -1,93 +1,74 @@
<script lang="ts" setup>
// 导入 VxeGridListeners 类型用于定义表格事件监听器
import type { VxeGridListeners } from '#/adapter/vxe-table';
// 导入 Vue 的 ref 函数用于创建响应式数据
import { ref } from 'vue';
// 导入 Vben 的公共 UI 组件和 Hook
import { Page, useVbenModal } from '@vben/common-ui';
// 导入 Ant Design Vue 的组件和消息提示函数
import { Button, message } from 'ant-design-vue';
import { Button, Image, message } from 'ant-design-vue';
// 导入自定义的 VxeGrid Hook 和 TableAction 组件
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';
// 导入删除 API 函数和模态框组件
import { deleteupperCamelCase } from './api';
import upperCamelCase from './components/modal.vue';
// 导入搜索表单和表格配置
import { deleteupperCamelCaseApi } from './api';
import FormModalDemo from './components/modal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';
// 定义是否显示顶部表格下拉操作的响应式数据
const hasTopTableDropDownActions = ref(false);
// 定义表格事件监听器
const gridEvents: VxeGridListeners<any> = {
// 监听表格复选框变化事件
checkboxChange() {
const records = gridApi.grid.getCheckboxRecords();
hasTopTableDropDownActions.value = records.length > 0;
},
// 监听表格全选复选框变化事件
checkboxAll() {
const records = gridApi.grid.getCheckboxRecords();
hasTopTableDropDownActions.value = records.length > 0;
},
checkboxChange() {
const records = gridApi.grid.getCheckboxRecords();
hasTopTableDropDownActions.value = records.length > 0;
},
checkboxAll() {
const records = gridApi.grid.getCheckboxRecords();
hasTopTableDropDownActions.value = records.length > 0;
},
};
// 使用自定义的 VxeGrid Hook
const [Grid, gridApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents,
formOptions,
gridOptions,
gridEvents,
});
// 使用 Vben 的 Modal Hook
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: upperCamelCase,
connectedComponent: FormModalDemo,
});
// 定义显示模态框的函数
const showModal = (data = {}, isUpdate = false) => {
formModalApi.setData({
values: data,
update: isUpdate,
gridApi,
});
formModalApi.open();
formModalApi.setData({
// 表单值
values: data,
update: isUpdate,
gridApi,
});
formModalApi.open();
};
// 定义删除操作的 API 函数
const deleteApi = (row: any) => {
let ids = [];
if (row) {
ids.push(row);
} else {
ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
}
deleteupperCamelCase({ ids }).then(() => {
message.success('删除成功!');
gridApi.reload();
});
const hasDelete = (row: any) => {
let ids = [];
if (row) {
ids.push(row);
} else {
ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
}
deleteupperCamelCaseApi({ ids }).then(() => {
message.success('删除成功!');
gridApi.reload();
});
};
</script>
<template>
<!-- 使用 Page 组件包裹整个页面 -->
<Page auto-content-height title="模板名称管理">
<!-- 渲染表单模态框 -->
<FormModal />
<!-- 渲染表格 -->
<Grid>
<!-- 定义表格工具栏按钮 -->
<template #toolbar-buttons>
<TableAction
:actions="[
<Page auto-content-height title="模板名称管理">
<FormModal />
<Grid>
<template #toolbar-buttons>
<TableAction
:actions="[
{
label: '新增',
type: 'primary',
@@ -95,49 +76,55 @@ const deleteApi = (row: any) => {
onClick: showModal.bind(null),
},
]"
:drop-down-actions="[
:drop-down-actions="[
{
label: '删除',
icon: 'ant-design:delete-outlined',
ifShow: hasTopTableDropDownActions,
popConfirm: {
title: '确定删除吗',
confirm: deleteApi.bind(null, false),
confirm: hasDelete.bind(null, false),
},
},
]"
>
<template #more>
<Button style="margin-left: 16px">
批量操作
</Button>
</template>
</TableAction>
</template>
<!-- 定义操作列的自定义模板 -->
<template #action="{ row }">
<TableAction
:actions="[
{
label: '编辑',
type: 'link',
icon: 'uil:edit',
size: 'small',
onClick: showModal.bind(null, row, true),
},
{
label: '删除',
type: 'link',
icon: 'ant-design:delete-outlined',
size: 'small',
popConfirm: {
title: '确定删除吗?',
confirm: deleteApi.bind(null, row.id),
},
},
]"
/>
</template>
</Grid>
</Page>
>
<template #more>
<Button style="margin-left: 16px">
批量操作
</Button>
</template>
</TableAction>
</template>
<template #avatar="{ row }">
<Image :src="row.avatar" height="30" width="30" />
</template>
<template #toolbar-tools></template>
<template #action="{ row }">
<TableAction
:actions="[
{
label: '编辑',
type: 'link',
icon: 'uil:edit',
size: 'small',
// auth: ['admin', 'sys:role:detail'],
onClick: showModal.bind(null, row, true),
},
{
label: '删除',
type: 'link',
icon: 'ant-design:delete-outlined',
size: 'small',
// auth: ['admin', 'sys:role:detail'],
popConfirm: {
title: '确定删除吗?',
confirm: hasDelete.bind(null, row.id),
},
},
]"
:drop-down-actions="[]"
/>
</template>
</Grid>
</Page>
</template>