Compare commits

...

8 Commits

Author SHA1 Message Date
aea0b9aa45 营养管理界面实现 2025-11-21 17:58:05 +08:00
0b22993ad3 营养管理接口 2025-11-21 17:55:20 +08:00
13f2692448 编辑按钮实现 2025-11-21 17:48:11 +08:00
595a2ef47f 添加原料按钮实现 2025-11-21 17:38:44 +08:00
2d864f7f7c 增加搜索框 2025-11-21 17:27:40 +08:00
4f5135a619 修复bug 2025-11-21 16:59:33 +08:00
733c346887 增加原料管理界面 2025-11-21 16:57:50 +08:00
f925df405f 更新swag 2025-11-21 16:46:25 +08:00
10 changed files with 1105 additions and 80 deletions

View File

@@ -1658,7 +1658,7 @@
"parameters": [
{
"type": "string",
"description": "按名称模糊查询",
"description": "按营养名称模糊查询",
"name": "name",
"in": "query"
},
@@ -1679,6 +1679,12 @@
"description": "每页数量",
"name": "page_size",
"in": "query"
},
{
"type": "string",
"description": "按原料名称模糊查询",
"name": "raw_material_name",
"in": "query"
}
],
"responses": {
@@ -2660,10 +2666,16 @@
"parameters": [
{
"type": "string",
"description": "按名称模糊查询",
"description": "按原料名称模糊查询",
"name": "name",
"in": "query"
},
{
"type": "string",
"description": "按营养名称模糊查询",
"name": "nutrient_name",
"in": "query"
},
{
"type": "string",
"description": "排序字段,例如 \"id DESC\"",
@@ -7331,6 +7343,23 @@
}
}
},
"dto.NutrientRawMaterialDTO": {
"type": "object",
"properties": {
"id": {
"description": "原料ID",
"type": "integer"
},
"name": {
"description": "原料名称",
"type": "string"
},
"value": {
"description": "该原料中此营养素的含量",
"type": "number"
}
}
},
"dto.NutrientResponse": {
"type": "object",
"properties": {
@@ -7346,6 +7375,13 @@
"name": {
"type": "string"
},
"raw_materials": {
"description": "包含此营养的原料列表",
"type": "array",
"items": {
"$ref": "#/definitions/dto.NutrientRawMaterialDTO"
}
},
"updated_at": {
"type": "string"
}

View File

@@ -1,9 +1,9 @@
import http from '../utils/http';
import { PaginationDTO, Response } from '../enums';
import {PaginationDTO, Response} from '../enums';
// --- Typedefs for Feed Management ---
// --- Nutrient ---
// --- NutrientRawMaterial ---
/**
* @typedef {object} NutrientResponse
@@ -12,6 +12,14 @@ import { PaginationDTO, Response } from '../enums';
* @property {string} description
* @property {string} created_at
* @property {string} updated_at
* @property {Array<NutrientRawMaterialDTO>} raw_materials - 包含此营养的原料列表
*/
/**
* @typedef {object} NutrientRawMaterialDTO
* @property {number} id - 原料ID
* @property {string} name - 原料名称
* @property {number} value - 该原料中此营养素的含量
*/
/**
@@ -22,7 +30,8 @@ import { PaginationDTO, Response } from '../enums';
/**
* @typedef {object} NutrientsParams
* @property {string} [name] - 按名称模糊查询
* @property {string} [name] - 按营养名称模糊查询
* @property {string} [raw_material_name] - 按原料名称模糊查询
* @property {string} [order_by] - 排序字段,例如 "id DESC"
* @property {number} [page]
* @property {number} [page_size]
@@ -231,7 +240,8 @@ import { PaginationDTO, Response } from '../enums';
/**
* @typedef {object} RawMaterialsParams
* @property {string} [name] - 按名称模糊查询
* @property {string} [name] - 按原料名称模糊查询
* @property {string} [nutrient_name] - 按营养名称模糊查询
* @property {string} [order_by] - 排序字段,例如 "id DESC"
* @property {number} [page]
* @property {number} [page_size]
@@ -257,38 +267,38 @@ import { PaginationDTO, Response } from '../enums';
/**
* 获取营养种类列表
* @param {NutrientsParams} params - 查询参数
* @returns {Promise<ListNutrientResponse>}
* @returns {Promise<Response<ListNutrientResponse>>}
*/
export const getNutrients = (params) => {
return http.get('/api/v1/feed/nutrients', { params });
return http.get('/api/v1/feed/nutrients', {params});
};
/**
* 创建营养种类
* @param {CreateNutrientRequest} data - 请求体
* @returns {Promise<NutrientResponse>}
* @returns {Promise<Response<NutrientResponse>>}
*/
export const createNutrient = (data) => {
return http.post('/api/v1/feed/nutrients', data);
return http.post('/api/v1/feed/nutrients', data);
};
/**
* 获取营养种类详情
* @param {number} id - 营养种类ID
* @returns {Promise<NutrientResponse>}
* @returns {Promise<Response<NutrientResponse>>}
*/
export const getNutrientById = (id) => {
return http.get(`/api/v1/feed/nutrients/${id}`);
return http.get(`/api/v1/feed/nutrients/${id}`);
};
/**
* 更新营养种类
* @param {number} id - 营养种类ID
* @param {UpdateNutrientRequest} data - 请求体
* @returns {Promise<NutrientResponse>}
* @returns {Promise<Response<NutrientResponse>>}
*/
export const updateNutrient = (id, data) => {
return http.put(`/api/v1/feed/nutrients/${id}`, data);
return http.put(`/api/v1/feed/nutrients/${id}`, data);
};
/**
@@ -297,7 +307,7 @@ export const updateNutrient = (id, data) => {
* @returns {Promise<Response>}
*/
export const deleteNutrient = (id) => {
return http.delete(`/api/v1/feed/nutrients/${id}`);
return http.delete(`/api/v1/feed/nutrients/${id}`);
};
// --- PigAgeStage ---
@@ -305,38 +315,38 @@ export const deleteNutrient = (id) => {
/**
* 获取猪年龄阶段列表
* @param {PigAgeStagesParams} params - 查询参数
* @returns {Promise<ListPigAgeStageResponse>}
* @returns {Promise<Response<ListPigAgeStageResponse>>}
*/
export const getPigAgeStages = (params) => {
return http.get('/api/v1/feed/pig-age-stages', { params });
return http.get('/api/v1/feed/pig-age-stages', {params});
};
/**
* 创建猪年龄阶段
* @param {CreatePigAgeStageRequest} data - 请求体
* @returns {Promise<PigAgeStageResponse>}
* @returns {Promise<Response<PigAgeStageResponse>>}
*/
export const createPigAgeStage = (data) => {
return http.post('/api/v1/feed/pig-age-stages', data);
return http.post('/api/v1/feed/pig-age-stages', data);
};
/**
* 获取猪年龄阶段详情
* @param {number} id - 猪年龄阶段ID
* @returns {Promise<PigAgeStageResponse>}
* @returns {Promise<Response<PigAgeStageResponse>>}
*/
export const getPigAgeStageById = (id) => {
return http.get(`/api/v1/feed/pig-age-stages/${id}`);
return http.get(`/api/v1/feed/pig-age-stages/${id}`);
};
/**
* 更新猪年龄阶段
* @param {number} id - 猪年龄阶段ID
* @param {UpdatePigAgeStageRequest} data - 请求体
* @returns {Promise<PigAgeStageResponse>}
* @returns {Promise<Response<PigAgeStageResponse>>}
*/
export const updatePigAgeStage = (id, data) => {
return http.put(`/api/v1/feed/pig-age-stages/${id}`, data);
return http.put(`/api/v1/feed/pig-age-stages/${id}`, data);
};
/**
@@ -345,7 +355,7 @@ export const updatePigAgeStage = (id, data) => {
* @returns {Promise<Response>}
*/
export const deletePigAgeStage = (id) => {
return http.delete(`/api/v1/feed/pig-age-stages/${id}`);
return http.delete(`/api/v1/feed/pig-age-stages/${id}`);
};
// --- PigBreed ---
@@ -353,38 +363,38 @@ export const deletePigAgeStage = (id) => {
/**
* 获取猪品种列表
* @param {PigBreedsParams} params - 查询参数
* @returns {Promise<ListPigBreedResponse>}
* @returns {Promise<Response<ListPigBreedResponse>>}
*/
export const getPigBreeds = (params) => {
return http.get('/api/v1/feed/pig-breeds', { params });
return http.get('/api/v1/feed/pig-breeds', {params});
};
/**
* 创建猪品种
* @param {CreatePigBreedRequest} data - 请求体
* @returns {Promise<PigBreedResponse>}
* @returns {Promise<Response<PigBreedResponse>>}
*/
export const createPigBreed = (data) => {
return http.post('/api/v1/feed/pig-breeds', data);
return http.post('/api/v1/feed/pig-breeds', data);
};
/**
* 获取猪品种详情
* @param {number} id - 猪品种ID
* @returns {Promise<PigBreedResponse>}
* @returns {Promise<Response<PigBreedResponse>>}
*/
export const getPigBreedById = (id) => {
return http.get(`/api/v1/feed/pig-breeds/${id}`);
return http.get(`/api/v1/feed/pig-breeds/${id}`);
};
/**
* 更新猪品种
* @param {number} id - 猪品种ID
* @param {UpdatePigBreedRequest} data - 请求体
* @returns {Promise<PigBreedResponse>}
* @returns {Promise<Response<PigBreedResponse>>}
*/
export const updatePigBreed = (id, data) => {
return http.put(`/api/v1/feed/pig-breeds/${id}`, data);
return http.put(`/api/v1/feed/pig-breeds/${id}`, data);
};
/**
@@ -393,7 +403,7 @@ export const updatePigBreed = (id, data) => {
* @returns {Promise<Response>}
*/
export const deletePigBreed = (id) => {
return http.delete(`/api/v1/feed/pig-breeds/${id}`);
return http.delete(`/api/v1/feed/pig-breeds/${id}`);
};
// --- PigType ---
@@ -401,38 +411,38 @@ export const deletePigBreed = (id) => {
/**
* 获取猪类型列表
* @param {PigTypesParams} params - 查询参数
* @returns {Promise<ListPigTypeResponse>}
* @returns {Promise<Response<ListPigTypeResponse>>}
*/
export const getPigTypes = (params) => {
return http.get('/api/v1/feed/pig-types', { params });
return http.get('/api/v1/feed/pig-types', {params});
};
/**
* 创建猪类型
* @param {CreatePigTypeRequest} data - 请求体
* @returns {Promise<PigTypeResponse>}
* @returns {Promise<Response<PigTypeResponse>>}
*/
export const createPigType = (data) => {
return http.post('/api/v1/feed/pig-types', data);
return http.post('/api/v1/feed/pig-types', data);
};
/**
* 获取猪类型详情
* @param {number} id - 猪类型ID
* @returns {Promise<PigTypeResponse>}
* @returns {Promise<Response<PigTypeResponse>>}
*/
export const getPigTypeById = (id) => {
return http.get(`/api/v1/feed/pig-types/${id}`);
return http.get(`/api/v1/feed/pig-types/${id}`);
};
/**
* 更新猪类型
* @param {number} id - 猪类型ID
* @param {UpdatePigTypeRequest} data - 请求体
* @returns {Promise<PigTypeResponse>}
* @returns {Promise<Response<PigTypeResponse>>}
*/
export const updatePigType = (id, data) => {
return http.put(`/api/v1/feed/pig-types/${id}`, data);
return http.put(`/api/v1/feed/pig-types/${id}`, data);
};
/**
@@ -441,7 +451,7 @@ export const updatePigType = (id, data) => {
* @returns {Promise<Response>}
*/
export const deletePigType = (id) => {
return http.delete(`/api/v1/feed/pig-types/${id}`);
return http.delete(`/api/v1/feed/pig-types/${id}`);
};
// --- RawMaterial ---
@@ -449,38 +459,38 @@ export const deletePigType = (id) => {
/**
* 获取原料列表
* @param {RawMaterialsParams} params - 查询参数
* @returns {Promise<ListRawMaterialResponse>}
* @returns {Promise<Response<ListRawMaterialResponse>>}
*/
export const getRawMaterials = (params) => {
return http.get('/api/v1/feed/raw-materials', { params });
return http.get('/api/v1/feed/raw-materials', {params});
};
/**
* 创建原料
* @param {CreateRawMaterialRequest} data - 请求体
* @returns {Promise<RawMaterialResponse>}
* @returns {Promise<Response<RawMaterialResponse>>}
*/
export const createRawMaterial = (data) => {
return http.post('/api/v1/feed/raw-materials', data);
return http.post('/api/v1/feed/raw-materials', data);
};
/**
* 获取原料详情
* @param {number} id - 原料ID
* @returns {Promise<RawMaterialResponse>}
* @returns {Promise<Response<RawMaterialResponse>>}
*/
export const getRawMaterialById = (id) => {
return http.get(`/api/v1/feed/raw-materials/${id}`);
return http.get(`/api/v1/feed/raw-materials/${id}`);
};
/**
* 更新原料
* @param {number} id - 原料ID
* @param {UpdateRawMaterialRequest} data - 请求体
* @returns {Promise<RawMaterialResponse>}
* @returns {Promise<Response<RawMaterialResponse>>}
*/
export const updateRawMaterial = (id, data) => {
return http.put(`/api/v1/feed/raw-materials/${id}`, data);
return http.put(`/api/v1/feed/raw-materials/${id}`, data);
};
/**
@@ -489,34 +499,34 @@ export const updateRawMaterial = (id, data) => {
* @returns {Promise<Response>}
*/
export const deleteRawMaterial = (id) => {
return http.delete(`/api/v1/feed/raw-materials/${id}`);
return http.delete(`/api/v1/feed/raw-materials/${id}`);
};
export const FeedApi = {
getNutrients,
createNutrient,
getNutrientById,
updateNutrient,
deleteNutrient,
getPigAgeStages,
createPigAgeStage,
getPigAgeStageById,
updatePigAgeStage,
deletePigAgeStage,
getPigBreeds,
createPigBreed,
getPigBreedById,
updatePigBreed,
deletePigBreed,
getPigTypes,
createPigType,
getPigTypeById,
updatePigType,
deletePigType,
getRawMaterials,
createRawMaterial,
getRawMaterialById,
updateRawMaterial,
deleteRawMaterial,
getNutrients,
createNutrient,
getNutrientById,
updateNutrient,
deleteNutrient,
getPigAgeStages,
createPigAgeStage,
getPigAgeStageById,
updatePigAgeStage,
deletePigAgeStage,
getPigBreeds,
createPigBreed,
getPigBreedById,
updatePigBreed,
deletePigBreed,
getPigTypes,
createPigType,
getPigTypeById,
updatePigType,
deletePigType,
getRawMaterials,
createRawMaterial,
getRawMaterialById,
updateRawMaterial,
deleteRawMaterial,
};

View File

@@ -0,0 +1,103 @@
<template>
<el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
<el-form-item label="营养名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入营养名称"></el-input>
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input
v-model="formData.description"
type="textarea"
:rows="3"
placeholder="请输入营养描述"
></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
<el-button @click="cancelForm">取消</el-button>
</el-form-item>
</el-form>
</template>
<script>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
export default {
name: 'NutrientForm',
props: {
isEdit: {
type: Boolean,
default: false,
},
initialData: {
type: Object,
default: () => ({
name: '',
description: '',
}),
},
},
emits: ['submit', 'cancel'],
setup(props, { emit }) {
const formRef = ref(null);
const formData = reactive({
name: '',
description: '',
});
// 监听 initialData 变化,用于编辑模式下初始化表单
watch(
() => props.initialData,
(newVal) => {
if (newVal) {
formData.name = newVal.name || '';
formData.description = newVal.description || '';
}
},
{ immediate: true, deep: true }
);
const rules = {
name: [
{ required: true, message: '请输入营养名称', trigger: 'blur' },
{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
],
};
const submitForm = () => {
formRef.value.validate((valid) => {
if (valid) {
emit('submit', { ...formData });
} else {
ElMessage.error('请检查表单项');
return false;
}
});
};
const cancelForm = () => {
emit('cancel');
resetForm();
};
const resetForm = () => {
formRef.value.resetFields();
// 手动重置 formData因为 resetFields 不会重置未绑定 prop 的字段
formData.name = '';
formData.description = '';
};
return {
formRef,
formData,
rules,
submitForm,
cancelForm,
resetForm,
};
},
};
</script>
<style scoped>
</style>

View File

@@ -0,0 +1,190 @@
<template>
<div>
<!-- 搜索区域 -->
<div style="margin-bottom: 20px; display: flex; align-items: center; gap: 10px;">
<el-select v-model="searchType" placeholder="请选择搜索类型" style="width: 150px;">
<el-option label="按营养名称" value="name"></el-option>
<!-- 根据接口定义也可以按 raw_material_name 搜索但目前界面上只提供按营养名称搜索 -->
<!-- <el-option label="按原料名称" value="raw_material_name"></el-option> -->
</el-select>
<el-input
v-model="searchKeyword"
placeholder="请输入关键词"
clearable
style="width: 300px;"
@keyup.enter="handleSearch"
></el-input>
<el-button type="primary" @click="handleSearch">搜索</el-button>
</div>
<!-- 营养列表 -->
<el-table :data="tableData" style="width: 100%" v-loading="loading" row-key="id"
:expand-row-keys="expandRowKeys" @expand-change="handleExpandChange">
<el-table-column type="expand">
<template #default="props">
<div style="padding: 10px 20px;">
<h4>包含此营养的原料</h4>
<el-table :data="props.row.raw_materials" border>
<el-table-column prop="name" label="原料名称"></el-table-column>
<el-table-column prop="value" label="含量"></el-table-column>
</el-table>
</div>
</template>
</el-table-column>
<!-- 移除 ID -->
<el-table-column prop="name" label="营养名称"></el-table-column>
<el-table-column prop="description" label="描述"></el-table-column>
<el-table-column label="操作" width="180">
<template #default="scope">
<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<el-pagination
style="margin-top: 20px;"
:current-page="pagination.page"
:page-size="pagination.page_size"
:total="pagination.total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
></el-pagination>
</div>
</template>
<script>
import {ref, onMounted} from 'vue';
import {FeedApi} from '../../api/feed';
import {ElMessageBox, ElMessage} from 'element-plus';
export default {
name: 'NutrientTable',
emits: ['edit'], // 声明触发的事件
setup(props, { emit }) {
const tableData = ref([]);
const loading = ref(false);
const searchKeyword = ref('');
const searchType = ref('name'); // 默认按营养名称搜索
const expandRowKeys = ref([]); // 用于控制展开行
const pagination = ref({
page: 1,
page_size: 10,
total: 0,
});
const fetchNutrients = async () => {
loading.value = true;
try {
const params = {
page: pagination.value.page,
page_size: pagination.value.page_size,
};
if (searchKeyword.value) {
params[searchType.value] = searchKeyword.value;
}
const response = await FeedApi.getNutrients(params);
if (response.data) {
tableData.value = response.data.list;
pagination.value.total = response.data.pagination.total;
}
} catch (error) {
console.error('获取营养列表失败:', error);
ElMessage.error('获取营养列表失败');
} finally {
loading.value = false;
}
};
const handleSearch = () => {
pagination.value.page = 1;
fetchNutrients();
};
const handleSizeChange = (size) => {
pagination.value.page_size = size;
fetchNutrients();
};
const handleCurrentChange = (page) => {
pagination.value.page = page;
fetchNutrients();
};
// 处理行展开/折叠事件
const handleExpandChange = async (row, expandedRows) => {
const isExpanded = expandedRows.some(r => r.id === row.id);
// 优化:仅在展开时且数据未加载时才请求
if (isExpanded && (!row.raw_materials || row.raw_materials.length === 0)) {
try {
const response = await FeedApi.getNutrientById(row.id);
if (response.data) {
const index = tableData.value.findIndex(item => item.id === row.id);
if (index !== -1) {
tableData.value[index].raw_materials = response.data.raw_materials;
}
}
} catch (error) {
console.error('获取营养详情失败:', error);
ElMessage.error('获取营养所含原料失败');
}
}
};
const handleEdit = (row) => {
emit('edit', row); // 触发 edit 事件,并传递当前行数据
};
const handleDelete = (row) => {
ElMessageBox.confirm(
`确定要删除营养 "${row.name}" 吗?`,
'提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
).then(async () => {
try {
await FeedApi.deleteNutrient(row.id);
ElMessage.success('删除成功');
await fetchNutrients();
} catch (error) {
ElMessage.error('删除失败: ' + (error.message || '未知错误'));
}
}).catch(() => {
// 用户取消操作
});
};
onMounted(() => {
fetchNutrients();
});
return {
tableData,
loading,
searchKeyword,
searchType,
expandRowKeys,
pagination,
handleSearch,
handleSizeChange,
handleCurrentChange,
handleExpandChange,
handleEdit,
handleDelete,
fetchNutrients, // 将方法暴露出去
};
},
};
</script>
<style scoped>
</style>

View File

@@ -0,0 +1,103 @@
<template>
<el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
<el-form-item label="原料名称" prop="name">
<el-input v-model="formData.name" placeholder="请输入原料名称"></el-input>
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input
v-model="formData.description"
type="textarea"
:rows="3"
placeholder="请输入原料描述"
></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
<el-button @click="cancelForm">取消</el-button>
</el-form-item>
</el-form>
</template>
<script>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
export default {
name: 'RawMaterialForm',
props: {
isEdit: {
type: Boolean,
default: false,
},
initialData: {
type: Object,
default: () => ({
name: '',
description: '',
}),
},
},
emits: ['submit', 'cancel'],
setup(props, { emit }) {
const formRef = ref(null);
const formData = reactive({
name: '',
description: '',
});
// 监听 initialData 变化,用于编辑模式下初始化表单
watch(
() => props.initialData,
(newVal) => {
if (newVal) {
formData.name = newVal.name || '';
formData.description = newVal.description || '';
}
},
{ immediate: true, deep: true }
);
const rules = {
name: [
{ required: true, message: '请输入原料名称', trigger: 'blur' },
{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
],
};
const submitForm = () => {
formRef.value.validate((valid) => {
if (valid) {
emit('submit', { ...formData });
} else {
ElMessage.error('请检查表单项');
return false;
}
});
};
const cancelForm = () => {
emit('cancel');
resetForm();
};
const resetForm = () => {
formRef.value.resetFields();
// 手动重置 formData因为 resetFields 不会重置未绑定 prop 的字段
formData.name = '';
formData.description = '';
};
return {
formRef,
formData,
rules,
submitForm,
cancelForm,
resetForm,
};
},
};
</script>
<style scoped>
</style>

View File

@@ -0,0 +1,184 @@
<template>
<div>
<!-- 搜索区域 -->
<div style="margin-bottom: 20px; display: flex; align-items: center; gap: 10px;">
<el-select v-model="searchType" placeholder="请选择搜索类型" style="width: 150px;">
<el-option label="按原料名称" value="name"></el-option>
<el-option label="按营养名称" value="nutrient_name"></el-option>
</el-select>
<el-input
v-model="searchKeyword"
placeholder="请输入关键词"
clearable
style="width: 300px;"
@keyup.enter="handleSearch"
></el-input>
<el-button type="primary" @click="handleSearch">搜索</el-button>
</div>
<!-- 原料列表 -->
<el-table :data="tableData" style="width: 100%" v-loading="loading" row-key="id"
:expand-row-keys="expandRowKeys" @expand-change="handleExpandChange">
<el-table-column type="expand">
<template #default="props">
<div style="padding: 10px 20px;">
<h4>营养成分</h4>
<el-table :data="props.row.raw_material_nutrients" border>
<el-table-column prop="nutrient_name" label="营养名称"></el-table-column>
<el-table-column prop="value" label="含量"></el-table-column>
</el-table>
</div>
</template>
</el-table-column>
<el-table-column prop="name" label="原料名称"></el-table-column>
<el-table-column prop="description" label="描述"></el-table-column>
<el-table-column label="操作">
<template #default="scope">
<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
<el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页 -->
<el-pagination
style="margin-top: 20px;"
:current-page="pagination.page"
:page-size="pagination.page_size"
:total="pagination.total"
layout="total, sizes, prev, pager, next, jumper"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
></el-pagination>
</div>
</template>
<script>
import {ref, onMounted} from 'vue';
import {FeedApi} from '../../api/feed';
import {ElMessageBox, ElMessage} from 'element-plus';
export default {
name: 'RawMaterialTable',
emits: ['edit'], // 声明触发的事件
setup(props, { emit }) {
const tableData = ref([]);
const loading = ref(false);
const searchKeyword = ref('');
const searchType = ref('name'); // 默认按原料名称搜索
const expandRowKeys = ref([]);
const pagination = ref({
page: 1,
page_size: 10,
total: 0,
});
const fetchRawMaterials = async () => {
loading.value = true;
try {
const params = {
page: pagination.value.page,
page_size: pagination.value.page_size,
};
if (searchKeyword.value) {
params[searchType.value] = searchKeyword.value;
}
const response = await FeedApi.getRawMaterials(params);
if (response.data) {
tableData.value = response.data.list;
pagination.value.total = response.data.pagination.total;
}
} catch (error) {
console.error('获取原料列表失败:', error);
ElMessage.error('获取原料列表失败');
} finally {
loading.value = false;
}
};
const handleSearch = () => {
pagination.value.page = 1;
fetchRawMaterials();
};
const handleSizeChange = (size) => {
pagination.value.page_size = size;
fetchRawMaterials();
};
const handleCurrentChange = (page) => {
pagination.value.page = page;
fetchRawMaterials();
};
const handleExpandChange = async (row, expandedRows) => {
const isExpanded = expandedRows.some(r => r.id === row.id);
// 优化:仅在展开时且数据未加载时才请求
if (isExpanded && (!row.raw_material_nutrients || row.raw_material_nutrients.length === 0)) {
try {
const response = await FeedApi.getRawMaterialById(row.id);
if (response.data) {
const index = tableData.value.findIndex(item => item.id === row.id);
if (index !== -1) {
tableData.value[index].raw_material_nutrients = response.data.raw_material_nutrients;
}
}
} catch (error) {
console.error('获取原料详情失败:', error);
ElMessage.error('获取原料营养成分失败');
}
}
};
const handleDelete = (row) => {
ElMessageBox.confirm(
`确定要删除原料 "${row.name}" 吗?`,
'提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
).then(async () => {
try {
await FeedApi.deleteRawMaterial(row.id);
ElMessage.success('删除成功');
await fetchRawMaterials();
} catch (error) {
ElMessage.error('删除失败: ' + (error.message || '未知错误'));
}
}).catch(() => {
// 用户取消操作
});
};
const handleEdit = (row) => {
emit('edit', row); // 触发 edit 事件,并传递当前行数据
};
onMounted(() => {
fetchRawMaterials();
});
return {
tableData,
loading,
searchKeyword,
searchType,
pagination,
expandRowKeys,
handleSearch,
handleSizeChange,
handleCurrentChange,
handleExpandChange,
handleEdit,
handleDelete,
fetchRawMaterials, // 将方法暴露出去
};
},
};
</script>

View File

@@ -17,7 +17,7 @@
:collapse="isCollapse"
:collapse-transition="false"
router
:default-openeds="['/device-management', '/monitor', '/pms', '/alarm']"
:default-openeds="['/device-management', '/monitor', '/pms', '/alarm', '/feed']"
>
<el-menu-item index="/">
<el-icon>
@@ -70,6 +70,29 @@
</el-menu-item>
</el-sub-menu>
<!-- 饲料管理二级菜单 -->
<el-sub-menu index="/feed">
<template #title>
<el-icon>
<TakeawayBox />
</el-icon>
<span>饲料管理</span>
</template>
<el-menu-item index="/feed/raw-materials">
<el-icon>
<Tickets/>
</el-icon>
<template #title>原料管理</template>
</el-menu-item>
<el-menu-item index="/feed/nutrients">
<el-icon>
<Tickets/>
</el-icon>
<template #title>营养管理</template>
</el-menu-item>
</el-sub-menu>
<el-menu-item index="/plans">
<el-icon>
<Calendar/>
@@ -280,7 +303,8 @@ import {
ScaleToOriginal,
OfficeBuilding,
Management,
Bell
Bell,
TakeawayBox
} from '@element-plus/icons-vue';
import { getActiveAlarms } from '../api/alarm'; // 导入告警API
@@ -312,7 +336,8 @@ export default {
ScaleToOriginal,
OfficeBuilding,
Management,
Bell
Bell,
TakeawayBox
},
setup() {
const route = useRoute();
@@ -396,7 +421,7 @@ export default {
const activeMenu = computed(() => {
const path = route.path;
if (path.startsWith('/monitor') || path.startsWith('/pms') || path.startsWith('/devices') || path.startsWith('/device-templates') || path.startsWith('/alarms')) {
if (path.startsWith('/monitor') || path.startsWith('/pms') || path.startsWith('/devices') || path.startsWith('/device-templates') || path.startsWith('/alarms') || path.startsWith('/feed')) {
return path;
}
return route.path;

View File

@@ -23,6 +23,8 @@ import WeighingBatchesView from '../views/monitor/WeighingBatchesView.vue';
import WeighingRecordsView from '../views/monitor/WeighingRecordsView.vue';
import AlarmList from '../views/alarm/AlarmList.vue';
import ThresholdAlarmList from '../views/alarm/ThresholdAlarmList.vue';
import RawMaterialList from '../views/feed/RawMaterialList.vue';
import NutrientList from '../views/feed/NutrientList.vue'; // 导入 NutrientList 组件
const routes = [
{path: '/', component: Home, meta: {requiresAuth: true, title: '系统首页'}},
@@ -34,6 +36,8 @@ const routes = [
{path: '/login', component: LoginForm},
{path: '/pms/farm-management', name: 'PigFarmManagement', component: PigFarmManagementView, meta: { requiresAuth: true, title: '栏舍管理' }},
{path: '/pms/batch-management', name: 'PigBatchManagement', component: PigBatchManagementView, meta: { requiresAuth: true, title: '猪群管理' }},
{path: '/feed/raw-materials', component: RawMaterialList, meta: {requiresAuth: true, title: '原料管理'}},
{path: '/feed/nutrients', component: NutrientList, meta: {requiresAuth: true, title: '营养管理'}}, // 添加营养管理路由
{path: '/monitor/device-command-logs', component: DeviceCommandLogView, meta: {requiresAuth: true, title: '设备命令日志'}},
{path: '/monitor/medication-logs', component: MedicationLogsView, meta: {requiresAuth: true, title: '用药记录'}},
{path: '/monitor/notifications', component: NotificationLogView, meta: {requiresAuth: true, title: '通知记录'}},

View File

@@ -0,0 +1,184 @@
<template>
<div class="nutrient-list-container">
<el-card>
<template #header>
<div class="card-header">
<div class="title-container">
<h2 class="page-title">营养管理</h2>
<el-button type="text" @click="refreshList" class="refresh-btn" title="刷新营养列表">
<el-icon :size="20"><Refresh /></el-icon>
</el-button>
</div>
<el-button type="primary" @click="handleAddNutrient">添加营养</el-button>
</div>
</template>
<nutrient-table ref="nutrientTableRef" @edit="handleEdit"></nutrient-table>
</el-card>
<!-- 添加/编辑营养弹窗 -->
<el-dialog
v-model="showDialog"
:title="formTitle"
width="500px"
:close-on-click-modal="false"
@close="handleCancel"
>
<!-- 只有在弹窗显示时才渲染表单组件并传递编辑状态和初始数据 -->
<nutrient-form
v-if="showDialog"
ref="nutrientFormRef"
:isEdit="isEditMode"
:initialData="currentEditData"
@submit="handleSubmit"
@cancel="handleCancel"
></nutrient-form>
</el-dialog>
</div>
</template>
<script>
import { ref, nextTick } from 'vue';
import { Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import NutrientTable from '../../components/feed/NutrientTable.vue';
import NutrientForm from '../../components/feed/NutrientForm.vue';
import { FeedApi } from '../../api/feed';
export default {
name: 'NutrientList',
components: {
NutrientTable,
NutrientForm,
Refresh,
},
setup() {
const nutrientTableRef = ref(null);
const nutrientFormRef = ref(null);
const showDialog = ref(false);
const isEditMode = ref(false);
const currentEditData = ref(null);
const formTitle = ref('添加营养');
const refreshList = () => {
if (nutrientTableRef.value) {
nutrientTableRef.value.fetchNutrients();
}
};
// 处理添加营养按钮点击事件
const handleAddNutrient = () => {
formTitle.value = '添加营养';
isEditMode.value = false; // 新增模式
currentEditData.value = null; // 清空编辑数据
showDialog.value = true;
nextTick(() => {
nutrientFormRef.value?.resetForm();
});
};
// 处理编辑按钮点击事件
const handleEdit = (row) => {
formTitle.value = '编辑营养';
isEditMode.value = true; // 编辑模式
currentEditData.value = { ...row }; // 存储当前编辑数据,进行深拷贝
showDialog.value = true;
};
// 处理表单提交
const handleSubmit = async (formData) => {
try {
let message = '';
if (isEditMode.value) {
// 编辑模式
await FeedApi.updateNutrient(currentEditData.value.id, formData);
message = '营养更新成功';
} else {
// 新增模式
await FeedApi.createNutrient(formData);
message = '营养添加成功';
}
ElMessage.success(message);
refreshList(); // 刷新列表
showDialog.value = false; // 关闭弹窗
} catch (error) {
ElMessage.error('操作失败: ' + (error.message || '未知错误'));
}
};
// 处理弹窗取消或关闭
const handleCancel = () => {
showDialog.value = false;
// 关闭弹窗时重置表单和编辑状态
if (nutrientFormRef.value) {
nutrientFormRef.value.resetForm();
}
isEditMode.value = false;
currentEditData.value = null;
};
return {
nutrientTableRef,
nutrientFormRef,
showDialog,
formTitle,
isEditMode,
currentEditData,
refreshList,
handleAddNutrient,
handleEdit,
handleSubmit,
handleCancel,
};
},
};
</script>
<style scoped>
.nutrient-list-container {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
}
.title-container {
display: flex;
align-items: center;
gap: 5px;
}
.page-title {
margin: 0;
font-size: 1.5rem;
font-weight: bold;
line-height: 1;
}
.refresh-btn {
color: black;
background-color: transparent;
padding: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border: none;
}
@media (max-width: 768px) {
.nutrient-list-container {
padding: 10px;
}
.card-header {
flex-direction: column;
gap: 15px;
}
}
</style>

View File

@@ -0,0 +1,186 @@
<template>
<div class="raw-material-list-container">
<el-card>
<template #header>
<div class="card-header">
<div class="title-container">
<h2 class="page-title">原料管理</h2>
<el-button type="text" @click="refreshList" class="refresh-btn" title="刷新原料列表">
<el-icon :size="20"><Refresh /></el-icon>
</el-button>
</div>
<el-button type="primary" @click="handleAddRawMaterial">添加原料</el-button>
</div>
</template>
<!-- 确保只有一个 raw-material-table 实例并正确绑定事件 -->
<raw-material-table ref="rawMaterialTableRef" @edit="handleEdit"></raw-material-table>
</el-card>
<!-- 添加/编辑原料弹窗 -->
<el-dialog
v-model="showDialog"
:title="formTitle"
width="500px"
:close-on-click-modal="false"
@close="handleCancel"
>
<!-- 只有在弹窗显示时才渲染表单组件并传递编辑状态和初始数据 -->
<raw-material-form
v-if="showDialog"
ref="rawMaterialFormRef"
:isEdit="isEditMode"
:initialData="currentEditData"
@submit="handleSubmit"
@cancel="handleCancel"
></raw-material-form>
</el-dialog>
</div>
</template>
<script>
import { ref, nextTick } from 'vue'; // 导入 nextTick
import { Refresh } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import RawMaterialTable from '../../components/feed/RawMaterialTable.vue';
import RawMaterialForm from '../../components/feed/RawMaterialForm.vue';
import { FeedApi } from '../../api/feed';
export default {
name: 'RawMaterialList',
components: {
RawMaterialTable,
Refresh,
RawMaterialForm,
},
setup() {
const rawMaterialTableRef = ref(null);
const rawMaterialFormRef = ref(null); // 用于引用 RawMaterialForm 组件
const showDialog = ref(false);
const isEditMode = ref(false); // 标识当前是新增模式还是编辑模式
const currentEditData = ref(null); // 存储当前正在编辑的原料数据
const formTitle = ref('添加原料');
const refreshList = () => {
if (rawMaterialTableRef.value) {
rawMaterialTableRef.value.fetchRawMaterials();
}
};
// 处理添加原料按钮点击事件
const handleAddRawMaterial = () => {
formTitle.value = '添加原料';
isEditMode.value = false; // 新增模式
currentEditData.value = null; // 清空编辑数据
showDialog.value = true;
// 在 nextTick 中执行,确保 DOM 更新完成,表单组件被渲染后才调用 resetForm
nextTick(() => {
rawMaterialFormRef.value?.resetForm();
});
};
// 处理编辑按钮点击事件
const handleEdit = (row) => {
formTitle.value = '编辑原料';
isEditMode.value = true; // 编辑模式
currentEditData.value = { ...row }; // 存储当前编辑数据,进行深拷贝
showDialog.value = true;
};
// 处理表单提交
const handleSubmit = async (formData) => {
try {
let message = '';
if (isEditMode.value) {
// 编辑模式
await FeedApi.updateRawMaterial(currentEditData.value.id, formData);
message = '原料更新成功';
} else {
// 新增模式
await FeedApi.createRawMaterial(formData);
message = '原料添加成功';
}
ElMessage.success(message);
refreshList(); // 刷新列表
showDialog.value = false; // 关闭弹窗
} catch (error) {
ElMessage.error('操作失败: ' + (error.message || '未知错误'));
}
};
// 处理弹窗取消或关闭
const handleCancel = () => {
showDialog.value = false;
// 关闭弹窗时重置表单和编辑状态
if (rawMaterialFormRef.value) {
rawMaterialFormRef.value.resetForm();
}
isEditMode.value = false;
currentEditData.value = null;
};
return {
rawMaterialTableRef,
rawMaterialFormRef,
showDialog,
formTitle,
isEditMode,
currentEditData,
refreshList,
handleAddRawMaterial,
handleEdit,
handleSubmit,
handleCancel,
};
},
};
</script>
<style scoped>
.raw-material-list-container {
padding: 20px;
max-width: 1200px;
margin: 0 auto;
}
.card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 0;
}
.title-container {
display: flex;
align-items: center;
gap: 5px;
}
.page-title {
margin: 0;
font-size: 1.5rem;
font-weight: bold;
line-height: 1;
}
.refresh-btn {
color: black;
background-color: transparent;
padding: 0;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
border: none;
}
@media (max-width: 768px) {
.raw-material-list-container {
padding: 10px;
}
.card-header {
flex-direction: column;
gap: 15px;
}
}
</style>