问卷复制

master
lion 2 weeks ago
parent 9e8048be97
commit b6caed4999

@ -0,0 +1,26 @@
// Copy editable definitions only. IDs, replies, statistics and QR codes belong to the source.
export function surveyCopyDraft(source, questions) {
const clone = value => JSON.parse(JSON.stringify(value))
const form = {
step: '',
title: `${Array.from(source.title || '').slice(0, 251).join('')}(副本)`,
desc: source.desc || '',
course_id: source.course_id ? Number(source.course_id) : '',
course_content_id: source.course_content_id || '',
type_id: source.type_id ? Number(source.type_id) : '',
audience_course_ids: Array.isArray(source.audience_course_ids) ? source.audience_course_ids.map(Number) : [],
start_time: source.start_time || '',
end_time: source.end_time || '',
status: 0,
question: ''
}
const fields = ['course_content_id', 'name', 'field', 'edit_input', 'rule', 'sort', 'help', 'select_item', 'need_fill', 'allow_input', 'dimensions', 'config']
return {
form,
questions: questions.map((question, index) => {
const draft = { id: `copy_${index}`, course_id: form.course_id, course_content_evaluation_id: '' }
fields.forEach(key => { if (Object.prototype.hasOwnProperty.call(question, key)) draft[key] = clone(question[key]) })
return draft
})
}
}

