Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…main-back into feat/#55/admin-login-api-feat
  • Loading branch information
gwgw123 committed Jan 5, 2025
2 parents 520fc9e + 3e447a6 commit af210cc
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 25 deletions.
2 changes: 0 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { SectionsModule } from './sections/sections.module';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from './auth/auth.module';
import { AppController } from './app.controller';
import { PartProgressModule } from './part-progress/part-progress.module';

@Module({
imports: [
Expand All @@ -23,7 +22,6 @@ import { PartProgressModule } from './part-progress/part-progress.module';
isGlobal: true,
}),
AuthModule,
PartProgressModule,
],
controllers: [AppController],
providers: [AppService],
Expand Down
4 changes: 4 additions & 0 deletions src/part-progress/dto/create-part-progress.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ export class CreatePartProgressDto {
})
@IsEnum(PartStatusValues, { message: 'bad status value' })
readonly status: PartStatus;

constructor(status: PartStatus) {
this.status = status;
}
}
9 changes: 2 additions & 7 deletions src/part-progress/part-progress.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@ import { forwardRef, Module } from '@nestjs/common';
import { PartProgressService } from './part-progress.service';
import { PartProgressController } from './part-progress.controller';
import { PartProgressRepository } from './part-progress.repository';
import { SectionsModule } from 'src/sections/sections.module';
import { PartsModule } from 'src/parts/parts.module';
import { QuizzesModule } from 'src/quizzes/quizzes.module';

