Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

그룹 카테고리 순서를 변경한다. #618

Merged
merged 2 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions BE/src/category/controller/category.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ export class CategoryController {

@ApiBearerAuth('accessToken')
@ApiOperation({
summary: '카테고리 순서 변경 API',
summary: '카테고리 삭제 API',
description:
'변경될 카테고리 순서로 카테고리 아이디를 배열의 형태로 요청한다.',
'카테고리를 삭제한다.',
})
@Delete('/:categoryId')
@UseGuards(AccessTokenGuard)
Expand Down
104 changes: 104 additions & 0 deletions BE/src/group/category/application/group-category.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { GroupCategoryFixture } from '../../../../test/group/category/group-cate
import { GroupAchievementTestModule } from '../../../../test/group/achievement/group-achievement-test.module';
import { GroupAchievementFixture } from '../../../../test/group/achievement/group-achievement-fixture';
import { UnauthorizedApproachGroupCategoryException } from '../exception/unauthorized-approach-group-category.exception';
import { CategoryRelocateRequest } from '../../../category/dto/category-relocate.request';
import { InvalidCategoryRelocateException } from '../../../category/exception/Invalid-Category-Relocate.exception';

describe('GroupCategoryService test', () => {
let groupCategoryService: GroupCategoryService;
Expand Down Expand Up @@ -698,4 +700,106 @@ describe('GroupCategoryService test', () => {
});
});
});

describe('relocateCategory는 카테고리 순서를 재배열할 수 있다.', () => {
it('카테고리 순서를 변경한다.', async () => {
await transactionTest(dataSource, async () => {
// given
const leader = await usersFixture.getUser('ABC');

const group = await groupFixture.createGroups(leader);

const groupCategory1 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리1',
);
const groupCategory2 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리2',
);
const groupCategory3 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리3',
);
const groupCategory4 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리4',
);

const categoryRelocateRequest = new CategoryRelocateRequest();
categoryRelocateRequest.order = [
groupCategory4.id,
groupCategory3.id,
groupCategory1.id,
groupCategory2.id,
];

// when
await groupCategoryService.relocateCategory(
leader,
group.id,
categoryRelocateRequest,
);
const categories = await groupCategoryService.retrieveCategoryMetadata(
leader,
group.id,
);

// then
expect(categories.length).toBe(5);
expect(categories[0].categoryId).toBe(-1);
expect(categories[1].categoryId).toBe(groupCategory4.id);
expect(categories[2].categoryId).toBe(groupCategory3.id);
expect(categories[3].categoryId).toBe(groupCategory1.id);
expect(categories[4].categoryId).toBe(groupCategory2.id);
});
});

it('모든 카테고리를 요청하지 않으면 에러를 던진다.', async () => {
await transactionTest(dataSource, async () => {
// given
const leader = await usersFixture.getUser('ABC');

const group = await groupFixture.createGroups(leader);

const groupCategory1 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리1',
);
const groupCategory2 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리2',
);
const groupCategory3 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리3',
);
const groupCategory4 = await groupCategoryFixture.createCategory(
leader,
group,
'카테고리4',
);

const categoryRelocateRequest = new CategoryRelocateRequest();
categoryRelocateRequest.order = [groupCategory4.id, groupCategory3.id];

// when
// then
await expect(
groupCategoryService.relocateCategory(
leader,
group.id,
categoryRelocateRequest,
),
).rejects.toThrow(InvalidCategoryRelocateException);
});
});
});
});
26 changes: 26 additions & 0 deletions BE/src/group/category/application/group-category.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { GroupRepository } from '../../group/entities/group.repository';
import { UnauthorizedGroupCategoryException } from '../exception/unauthorized-group-category.exception';
import { GroupCategory } from '../domain/group.category';
import { UnauthorizedApproachGroupCategoryException } from '../exception/unauthorized-approach-group-category.exception';
import { GroupCategoryRelocateRequest } from '../dto/group-category-relocate';
import { InvalidCategoryRelocateException } from '../../../category/exception/Invalid-Category-Relocate.exception';

