Skip to content

Commit

Permalink
feat: 优化问卷分组功能
Browse files Browse the repository at this point in the history
  • Loading branch information
luch1994 committed Jan 3, 2025
1 parent 89544e2 commit 4a6dbf9
Show file tree
Hide file tree
Showing 14 changed files with 255 additions and 124 deletions.
4 changes: 4 additions & 0 deletions server/src/enums/surveyGroup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export enum GROUP_STATE {
ALL = 'all',
UNCLASSIFIED = 'unclassified',
}
27 changes: 21 additions & 6 deletions server/src/modules/survey/__test/surveyGroup.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,12 @@ describe('SurveyGroupController', () => {

describe('findAll', () => {
it('should return a list of survey groups', async () => {
const result = { total: 0, notTotal: 0, list: [], allList: [] };
const result = {
total: 0,
unclassifiedSurveyTotal: 0,
list: [],
allList: [],
};
jest.spyOn(service, 'findAll').mockResolvedValue(result);
const mockReq = { user: { _id: new ObjectId() } };
const mockQue = { curPage: 1, pageSize: 10, name: '' };
Expand All @@ -104,7 +109,15 @@ describe('SurveyGroupController', () => {
const id = '1';
jest.spyOn(service, 'update').mockResolvedValue(updatedResult);

expect(await controller.updateOne(id, updatedFields)).toEqual({
expect(
await controller.updateOne(
{
groupId: id,
name: 'xxx',
},
{ user: { _id: new ObjectId() } },
),
).toEqual({
code: 200,
ret: updatedResult,
});
Expand All @@ -113,10 +126,12 @@ describe('SurveyGroupController', () => {

it('should throw error on invalid parameter', async () => {
const id = '1';
const invalidFields: any = {};
await expect(controller.updateOne(id, invalidFields)).rejects.toThrow(
HttpException,
);
await expect(
controller.updateOne(
{ groupId: id, name: '' },
{ user: { _id: new ObjectId() } },
),
).rejects.toThrow(HttpException);
});
});

Expand Down
64 changes: 47 additions & 17 deletions server/src/modules/survey/controllers/surveyGroup.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import {
Controller,
Get,
Post,
Delete,
Body,
Param,
UseGuards,
Request,
HttpCode,
Expand All @@ -23,16 +21,18 @@ import { EXCEPTION_CODE } from 'src/enums/exceptionCode';
import { CreateSurveyGroupDto } from '../dto/createSurveyGroup.dto';
import { UpdateSurveyGroupDto } from '../dto/updateSurveyGroup.dto';
import { GetGroupListDto } from '../dto/getGroupList.dto';
import { CollaboratorService } from '../services/collaborator.service';

@ApiTags('surveyGroup')
@ApiBearerAuth()
@UseGuards(Authentication)
@Controller('api/surveyGroup')
@Controller('/api/surveyGroup')
export class SurveyGroupController {
constructor(
private readonly surveyMetaService: SurveyMetaService,
private readonly SurveyGroupService: SurveyGroupService,
private readonly surveyGroupService: SurveyGroupService,
private readonly logger: Logger,
private readonly collaboratorService: CollaboratorService,
) {}
@Post()
@HttpCode(200)
Expand All @@ -48,7 +48,7 @@ export class SurveyGroupController {
throw new HttpException('参数错误', EXCEPTION_CODE.PARAMETER_ERROR);
}
const userId = req.user._id.toString();
const ret = await this.SurveyGroupService.create({
const ret = await this.surveyGroupService.create({
name: value.name,
ownerId: userId,
});
Expand All @@ -75,7 +75,7 @@ export class SurveyGroupController {
const curPage = Number(value.curPage);
const pageSize = Number(value.pageSize);
const skip = (curPage - 1) * pageSize;
const { total, list, allList } = await this.SurveyGroupService.findAll(
const { total, list, allList } = await this.surveyGroupService.findAll(
userId,
value.name,
skip,
Expand All @@ -95,10 +95,20 @@ export class SurveyGroupController {
pre[cur] = total;
return pre;
}, {});
const notTotal = await this.surveyMetaService.countSurveyMetaByGroupId({
userId,
groupId: null,
});
const unclassifiedSurveyTotal =
await this.surveyMetaService.countSurveyMetaByGroupId({
userId,
groupId: null,
});
const cooperationList =
await this.collaboratorService.getCollaboratorListByUserId({ userId });
const surveyIdList = cooperationList.map((item) => item.surveyId);
const allSurveyTotal =
await this.surveyMetaService.countSurveyMetaByGroupId({
userId,
surveyIdList,
groupId: 'all',
});
return {
code: 200,
data: {
Expand All @@ -112,34 +122,54 @@ export class SurveyGroupController {
};
}),
allList,
notTotal,
unclassifiedSurveyTotal,
allSurveyTotal,
},
};
}

@Post(':id')
@Post('/update')
@HttpCode(200)
async updateOne(
@Param('id') id: string,
@Body()
reqBody: UpdateSurveyGroupDto,
@Request()
req,
) {
const { error, value } = UpdateSurveyGroupDto.validate(reqBody);
if (error) {
this.logger.error(`createSurveyGroup_parameter error: ${error.message}`);
throw new HttpException('参数错误', EXCEPTION_CODE.PARAMETER_ERROR);
}
const ret = await this.SurveyGroupService.update(id, value);
const group = await this.surveyGroupService.findOne(value.groupId);
if (group.ownerId !== req.user._id.toString()) {
throw new HttpException('没有权限', EXCEPTION_CODE.NO_PERMISSION);
}
const ret = await this.surveyGroupService.update(value.group, {
name: value.name,
});
return {
code: 200,
ret,
};
}

@Delete(':id')
@Post('delete')
@HttpCode(200)
async remove(@Param('id') id: string) {
await this.SurveyGroupService.remove(id);
async remove(
@Request()
req,
) {
const groupId = req.body.groupId;
if (!groupId) {
this.logger.error(`deleteSurveyGroup_parameter error: ${groupId}`);
throw new HttpException('参数错误', EXCEPTION_CODE.PARAMETER_ERROR);
}
const group = await this.surveyGroupService.findOne(groupId);
if (group.ownerId !== req.user._id.toString()) {
throw new HttpException('没有权限', EXCEPTION_CODE.NO_PERMISSION);
}
await this.surveyGroupService.remove(groupId);
return {
code: 200,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { PERMISSION as WORKSPACE_PERMISSION } from 'src/enums/workspace';

import { GetSurveyListDto } from '../dto/getSurveyMetaList.dto';
import { CollaboratorService } from '../services/collaborator.service';
import { GROUP_STATE } from 'src/enums/surveyGroup';

@ApiTags('survey')
@Controller('/api/survey')
Expand Down Expand Up @@ -107,8 +108,11 @@ export class SurveyMetaController {
}
}
const userId = req.user._id.toString();
const cooperationList =
await this.collaboratorService.getCollaboratorListByUserId({ userId });
let cooperationList = [];
if (groupId === GROUP_STATE.ALL) {
cooperationList =
await this.collaboratorService.getCollaboratorListByUserId({ userId });
}
const cooperSurveyIdMap = cooperationList.reduce((pre, cur) => {
pre[cur.surveyId] = cur;
return pre;
Expand Down
4 changes: 4 additions & 0 deletions server/src/modules/survey/dto/updateSurveyGroup.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,15 @@ import { ApiProperty } from '@nestjs/swagger';
import Joi from 'joi';

export class UpdateSurveyGroupDto {
@ApiProperty({ description: '分组id', required: true })
groupId: string;

@ApiProperty({ description: '分组名称', required: true })
name: string;

static validate(data) {
return Joi.object({
groupId: Joi.string().required(),
name: Joi.string().required(),
}).validate(data);
}
Expand Down
23 changes: 16 additions & 7 deletions server/src/modules/survey/services/surveyGroup.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,25 @@ import { MongoRepository } from 'typeorm';

import { SurveyGroup } from 'src/models/surveyGroup.entity';
import { SurveyMeta } from 'src/models/surveyMeta.entity';
import { ObjectId } from 'mongodb';

@Injectable()
export class SurveyGroupService {
constructor(
@InjectRepository(SurveyGroup)
private readonly SurveyGroup: MongoRepository<SurveyGroup>,
private readonly surveyGroupRepository: MongoRepository<SurveyGroup>,
@InjectRepository(SurveyMeta)
private surveyMetaRepository: MongoRepository<SurveyMeta>,
) {}
create(params: { name: string; ownerId: string }) {
const newGroup = this.SurveyGroup.create({
const newGroup = this.surveyGroupRepository.create({
...params,
});
return this.SurveyGroup.save(newGroup);
return this.surveyGroupRepository.save(newGroup);
}

async findAll(userId: string, name: string, skip: number, pageSize: number) {
const [list, total] = await this.SurveyGroup.findAndCount({
const [list, total] = await this.surveyGroupRepository.findAndCount({
skip: skip,
take: pageSize,
where: name
Expand All @@ -31,7 +32,7 @@ export class SurveyGroupService {
createdAt: -1,
},
});
const allList = await this.SurveyGroup.find({
const allList = await this.surveyGroupRepository.find({
where: { ownerId: userId },
select: ['_id', 'name'],
});
Expand All @@ -42,15 +43,23 @@ export class SurveyGroupService {
};
}

async findOne(id: string) {
return this.surveyGroupRepository.findOne({
where: {
_id: new ObjectId(id),
},
});
}

update(id: string, updatedFields: Partial<SurveyGroup>) {
updatedFields.updatedAt = new Date();
return this.SurveyGroup.update(id, updatedFields);
return this.surveyGroupRepository.update(id, updatedFields);
}

async remove(id: string) {
const query = { groupId: id };
const update = { $set: { groupId: null } };
await this.surveyMetaRepository.updateMany(query, update);
return this.SurveyGroup.delete(id);
return this.surveyGroupRepository.delete(id);
}
}
Loading

0 comments on commit 4a6dbf9

Please sign in to comment.