@ -340,6 +340,7 @@ import { index } from "@/api/course/courseContent.js";
import { index as formIndex } from "@/api/survey/index.js";
import { getparameter } from "@/api/system/dictionary.js";
import { deepCopy } from "@/utils";
import { surveyCopyDraft } from "@/utils/surveyCopy";
import applyForm from "../components/applyForm.vue";
import SurveyQuestion from "./SurveyQuestion.vue";
export default {
@ -354,6 +355,7 @@ export default {
type: "add",
active: 0,
id: "",
copyFromId: "",
questionLinkIds: {
course_id: "",
course_content_id: "",
@ -416,6 +418,21 @@ export default {
audienceSelection() { return this.form.audience_course_ids.length ? this.form.audience_course_ids : ['all']; }
},
methods: {
async openCopy(sourceId, courses) {
const [source, questions] = await Promise.all([
show({ id: sourceId }),
formIndex({ filter: [{ key: 'course_content_evaluation_id', op: 'eq', value: sourceId }], page: 1, page_size: 999, sort_name: 'sort', sort_type: 'ASC' })
]);
const draft = surveyCopyDraft(source, questions.data || []);
this.type = 'add';
this.id = '';
this.copyFromId = sourceId;
this.courseList = courses;
this.form = draft.form;
this.questionList = draft.questions;
await this.applySurveyDetails(draft.form);
this.isShow = true;
},
changeAudience(values) {
const addedAll = values.includes('all') && !this.audienceSelection.includes('all');
this.form.audience_course_ids = addedAll ? [] : values.filter(v => v !== 'all').map(Number);
@ -536,15 +553,20 @@ export default {
}));
}
save({
const copying = this.copyFromId && !this.id;
return save({
...this.form,
}).then((res) => {
...(this.id ? { id: this.id } : {}),
...(copying ? { copy_from_id: this.copyFromId } : {}),
}).then(async (res) => {
this.$message({
type: "success",
message: "保存问卷成功",
duration: 2000,
});
this.id = res.id;
this.form.id = res.id;
if (copying) this.copyFromId = '';
this.questionLinkIds = {
course_id: res.course_id,
course_content_id: res.course_content_id,
@ -552,6 +574,7 @@ export default {
};
this.$emit("refresh");
this.active = 1;
if (copying) await this.getquestionList();
// this.active = 1
});
},
@ -607,9 +630,9 @@ export default {
}
},
getDetail() {
show({
id: this.id,
}).then(async (res) => {
return show({ id: this.id }).then(res => this.applySurveyDetails(res));
},
async applySurveyDetails(res) {
this.form = this.base.requestToForm(res, this.form);
this.form.audience_course_ids = Array.isArray(res.audience_course_ids) ? res.audience_course_ids.map(Number) : [];
this.form.status = res.status ? res.status : 0;
@ -655,9 +678,8 @@ export default {
this.questionLinkIds = {
course_id: res.course_id,
course_content_id: res.course_content_id,
course_content_evaluation_id: res.id,
course_content_evaluation_id: res.id || this.id || "",
};
});
},
// 下一步
next() {
@ -751,6 +773,7 @@ export default {
}
} else {
this.id = "";
this.copyFromId = "";
this.course_signs_count = 0;
this.active = 0;
this.questionList = [];

@ -78,8 +78,9 @@
><i class="el-icon-data-analysis"></i>
查看结果</el-dropdown-item
>
<!-- <el-dropdown-item @click.native="duplicateSurvey(survey.id)"><i class="el-icon-document-copy"></i>
复制</el-dropdown-item> -->
<el-dropdown-item :disabled="!!copyingSurveyId" @click.native="duplicateSurvey(survey.id)">
<i class="el-icon-document-copy"></i> 复制
</el-dropdown-item>
<el-dropdown-item
divided
@click.native="deleteSurvey(survey.id)"
@ -208,6 +209,7 @@ export default {
},
data() {
return {
copyingSurveyId: null,
courseList: [],
select: {
page: 1,
@ -290,10 +292,21 @@ export default {
);
},
openCreateModal(type, id) {
if (type === "editor") {
this.$refs.SurveyCreateWizard.id = id;
async duplicateSurvey(id) {
if (this.copyingSurveyId) return;
this.copyingSurveyId = id;
try {
await this.$refs.SurveyCreateWizard.openCopy(id, this.courseList);
} catch (error) {
this.$message.error('复制问卷内容加载失败,请重试');
} finally {
this.copyingSurveyId = null;
}
},
openCreateModal(type, id) {
if (this.copyingSurveyId) return;
this.$refs.SurveyCreateWizard.id = type === "editor" ? id : "";
this.$refs.SurveyCreateWizard.copyFromId = "";
this.$refs.SurveyCreateWizard.type = type;
this.$refs.SurveyCreateWizard.courseList = this.courseList;
this.$refs.SurveyCreateWizard.isShow = true;
@ -393,21 +406,6 @@ export default {
exportData(id) {
this.$message.info("数据导出功能开发中...");
},
duplicateSurvey(id) {
const survey = this.surveys.find((s) => s.id === id);
if (survey) {
const newSurvey = {
...survey,
id: this.surveys.length + 1,
title: survey.title + " (副本)",
status: "draft",
createTime: this.formatNow(),
responses: 0,
};
this.surveys.unshift(newSurvey);
this.filterSurveys();
}
},
deleteSurvey(id) {
var that = this;
this.$confirm("确定要删除这个问卷吗?此操作不可恢复。", "提示", {

@ -0,0 +1,105 @@
import Wizard from '@/views/survey/components/SurveyCreateWizard.vue'
import SurveyList from '@/views/survey/index.vue'
import { surveyCopyDraft } from '@/utils/surveyCopy'
import { show, save } from '@/api/survey/evaluations'
import { index as questionIndex } from '@/api/survey/index'
jest.mock('@/api/survey/evaluations', () => ({ show: jest.fn(), save: jest.fn(), index: jest.fn(), destroy: jest.fn(), qrCode: jest.fn() }))
jest.mock('@/api/survey/index', () => ({ index: jest.fn(), save: jest.fn(), destroy: jest.fn(), reorder: jest.fn() }))
const source = {
id: 10, title: '培训问卷', desc: '<p>说明</p>', course_id: '11', type_id: '3', audience_course_ids: [11, 12],
start_time: '2026-12-01 00:00:00', end_time: '2026-12-31 23:59:59', status: 1,
course_content_evaluation_forms_count: 20, qrCodeData: 'source-qr'
}
const questions = [
{ id: 20, course_content_evaluation_id: 10, field: 'attend', name: '是否参加', edit_input: 'radio', sort: 1, select_item: [{ key: 'yes', value: '是' }] },
{ id: 21, field: 'group', name: '组合题', edit_input: 'multi_dimension', sort: 2, dimensions: [{ field: 'count', edit_input: 'number', config: { min: 0 } }], config: { visible_when: { field: 'attend', values: ['yes'], required_values: ['yes'] } } }
]
function wizard() {
return {
...Wizard.data(), ...Wizard.methods,
base: { requestToForm: (data, form) => Object.fromEntries(Object.keys(form).map(key => [key, data[key] === undefined ? form[key] : data[key]])) },
compareTime: () => false,
$emit: jest.fn(), $message: jest.fn(), $refs: { dialog: { reset: jest.fn() } }, $nextTick: callback => callback()
}
}
describe('Copy a questionnaire into the new-survey dialog', () => {
beforeEach(() => jest.resetAllMocks())
it('opens an independent draft with all editable basics and deep-copied question settings, without saving', async() => {
show.mockResolvedValue(source)
questionIndex.mockResolvedValue({ data: questions })
const state = wizard()
await state.openCopy(10, [{ id: 11, is_arrange: 0 }])
expect(state.isShow).toBe(true)
expect(state.type).toBe('add')
expect(state.id).toBe('')
expect(state.form.id).toBeUndefined()
expect(state.form.title).toBe('培训问卷(副本)')
expect(state.form.status).toBe(0)
expect(state.form.desc).toBe(source.desc)
expect(state.form.audience_course_ids).toEqual([11, 12])
expect(state.form.start_time).toBe(source.start_time)
expect(state.form.qrCodeData).toBeUndefined()
expect(state.form.course_content_evaluation_forms_count).toBeUndefined()
expect(state.questionList[0].id).not.toBe(20)
state.questionList[1].dimensions[0].config.min = 5
state.questionList[1].config.visible_when.values.push('no')
expect(questions[1].dimensions[0].config.min).toBe(0)
expect(questions[1].config.visible_when.values).toEqual(['yes'])
expect(save).not.toHaveBeenCalled()
Wizard.watch.isShow.call(state, false)
expect(state.copyFromId).toBe('')
expect(state.questionList).toEqual([])
})
it('creates the copy only on save, reloads new question IDs and updates that same new survey on subsequent saves', async() => {
show.mockResolvedValue(source)
questionIndex.mockResolvedValueOnce({ data: questions }).mockResolvedValueOnce({ data: questions.map(question => ({ ...question, id: question.id + 100, course_content_evaluation_id: 100 })) })
const state = wizard()
await state.openCopy(10, [{ id: 11, is_arrange: 0 }])
save.mockResolvedValue({ ...source, id: 100, status: 0 })
await state.submit()
expect(save.mock.calls[0][0].copy_from_id).toBe(10)
expect(save.mock.calls[0][0].id).toBeUndefined()
expect(state.id).toBe(100)
expect(state.questionLinkIds.course_content_evaluation_id).toBe(100)
expect(state.questionList[0].id).toBe(120)
state.form.title = '修改新问卷标题'
await state.submit()
expect(save.mock.calls[1][0].id).toBe(100)
expect(save.mock.calls[1][0].copy_from_id).toBeUndefined()
expect(questionIndex).toHaveBeenCalledTimes(2)
})
it('restores selected schedules without retaining the original questionnaire link', async() => {
show.mockResolvedValue({ ...source, course_content_id: '8,9' })
questionIndex.mockResolvedValue({ data: questions })
const state = wizard()
state.filterSurveys = async() => { state.courseContentList = [{ id: 8 }, { id: 9 }, { id: 10 }] }
await state.openCopy(10, [{ id: 11, is_arrange: 1 }])
expect(state.courseContentList.map(item => !!item.checked)).toEqual([true, true, false])
expect(state.selectedCourseSchedules.map(item => item.id)).toEqual([8, 9])
expect(state.questionLinkIds.course_content_evaluation_id).toBe('')
})
it('does not open or create a copy when loading fails and unlocks the list copy menu for retry', async() => {
const state = wizard()
show.mockRejectedValue(new Error('missing source'))
questionIndex.mockResolvedValue({ data: [] })
await expect(state.openCopy(10, [])).rejects.toThrow('missing source')
expect(state.isShow).toBe(false)
expect(save).not.toHaveBeenCalled()
const list = { copyingSurveyId: null, courseList: [], $refs: { SurveyCreateWizard: state }, $message: { error: jest.fn() } }
await SurveyList.methods.duplicateSurvey.call(list, 10)
expect(list.copyingSurveyId).toBeNull()
expect(list.$message.error).toHaveBeenCalled()
})
it('preserves selected schedule links and keeps the draft name within the existing title limit', () => {
const draft = surveyCopyDraft({ ...source, title: '题'.repeat(255), course_content_id: '8,9' }, questions)
expect(draft.form.course_content_id).toBe('8,9')
expect(draft.form.title.length).toBeLessThanOrEqual(255)
})
})
Loading…
Cancel
Save