@Injectable()
export class GroupCategoryService {
Expand All @@ -23,6 +25,7 @@ export class GroupCategoryService {
): Promise<GroupCategory> {
const group = await this.getGroupByLeader(user, groupId);
const groupCategory = groupCtgCreate.toModel(user, group);
await this.groupRepository.saveGroup(group);
return this.groupCategoryRepository.saveGroupCategory(groupCategory);
}

Expand All @@ -47,6 +50,29 @@ export class GroupCategoryService {
return categoryMetaData;
}

@Transactional()
async relocateCategory(
user: User,
groupId: number,
categoryRelocateRequest: GroupCategoryRelocateRequest,
) {
const group = await this.getGroup(user, groupId);
if (group.categoryCount != categoryRelocateRequest.getCategoryCount())
throw new InvalidCategoryRelocateException();

const groupCategories =
await this.groupCategoryRepository.findAllByIdAndGroup(
groupId,
categoryRelocateRequest.order,
);

for (let index = 0; index < groupCategories.length; index++) {
const category = groupCategories[index];
category.seq = index + 1;
await this.groupCategoryRepository.saveGroupCategory(category);
}
}

private async getGroupByLeader(user: User, groupId: number) {
const group = await this.groupRepository.findGroupByIdAndLeaderUser(
user,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { AuthFixture } from '../../../../test/auth/auth-fixture';
import { anyOfClass, instance, mock, when } from 'ts-mockito';
import { anyNumber, anyOfClass, instance, mock, when } from 'ts-mockito';
import { Test, TestingModule } from '@nestjs/testing';
import { AppModule } from '../../../app.module';
import { AuthTestModule } from '../../../../test/auth/auth-test.module';
Expand All @@ -16,6 +16,8 @@ import { GroupCategoryFixture } from '../../../../test/group/category/group-cate
import { UnauthorizedGroupCategoryException } from '../exception/unauthorized-group-category.exception';
import { GroupCategoryMetadata } from '../dto/group-category-metadata';
import { UnauthorizedApproachGroupCategoryException } from '../exception/unauthorized-approach-group-category.exception';
import { InvalidCategoryRelocateException } from '../../../category/exception/Invalid-Category-Relocate.exception';
import { GroupCategoryRelocateRequest } from '../dto/group-category-relocate';

describe('GroupCategoryController Test', () => {
let app: INestApplication;
Expand Down Expand Up @@ -519,4 +521,75 @@ describe('GroupCategoryController Test', () => {
});
});
});

describe('카테고리의 순서를 변경할 수 있다.', () => {
it('카테고리의 순서를 변경할 수 있다.', async () => {
// given
const { accessToken } = await authFixture.getAuthenticatedUser('ABC');

when(
mockGroupCategoryService.relocateCategory(
anyOfClass(User),
anyNumber(),
anyOfClass(GroupCategoryRelocateRequest),
),
).thenResolve(undefined);

// when
// then
return request(app.getHttpServer())
.put(`/api/v1/groups/1/categories`)
.set('Authorization', `Bearer ${accessToken}`)
.send({ order: [1, 2, 3] })
.expect(204);
});

it('카테고리의 개수가 일치하지 않으면 400을 반환한다.', async () => {
// given
const { accessToken } = await authFixture.getAuthenticatedUser('ABC');

when(
mockGroupCategoryService.relocateCategory(
anyOfClass(User),
anyNumber(),
anyOfClass(GroupCategoryRelocateRequest),
),
).thenThrow(new InvalidCategoryRelocateException());

// when
// then
return request(app.getHttpServer())
.put(`/api/v1/groups/1/categories`)
.set('Authorization', `Bearer ${accessToken}`)
.send({ order: [1, 2, 3] })
.expect(400)
.expect((res: request.Response) => {
expect(res.body.success).toBe(false);
expect(res.body.message).toBe(
'잘못된 카테고리 순서 변경 요청입니다.',
);
});
});

it('카테고리의 순서가 배열의 형태가 아니면 400을 반환한다.', async () => {
// given
const { accessToken } = await authFixture.getAuthenticatedUser('ABC');

when(
mockGroupCategoryService.relocateCategory(
anyOfClass(User),
anyNumber(),
anyOfClass(GroupCategoryRelocateRequest),
),
).thenResolve(undefined);

// when
// then
return request(app.getHttpServer())
.put(`/api/v1/categories`)
.set('Authorization', `Bearer ${accessToken}`)
.send({ order: 1 })
.expect(400);
});
});
});
31 changes: 30 additions & 1 deletion BE/src/group/category/controller/group-category.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common';
import {
Body,
Controller,
Get,
HttpCode,
HttpStatus,
Param,
Post,
Put,
UseGuards,
} from '@nestjs/common';
import { GroupCategoryService } from '../application/group-category.service';
import { AccessTokenGuard } from '../../../auth/guard/access-token.guard';
import { AuthenticatedUser } from '../../../auth/decorator/athenticated-user.decorator';
Expand All @@ -15,6 +25,8 @@ import {
ApiOperation,
ApiTags,
} from '@nestjs/swagger';
import { CategoryRelocateRequest } from '../../../category/dto/category-relocate.request';
import { GroupCategoryRelocateRequest } from "../dto/group-category-relocate";