@Module({
imports: [
forwardRef(() => SectionsModule),
forwardRef(() => PartsModule),
forwardRef(() => QuizzesModule),
],
imports: [forwardRef(() => PartsModule)],
controllers: [PartProgressController],
providers: [PartProgressService, PartProgressRepository],
exports: [PartProgressService],
})
export class PartProgressModule {}
6 changes: 5 additions & 1 deletion src/part-progress/part-progress.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ export class PartProgressService {
private readonly partsService: PartsService,
private readonly partProgressRepository: PartProgressRepository,
) {}
// 추후 수정사항
/**
* @todo 추후에 유저서비스에서 연결하는 코드로 변경하기
* @param id
* @returns
*/
private async findUserById(id: number) {
const user = await this.prisma.user.findUnique({
where: {
Expand Down
4 changes: 2 additions & 2 deletions src/parts/parts.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class PartsController {
await this.partsService.create(createPartDto);
}

//@ApiParts.updateAll()
@ApiParts.updateAll()
@Patch(':id')
@HttpCode(204)
async updateAll(
Expand All @@ -45,7 +45,7 @@ export class PartsController {
await this.partsService.updateAll(id, body);
}

//@ApiParts.updateOrder()
@ApiParts.updateOrder()
@Patch(':id/order')
@HttpCode(204)
async updateOrder(
Expand Down
9 changes: 7 additions & 2 deletions src/parts/parts.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ import { PartsController } from './parts.controller';
import { PartsRepository } from './parts.repository';
import { QuizzesModule } from 'src/quizzes/quizzes.module';
import { SectionsModule } from 'src/sections/sections.module';
import { PartProgressModule } from 'src/part-progress/part-progress.module';

@Module({
imports: [QuizzesModule, forwardRef(() => SectionsModule)],
imports: [
forwardRef(() => SectionsModule),
QuizzesModule,
PartProgressModule,
],
controllers: [PartsController],
providers: [PartsService, PartsRepository],
exports: [PartsService, PartsRepository, QuizzesModule],
exports: [PartsService, PartsRepository, QuizzesModule, PartProgressModule],
})
export class PartsModule {}
22 changes: 19 additions & 3 deletions src/parts/parts.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { PrismaService } from 'src/prisma/prisma.service';
import { CreatePartDto } from './dto/create-part.dto';
import { Injectable } from '@nestjs/common';
import { Part } from './entities/part.entity';
import { PartStatus } from 'src/part-progress/entities/part-progress.entity';

@Injectable()
export class PartsRepository {
Expand Down Expand Up @@ -38,17 +39,32 @@ export class PartsRepository {
});
}

async findPartMaxOrderBySectionId(sectionId: number): Promise<number> {
/**
*
* @param sectionId - 섹션 아이디 별 파트 개수를 검색
* @returns order를 리턴합니다. 파트가 하나도 없으면 0을 리턴
*/
async aggregateBySectionId(sectionId: number): Promise<number> {
const result = await this.prisma.part.aggregate({
where: { sectionId },
_max: { order: true },
});
return result._max.order ?? 0;
}

async createPartById(data): Promise<Part> {
async createPartWithPartProgress(
body: CreatePartDto,
order: number,
defaultPartProgress: { userId: number; status: PartStatus }[],
): Promise<Part> {
return this.prisma.part.create({
data,
data: {
...body,
order,
PartProgress: {
create: defaultPartProgress,
},
},
});
}

Expand Down
52 changes: 45 additions & 7 deletions src/parts/parts.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ import { QuizzesRepository } from 'src/quizzes/quizzes.repository';
import { Part } from './entities/part.entity';
import { UpdatePartOrderDto } from './dto/update-part-order.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import {
PartStatus,
PartStatusValues,
} from 'src/part-progress/entities/part-progress.entity';

@Injectable()
export class PartsService {
Expand Down Expand Up @@ -67,6 +71,30 @@ export class PartsService {
);
}

/**
* 기본적으로 파트 생성시 모든 유저에게 생성된 파트의 진행도를 넣어 줍니다.
* 지금은 매우 적은 유저가 있을꺼라 생각해서 그냥 다 불러오는데
* 언젠가 수많은 유저가 생성되면 해당로직을 고쳐야합니다.
*/
private async createDefaultPartProgress(order: number) {
const users = await this.prisma.user.findMany();

return users.map((user) => {
let defaultStatus: PartStatus;

if (order === 1) {
defaultStatus = PartStatusValues.STARTED;
} else {
defaultStatus = PartStatusValues.LOCKED;
}

return {
userId: user.id,
status: defaultStatus,
};
});
}

async findOne(id: number): Promise<Part> {
const part = await this.partsRepository.findOnePartById(id);

Expand All @@ -92,11 +120,21 @@ export class PartsService {
throw new ConflictException('part의 이름은 유니크 해야합니다.');
}

const maxOrder =
await this.partsRepository.findPartMaxOrderBySectionId(sectionId);
// 관련 섹션의 순서를 찾아보기
const maxOrder = await this.partsRepository.aggregateBySectionId(sectionId);

// 새로운 순서
const newOrder = maxOrder + 1;

return this.partsRepository.createPartById({ ...body, order: newOrder });
// 파트 순서를 보고 모든유저에게 디폴트 진행도 값을 설정
const defaultPartProgress = await this.createDefaultPartProgress(newOrder);

// 각 값들로 트랜젝션 돌리기
return this.partsRepository.createPartWithPartProgress(
body,
newOrder,
defaultPartProgress,
);
}

async updateAll(id: number, body: CreatePartDto): Promise<Part> {
Expand All @@ -112,11 +150,11 @@ export class PartsService {
return part;
}

// 섹션 순서 재배치를 위한 처리
const updatedSectionIds = await this.reorderPartIds(part, body.order);
// 파트 순서 재배치를 위한 처리
const updatedPartIds = await this.reorderPartIds(part, body.order);

// 데이터베이스의 섹션 순서를 업데이트
await this.updatePartOrders(updatedSectionIds);
// 데이터베이스의 파트 순서를 업데이트
await this.updatePartOrders(updatedPartIds);

// 변경된 섹션 반환
return this.partsRepository.findOnePartById(id);
Expand Down
35 changes: 34 additions & 1 deletion src/users/services/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,34 @@ import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { ResponseUserDto } from '../dtos/response-user.dto';
import { UpdateUserDto } from '../dtos/update-user.dto';
import {
PartStatus,
PartStatusValues,
} from 'src/part-progress/entities/part-progress.entity';

@Injectable()
export class UsersService {
constructor(private readonly prisma: PrismaService) {}

private async createDefaultPartProgress() {
const parts = await this.prisma.part.findMany();

return parts.map((part) => {
let defaultStatus: PartStatus;

if (part.order === 1) {
defaultStatus = PartStatusValues.STARTED;
} else {
defaultStatus = PartStatusValues.LOCKED;
}

return {
partId: part.id,
status: defaultStatus,
};
});
}

getAllUsers(): Promise<ResponseUserDto[]> {
return this.prisma.user.findMany();
}
Expand All @@ -16,8 +39,18 @@ export class UsersService {
providerId: string,
name: string,
): Promise<ResponseUserDto> {
// 유저 생성시 디폴트 파트 진행도를 생성
const defaulPartProgress = await this.createDefaultPartProgress();

const userResponse = await this.prisma.user.create({
data: { provider, providerId, name },
data: {
provider,
providerId,
name,
partProgress: {
create: defaulPartProgress,
},
},
});

if (!userResponse) {
Expand Down

0 comments on commit af210cc

Please sign in to comment.