@ApiTags('그룹 카테고리 API')
@Controller('/api/v1/groups/:groupId/categories')
Expand Down Expand Up @@ -91,4 +103,21 @@ export class GroupCategoryController {
);
return ApiData.success(new GroupCategoryListElementResponse(groupCategory));
}

@ApiBearerAuth('accessToken')
@ApiOperation({
summary: '그룹 카테고리 순서 변경 API',
description:
'변경될 그룹의 카테고리 순서로 카테고리 아이디를 배열의 형태로 요청한다.',
})
@Put()
@UseGuards(AccessTokenGuard)
@HttpCode(HttpStatus.NO_CONTENT)
async relocateCategory(
@Body() categoryRelocateRequest: GroupCategoryRelocateRequest,
@Param('groupId', ParseIntPipe) groupId: number,
@AuthenticatedUser() user: User,
) {
return this.groupCategoryService.relocateCategory(user, groupId, categoryRelocateRequest);
}
}
4 changes: 3 additions & 1 deletion BE/src/group/category/domain/group.category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ export class GroupCategory {
user: User;
group: Group;
name: string;
seq: number;

constructor(user: User, group: Group, name: string) {
constructor(user: User, group: Group, name: string, seq: number) {
this.user = user;
this.group = group;
this.name = name;
this.seq = seq;
}
}
5 changes: 3 additions & 2 deletions BE/src/group/category/dto/group-category-create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { IsNotEmptyString } from '../../../config/config/validation-decorator';
import { ApiProperty } from '@nestjs/swagger';
import { GroupCategory } from '../domain/group.category';
import { User } from '../../../users/domain/user.domain';
import { Group } from '../../../group/group/domain/group.domain';
import { Group } from '../../group/domain/group.domain';

export class GroupCategoryCreate {
@IsNotEmptyString({ message: '잘못된 카테고리 이름입니다.' })
Expand All @@ -14,6 +14,7 @@ export class GroupCategoryCreate {
}

toModel(user: User, group: Group): GroupCategory {
return new GroupCategory(user, group, this.name);
++group.categoryCount;
return new GroupCategory(user, group, this.name, ++group.categorySequence);
}
}
16 changes: 16 additions & 0 deletions BE/src/group/category/dto/group-category-relocate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { IsArray } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class GroupCategoryRelocateRequest {
@IsArray({
message: '요청 형식이 잘 못 되었습니다.',
})
@ApiProperty({
description: '변경할 카테고리 아이디의 순서',
})
order: number[];

getCategoryCount() {
return this.order.length;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ describe('GroupCategoryEntity Test', () => {

it('user와 group이 없는 경우에도 변환이 가능하다.', () => {
// given
const groupCategory = new GroupCategory(null, null, '#1');
const groupCategory = new GroupCategory(null, null, '#1',0);

// when
const groupCategoryEntity = GroupCategoryEntity.from(groupCategory);
Expand Down
5 changes: 5 additions & 0 deletions BE/src/group/category/entities/group-category.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ export class GroupCategoryEntity extends BaseTimeEntity {
@Column({ name: 'name' })
name: string;

@Column()
seq: number;

@OneToMany(
() => GroupAchievementEntity,
(achievements) => achievements.groupCategory,
Expand All @@ -40,6 +43,7 @@ export class GroupCategoryEntity extends BaseTimeEntity {
this.user?.toModel(),
this.group?.toModel(),
this.name,
this.seq,
);
group.id = this.id;

Expand All @@ -54,6 +58,7 @@ export class GroupCategoryEntity extends BaseTimeEntity {
groupCategoryEntity.user = UserEntity.from(groupCategory?.user);
groupCategoryEntity.group = GroupEntity.from(groupCategory?.group);
groupCategoryEntity.name = groupCategory.name;
groupCategoryEntity.seq = groupCategory.seq;
return groupCategoryEntity;
}
}
Loading