260812_01_ENH: 배정·진행 현황 개선 및 예약/이벤트 이력 기능 추가

- 프로젝트별 외주사·필드워커 배정 현황 API 추가
- 진행 현황을 리스트 배정 기준으로 변경 및 미배정 집계 추가
- 마지막 이벤트 일자 필터·정렬 추가
- 예약 알림·기간 조회·확인 API 추가
- 이벤트 이력 단건 삭제 기능 추가
- 일반 리스트 헤더 ID를 101부터 생성
- 비밀번호 검증 규칙 완화
This commit is contained in:
2026-08-12 08:39:36 +09:00
parent d35c79217b
commit de7c09ac33
20 changed files with 1252 additions and 69 deletions

View File

@@ -2,6 +2,8 @@ package com.kri.contact.server.controller;
import com.kri.common.feature.datetime.DateTimeUtil;
import com.kri.common.feature.web.RequestUserContext;
import com.kri.contact.server.dto.assign.ProjectCompanyAssignSummaryDto;
import com.kri.contact.server.dto.assign.ProjectFieldworkAssignSummaryDto;
import com.kri.contact.server.dto.list.ListAssignRequestDto;
import com.kri.contact.server.dto.list.ListAssignResetRequestDto;
import com.kri.contact.server.service.AssignService;
@@ -18,6 +20,7 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@@ -41,6 +44,32 @@ public class AssignController {
return assignService.getPrjctCmpnAssign(prjctIdx);
}
@Operation(summary = "프로젝트 외주사별 리스트 배정 현황 조회")
@GetMapping("/prjct-cmpn-summary/{prjctIdx}")
public ProjectCompanyAssignSummaryDto getProjectCompanyAssignSummary(
@PathVariable Long prjctIdx,
RequestUserContext ctx
) {
return assignService.getProjectCompanyAssignSummary(prjctIdx, ctx.getUserRole());
}
@Operation(summary = "프로젝트 필드워커별 리스트 배정 현황 조회")
@GetMapping("/prjct-fieldwork-summary/{prjctIdx}")
public ProjectFieldworkAssignSummaryDto getProjectFieldworkAssignSummary(
@PathVariable Long prjctIdx,
@RequestParam Short assignType,
@RequestParam(required = false) List<String> cmpnIds,
RequestUserContext ctx
) {
return assignService.getProjectFieldworkAssignSummary(
prjctIdx,
assignType,
cmpnIds,
ctx.getUserCmpn(),
ctx.getUserRole()
);
}
@Operation(summary = "프로젝트 fieldwork 배정")
@PutMapping("/prjct-fieldwork/{prjctIdx}")
public void upsertPrjctFieldworkAssign(

View File

@@ -23,6 +23,7 @@ import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@@ -108,6 +109,22 @@ public class ListHistoryController {
);
}
@Operation(description = "리스트 이벤트 이력 단건 삭제")
@DeleteMapping("/event/{listEventHistIdx}")
public ResponseEntity<Void> deleteEventHistory(
@PathVariable Long listEventHistIdx,
RequestUserContext ctx
) {
final LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
listUpdateService.deleteEventHistory(
listEventHistIdx,
ctx.getUserId(),
ctx.getUserRole(),
now
);
return ResponseEntity.noContent().build();
}
private String resolveRegUser(ListEventHistFromSurveyDto request, RequestUserContext ctx) {
if (ctx.getUserId() != null) {
return ctx.getUserId();

View File

@@ -8,14 +8,18 @@ import com.kri.contact.server.service.ReserveService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@@ -36,6 +40,26 @@ public class ReserveController {
return reserveService.reserve(request, ctx.getUserId(), now);
}
@Operation(summary = "Find reserve notifications by user")
@GetMapping("/user/{userId}")
public List<ListReserveDto> findNotifications(
@PathVariable String userId,
@RequestParam(defaultValue = "false") boolean requestPast
) {
LocalDateTime now = DateTimeUtil.nowKstLocalDateTime();
return reserveService.findNotifications(userId, requestPast, now);
}
@Operation(summary = "Find reserves by user and date range")
@GetMapping("/user/{userId}/search")
public List<ListReserveDto> findByUserAndDateRange(
@PathVariable String userId,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDt,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDt
) {
return reserveService.findByUserAndDateRange(userId, fromDt, toDt);
}
@Operation(summary = "Find reserves by user")
@GetMapping("/{prjctIdx}/user/{userId}")
public List<ListReserveDto> findByUser(
@@ -53,4 +77,13 @@ public class ReserveController {
) {
return reserveService.findBySid(prjctIdx, sid);
}
@Operation(summary = "Confirm reserve notification")
@PatchMapping("/confirm/{listResveIdx}")
public void confirm(
@PathVariable Long listResveIdx,
RequestUserContext ctx
) {
reserveService.confirm(listResveIdx, ctx.getUserId());
}
}

View File

@@ -0,0 +1,15 @@
package com.kri.contact.server.dto.assign;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
@Schema(description = "외주사별 리스트 배정 현황")
public class CompanyAssignSummaryItemDto {
private String cmpnId;
private String cmpnAlias;
private long assignedCount;
}

View File

@@ -0,0 +1,16 @@
package com.kri.contact.server.dto.assign;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
@Schema(description = "필드워커별 리스트 배정 현황")
public class FieldworkAssignSummaryItemDto {
private String userId;
private String userName;
private String userCmpn;
private long assignedCount;
}

View File

@@ -0,0 +1,16 @@
package com.kri.contact.server.dto.assign;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
@Schema(description = "프로젝트 외주사 리스트 배정 요약")
public class ProjectCompanyAssignSummaryDto {
private long totalCount;
private long unassignedCount;
private List<CompanyAssignSummaryItemDto> assignees;
}

View File

@@ -0,0 +1,16 @@
package com.kri.contact.server.dto.assign;
import io.swagger.v3.oas.annotations.media.Schema;
import java.util.List;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
@Schema(description = "프로젝트 필드워커 리스트 배정 요약")
public class ProjectFieldworkAssignSummaryDto {
private long totalCount;
private long unassignedCount;
private List<FieldworkAssignSummaryItemDto> assignees;
}

View File

@@ -0,0 +1,37 @@
package com.kri.contact.server.dto.list;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.kri.contact.server.common.enums.ResultCodeType;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import java.time.LocalDateTime;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@Schema(description = "마지막 이벤트 일자 필터 조건")
public class LastEventDateRangeDto {
@NotNull
@Schema(description = "결과 코드 타입")
private ResultCodeType resultCodeType;
@Schema(description = "프로젝트 설문 고유번호. SURVEY 타입인 경우 필수")
private Long prjctSurveyIdx;
@Schema(description = "시작 일시")
private LocalDateTime startDate;
@Schema(description = "종료 일시")
private LocalDateTime endDate;
@JsonIgnore
@AssertTrue(message = "SURVEY 타입은 prjctSurveyIdx가 필요합니다.")
public boolean isSurveyTargetValid() {
return resultCodeType != ResultCodeType.SURVEY || prjctSurveyIdx != null;
}
}

View File

@@ -47,6 +47,9 @@ public class ListFilterDto {
@Schema(description = "List 결과값 필터 key: ResultCodeType code, value: result code list")
private Map<ResultCodeType, Set<Integer>> resultCodeMap;
@Schema(description = "마지막 이벤트 일자 필터 조건")
private List<@Valid LastEventDateRangeDto> lastEventDateRange;
@Schema(description = "설문별 결과 필터 조건")
private List<@Valid ListSurveyResultFilterConditionDto> surveyResultConditions;

View File

@@ -16,6 +16,8 @@ public class ListReserveDto {
private Long listResveIdx;
@Schema(description = "prjctIdx")
private Long prjctIdx;
@Schema(description = "프로젝트명")
private String prjctName;
@Schema(description = "sid")
private String sid;
@Schema(description = "memo")
@@ -32,9 +34,14 @@ public class ListReserveDto {
private LocalDateTime regDt;
public static ListReserveDto from(TListResveEntity entity) {
return from(entity, null);
}
public static ListReserveDto from(TListResveEntity entity, String prjctName) {
return ListReserveDto.builder()
.listResveIdx(entity.getListResveIdx())
.prjctIdx(entity.getPrjctIdx())
.prjctName(prjctName)
.sid(entity.getSid())
.memo(entity.getMemo())
.cnfirm(entity.getCnfirm())

View File

@@ -0,0 +1,239 @@
package com.kri.contact.server.persistence.query;
import com.kri.contact.server.persistence.entity.QTCmpnEntity;
import com.kri.contact.server.persistence.entity.QTListAssignCmpnEntity;
import com.kri.contact.server.persistence.entity.QTListAssignUserEntity;
import com.kri.contact.server.persistence.entity.QTListEntity;
import com.kri.contact.server.persistence.entity.QTPrjctAssignCmpnEntity;
import com.kri.contact.server.persistence.entity.QTPrjctAssignUserEntity;
import com.kri.contact.server.persistence.entity.QTUserEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.dsl.CaseBuilder;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.util.Collection;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class AssignSummaryQuerySupport {
private final JPAQueryFactory jpaQueryFactory;
public long countProjectLists(Long prjctIdx) {
QTListEntity list = QTListEntity.tListEntity;
Long count = jpaQueryFactory
.select(list.id.sid.count())
.from(list)
.where(list.id.prjctIdx.eq(prjctIdx))
.fetchOne();
return safeLong(count);
}
public List<CompanyAssignSummaryRow> findCompanyAssignees(Long prjctIdx) {
QTCmpnEntity company = QTCmpnEntity.tCmpnEntity;
QTPrjctAssignCmpnEntity projectAssign = new QTPrjctAssignCmpnEntity("summaryProjectCompany");
QTListAssignCmpnEntity listAssign = new QTListAssignCmpnEntity("summaryListCompany");
QTListEntity list = new QTListEntity("summaryCompanyList");
NumberExpression<Long> assignedCount = list.id.sid.count();
return jpaQueryFactory
.select(company.cmpnId, company.cmpnAlias, assignedCount)
.from(company)
.leftJoin(projectAssign)
.on(
projectAssign.id.prjctIdx.eq(prjctIdx),
projectAssign.id.cmpnId.eq(company.cmpnId)
)
.leftJoin(listAssign)
.on(
listAssign.prjctIdx.eq(prjctIdx),
listAssign.cmpnId.eq(company.cmpnId)
)
.leftJoin(list)
.on(
list.id.prjctIdx.eq(listAssign.prjctIdx),
list.id.sid.eq(listAssign.sid)
)
.where(
projectAssign.id.prjctIdx.isNotNull()
.or(list.id.sid.isNotNull())
)
.groupBy(company.cmpnId, company.cmpnAlias)
.orderBy(company.cmpnId.asc(), company.cmpnAlias.asc())
.fetch()
.stream()
.map(row -> new CompanyAssignSummaryRow(
row.get(company.cmpnId),
row.get(company.cmpnAlias),
safeLong(row.get(assignedCount))
))
.toList();
}
public ScopeCountRow findFieldworkScopeCounts(
Long prjctIdx,
Short assignType,
Collection<Integer> allowedUserRoles,
Collection<String> companyIds,
boolean externalUser
) {
QTListEntity list = QTListEntity.tListEntity;
QTListAssignUserEntity listAssign = new QTListAssignUserEntity("summaryScopeUserAssign");
QTUserEntity assignedUser = new QTUserEntity("summaryScopeAssignedUser");
QTListAssignCmpnEntity companyAssign = new QTListAssignCmpnEntity("summaryScopeCompanyAssign");
boolean companyScoped = companyIds != null && !companyIds.isEmpty();
NumberExpression<Long> totalCount = list.id.sid.count();
NumberExpression<Long> unassignedCount = new CaseBuilder()
.when(assignedUser.userId.isNull())
.then(1L)
.otherwise(0L)
.sumLong();
JPAQuery<Tuple> query = jpaQueryFactory
.select(totalCount, unassignedCount)
.from(list);
if (externalUser) {
query.join(companyAssign).on(
companyAssign.prjctIdx.eq(list.id.prjctIdx),
companyAssign.sid.eq(list.id.sid),
companyAssign.cmpnId.in(companyIds)
);
}
query.leftJoin(listAssign).on(
listAssign.prjctIdx.eq(list.id.prjctIdx),
listAssign.sid.eq(list.id.sid),
listAssign.assignRole.eq(assignType)
);
BooleanBuilder userJoin = new BooleanBuilder()
.and(assignedUser.userId.eq(listAssign.userId))
.and(assignedUser.del.isFalse())
.and(assignedUser.userRole.in(allowedUserRoles));
if (externalUser) {
userJoin.and(assignedUser.userCmpn.in(companyIds));
}
query.leftJoin(assignedUser).on(userJoin);
BooleanBuilder predicate = new BooleanBuilder(list.id.prjctIdx.eq(prjctIdx));
if (!externalUser && companyScoped) {
predicate.and(
assignedUser.userId.isNull()
.or(assignedUser.userCmpn.in(companyIds))
);
}
Tuple row = query.where(predicate).fetchOne();
if (row == null) {
return new ScopeCountRow(0L, 0L);
}
return new ScopeCountRow(
safeLong(row.get(totalCount)),
safeLong(row.get(unassignedCount))
);
}
public List<FieldworkAssignSummaryRow> findFieldworkAssignees(
Long prjctIdx,
Short assignType,
Collection<Integer> allowedUserRoles,
Collection<String> companyIds,
boolean externalUser
) {
QTUserEntity user = QTUserEntity.tUserEntity;
QTPrjctAssignUserEntity projectAssign = new QTPrjctAssignUserEntity("summaryProjectUser");
QTListAssignUserEntity listAssign = new QTListAssignUserEntity("summaryListUser");
QTListEntity list = new QTListEntity("summaryAssignedList");
QTListAssignCmpnEntity companyAssign = new QTListAssignCmpnEntity("summaryAssignedCompany");
boolean companyScoped = companyIds != null && !companyIds.isEmpty();
NumberExpression<Long> assignedCount = externalUser
? companyAssign.listAssignIdx.count()
: list.id.sid.count();
JPAQuery<Tuple> query = jpaQueryFactory
.select(
user.userId,
user.userNm,
user.userCmpn,
assignedCount
)
.from(user)
.leftJoin(projectAssign)
.on(
projectAssign.id.prjctIdx.eq(prjctIdx),
projectAssign.id.userId.eq(user.userId)
)
.leftJoin(listAssign)
.on(
listAssign.prjctIdx.eq(prjctIdx),
listAssign.userId.eq(user.userId),
listAssign.assignRole.eq(assignType)
)
.leftJoin(list)
.on(
list.id.prjctIdx.eq(listAssign.prjctIdx),
list.id.sid.eq(listAssign.sid)
);
if (externalUser) {
query.leftJoin(companyAssign).on(
companyAssign.prjctIdx.eq(list.id.prjctIdx),
companyAssign.sid.eq(list.id.sid),
companyAssign.cmpnId.in(companyIds)
);
}
BooleanBuilder predicate = new BooleanBuilder()
.and(user.del.isFalse())
.and(user.userRole.in(allowedUserRoles));
if (companyScoped) {
predicate.and(user.userCmpn.in(companyIds));
}
predicate.and(
projectAssign.id.prjctIdx.isNotNull()
.or(externalUser
? companyAssign.listAssignIdx.isNotNull()
: list.id.sid.isNotNull())
);
return query
.where(predicate)
.groupBy(user.userId, user.userNm, user.userCmpn)
.orderBy(user.userId.asc(), user.userNm.asc())
.fetch()
.stream()
.map(row -> new FieldworkAssignSummaryRow(
row.get(user.userId),
row.get(user.userNm),
row.get(user.userCmpn),
safeLong(row.get(assignedCount))
))
.toList();
}
private static long safeLong(Long value) {
return value == null ? 0L : value;
}
public record CompanyAssignSummaryRow(
String companyId,
String companyAlias,
long assignedCount
) {}
public record ScopeCountRow(long totalCount, long unassignedCount) {}
public record FieldworkAssignSummaryRow(
String userId,
String userName,
String userCompany,
long assignedCount
) {}
}

View File

@@ -1,16 +1,21 @@
package com.kri.contact.server.persistence.query;
import com.kri.contact.server.persistence.entity.QTListAssignUserEntity;
import com.kri.contact.server.persistence.entity.QTListEntity;
import com.kri.contact.server.persistence.entity.QTListEventHistEntity;
import com.kri.contact.server.persistence.entity.QTListEventLatestEntity;
import com.kri.contact.server.persistence.entity.QTPrjctAssignUserEntity;
import com.kri.contact.server.persistence.entity.QTUserEntity;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.core.types.dsl.StringExpression;
import com.querydsl.core.types.dsl.StringTemplate;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@@ -24,26 +29,117 @@ public class ProgressQuerySupport {
public List<UserProgressRow> findUserProgress(
Long prjctIdx,
Short eventTy,
Short assignRole,
Collection<Integer> allowedUserRoles,
String userId,
String cmpnId,
LocalDateTime startDt,
LocalDateTime endDt
) {
QTListEventHistEntity history = QTListEventHistEntity.tListEventHistEntity;
NumberExpression<Long> count = history.listEventHistIdx.count();
QTUserEntity user = QTUserEntity.tUserEntity;
QTPrjctAssignUserEntity projectAssign = new QTPrjctAssignUserEntity("progressProjectAssign");
QTListAssignUserEntity listAssign = new QTListAssignUserEntity("progressListAssign");
QTListEntity list = new QTListEntity("progressAssignedList");
QTListEventLatestEntity latest = new QTListEventLatestEntity("progressAssignedLatest");
NumberExpression<Integer> resultCode = latest.resultCd.coalesce(0);
NumberExpression<Long> resultCount = list.id.sid.count();
BooleanBuilder latestJoin = new BooleanBuilder()
.and(latest.prjctIdx.eq(list.id.prjctIdx))
.and(latest.sid.eq(list.id.sid))
.and(latest.eventTy.eq(eventTy));
appendDatePredicate(latestJoin, latest.regDt, startDt, endDt);
BooleanBuilder predicate = new BooleanBuilder()
.and(user.del.isFalse())
.and(user.userRole.in(allowedUserRoles))
.and(
projectAssign.id.prjctIdx.isNotNull()
.or(list.id.sid.isNotNull())
);
if (userId != null) {
predicate.and(user.userId.eq(userId));
}
if (cmpnId != null) {
predicate.and(user.userCmpn.eq(cmpnId));
}
return jpaQueryFactory
.select(history.regUser, history.resultCd, count)
.from(history)
.where(basePredicate(history, prjctIdx, eventTy, userId, cmpnId, startDt, endDt))
.groupBy(history.regUser, history.resultCd)
.orderBy(history.regUser.asc(), history.resultCd.asc())
.select(user.userId, resultCode, resultCount)
.from(user)
.leftJoin(projectAssign)
.on(
projectAssign.id.prjctIdx.eq(prjctIdx),
projectAssign.id.userId.eq(user.userId)
)
.leftJoin(listAssign)
.on(
listAssign.prjctIdx.eq(prjctIdx),
listAssign.userId.eq(user.userId),
listAssign.assignRole.eq(assignRole)
)
.leftJoin(list)
.on(
list.id.prjctIdx.eq(listAssign.prjctIdx),
list.id.sid.eq(listAssign.sid)
)
.leftJoin(latest)
.on(latestJoin)
.where(predicate)
.groupBy(user.userId, resultCode)
.orderBy(user.userId.asc(), resultCode.asc())
.fetch()
.stream()
.map(row -> new UserProgressRow(
row.get(history.regUser),
row.get(history.resultCd),
safeLong(row.get(count))
row.get(user.userId),
safeInt(row.get(resultCode)),
safeLong(row.get(resultCount))
))
.toList();
}
public List<UserProgressRow> findUnassignedProgress(
Long prjctIdx,
Short eventTy,
Short assignRole,
LocalDateTime startDt,
LocalDateTime endDt
) {
QTListEntity list = QTListEntity.tListEntity;
QTListAssignUserEntity listAssign = new QTListAssignUserEntity("progressUnassigned");
QTListEventLatestEntity latest = new QTListEventLatestEntity("progressUnassignedLatest");
NumberExpression<Integer> resultCode = latest.resultCd.coalesce(0);
NumberExpression<Long> resultCount = list.id.sid.count();
BooleanBuilder latestJoin = new BooleanBuilder()
.and(latest.prjctIdx.eq(list.id.prjctIdx))
.and(latest.sid.eq(list.id.sid))
.and(latest.eventTy.eq(eventTy));
appendDatePredicate(latestJoin, latest.regDt, startDt, endDt);
return jpaQueryFactory
.select(resultCode, resultCount)
.from(list)
.leftJoin(listAssign)
.on(
listAssign.prjctIdx.eq(list.id.prjctIdx),
listAssign.sid.eq(list.id.sid),
listAssign.assignRole.eq(assignRole)
)
.leftJoin(latest)
.on(latestJoin)
.where(
list.id.prjctIdx.eq(prjctIdx),
listAssign.listAssignIdx.isNull()
)
.groupBy(resultCode)
.orderBy(resultCode.asc())
.fetch()
.stream()
.map(row -> new UserProgressRow(
"UNASSIGNED",
safeInt(row.get(resultCode)),
safeLong(row.get(resultCount))
))
.toList();
}
@@ -51,6 +147,8 @@ public class ProgressQuerySupport {
public List<DateProgressRow> findDateProgress(
Long prjctIdx,
Short eventTy,
Short assignRole,
Collection<Integer> allowedUserRoles,
String userId,
String cmpnId,
LocalDateTime startDt,
@@ -58,24 +156,46 @@ public class ProgressQuerySupport {
) {
QTListEventHistEntity history = QTListEventHistEntity.tListEventHistEntity;
DateExpressions expressions = DateExpressions.from(history);
return fetchDateRows(history, expressions, basePredicate(history, prjctIdx, eventTy, userId, cmpnId, startDt, endDt));
return fetchDateRows(
history,
expressions,
historyPredicate(
history,
prjctIdx,
eventTy,
assignRole,
allowedUserRoles,
userId,
cmpnId,
startDt,
endDt
)
);
}
public List<DateProgressRow> findLastDateProgress(
Long prjctIdx,
Short eventTy,
Short assignRole,
Collection<Integer> allowedUserRoles,
String userId,
String cmpnId,
LocalDateTime startDt,
LocalDateTime endDt
) {
if (userId == null && cmpnId == null && startDt == null && endDt == null) {
return findLastDateProgressFromLatest(prjctIdx, eventTy);
if (startDt == null && endDt == null) {
return findLastDateProgressFromLatest(
prjctIdx,
eventTy,
assignRole,
allowedUserRoles,
userId,
cmpnId
);
}
QTListEventHistEntity history = QTListEventHistEntity.tListEventHistEntity;
QTListEventHistEntity latestHistory = new QTListEventHistEntity("latestHistory");
QTListEventHistEntity latestHistory = new QTListEventHistEntity("progressLatestHistory");
DateExpressions expressions = DateExpressions.from(history);
BooleanBuilder predicate = new BooleanBuilder()
@@ -83,17 +203,47 @@ public class ProgressQuerySupport {
JPAExpressions
.select(latestHistory.listEventHistIdx.max())
.from(latestHistory)
.where(basePredicate(latestHistory, prjctIdx, eventTy, userId, cmpnId, startDt, endDt))
.where(historyPredicate(
latestHistory,
prjctIdx,
eventTy,
assignRole,
allowedUserRoles,
userId,
cmpnId,
startDt,
endDt
))
.groupBy(latestHistory.sid)
));
return fetchDateRows(history, expressions, predicate);
}
private List<DateProgressRow> findLastDateProgressFromLatest(Long prjctIdx, Short eventTy) {
private List<DateProgressRow> findLastDateProgressFromLatest(
Long prjctIdx,
Short eventTy,
Short assignRole,
Collection<Integer> allowedUserRoles,
String userId,
String cmpnId
) {
QTListEventLatestEntity latest = QTListEventLatestEntity.tListEventLatestEntity;
NumberExpression<Long> count = latest.listEventHistIdx.count();
DateExpressions expressions = DateExpressions.from(latest);
BooleanBuilder predicate = new BooleanBuilder()
.and(latest.prjctIdx.eq(prjctIdx))
.and(latest.eventTy.eq(eventTy));
appendAssignmentScope(
predicate,
latest.sid,
prjctIdx,
assignRole,
allowedUserRoles,
userId,
cmpnId,
"progressLatestScope"
);
List<Tuple> rows = jpaQueryFactory
.select(
@@ -104,10 +254,7 @@ public class ProgressQuerySupport {
count
)
.from(latest)
.where(
latest.prjctIdx.eq(prjctIdx),
latest.eventTy.eq(eventTy)
)
.where(predicate)
.groupBy(expressions.contactDate(), latest.resultCd)
.orderBy(expressions.contactDate().asc(), latest.resultCd.asc())
.fetch();
@@ -117,7 +264,7 @@ public class ProgressQuerySupport {
row.get(expressions.contactDate()),
row.get(expressions.startTime()),
row.get(expressions.endTime()),
row.get(latest.resultCd),
safeInt(row.get(latest.resultCd)),
safeLong(row.get(count))
))
.toList();
@@ -149,16 +296,18 @@ public class ProgressQuerySupport {
row.get(expressions.contactDate()),
row.get(expressions.startTime()),
row.get(expressions.endTime()),
row.get(history.resultCd),
safeInt(row.get(history.resultCd)),
safeLong(row.get(count))
))
.toList();
}
private BooleanBuilder basePredicate(
private BooleanBuilder historyPredicate(
QTListEventHistEntity history,
Long prjctIdx,
Short eventTy,
Short assignRole,
Collection<Integer> allowedUserRoles,
String userId,
String cmpnId,
LocalDateTime startDt,
@@ -167,29 +316,72 @@ public class ProgressQuerySupport {
BooleanBuilder predicate = new BooleanBuilder()
.and(history.prjctIdx.eq(prjctIdx))
.and(history.eventTy.eq(eventTy));
appendDatePredicate(predicate, history.regDt, startDt, endDt);
appendAssignmentScope(
predicate,
history.sid,
prjctIdx,
assignRole,
allowedUserRoles,
userId,
cmpnId,
"progressHistoryScope"
);
return predicate;
}
if (userId != null && !userId.isBlank()) {
predicate.and(history.regUser.eq(userId.trim()));
private void appendAssignmentScope(
BooleanBuilder predicate,
StringExpression sid,
Long prjctIdx,
Short assignRole,
Collection<Integer> allowedUserRoles,
String userId,
String cmpnId,
String aliasPrefix
) {
if (userId == null && cmpnId == null) {
return;
}
if (cmpnId != null && !cmpnId.isBlank()) {
QTUserEntity user = new QTUserEntity("progressUser");
predicate.and(JPAExpressions.selectOne()
.from(user)
.where(
user.userId.eq(history.regUser),
user.userCmpn.eq(cmpnId.trim()),
user.del.isFalse()
)
.exists());
QTListAssignUserEntity assign = new QTListAssignUserEntity(aliasPrefix + "Assign");
QTUserEntity user = new QTUserEntity(aliasPrefix + "User");
BooleanBuilder assignmentPredicate = new BooleanBuilder()
.and(assign.prjctIdx.eq(prjctIdx))
.and(assign.sid.eq(sid))
.and(assign.assignRole.eq(assignRole))
.and(user.userId.eq(assign.userId))
.and(user.del.isFalse())
.and(user.userRole.in(allowedUserRoles));
if (userId != null) {
assignmentPredicate.and(user.userId.eq(userId));
}
if (cmpnId != null) {
assignmentPredicate.and(user.userCmpn.eq(cmpnId));
}
predicate.and(JPAExpressions.selectOne()
.from(assign, user)
.where(assignmentPredicate)
.exists());
}
private void appendDatePredicate(
BooleanBuilder predicate,
com.querydsl.core.types.dsl.DateTimeExpression<LocalDateTime> regDt,
LocalDateTime startDt,
LocalDateTime endDt
) {
if (startDt != null) {
predicate.and(history.regDt.goe(startDt));
predicate.and(regDt.goe(startDt));
}
if (endDt != null) {
predicate.and(history.regDt.loe(endDt));
predicate.and(regDt.loe(endDt));
}
}
return predicate;
private static int safeInt(Integer value) {
return value == null ? 0 : value;
}
private static long safeLong(Long value) {

View File

@@ -11,6 +11,7 @@ import com.kri.contact.server.common.enums.ResultCodeType;
import com.kri.contact.server.dto.list.ListAssignFilterConditionDto;
import com.kri.contact.server.dto.list.ListFilterConditionDto;
import com.kri.contact.server.dto.list.ListFilterDto;
import com.kri.contact.server.dto.list.LastEventDateRangeDto;
import com.kri.contact.server.common.enums.ListFilterMatchType;
import com.kri.contact.server.common.enums.ListFilterOperator;
import com.kri.contact.server.dto.list.ListOtherItemFilterConditionDto;
@@ -33,6 +34,7 @@ import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.impl.JPAQueryFactory;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -203,6 +205,12 @@ public class ListQueryRepositoryImpl implements ListQueryRepository {
appendAssignPredicates(predicate, prjctIdx, list, listFilter.getAssignUserMap());
appendAssignConditionPredicates(predicate, prjctIdx, list, listFilter.getAssignConditions());
appendResultCodePredicates(predicate, prjctIdx, list, listFilter.getResultCodeMap());
appendLastEventDateRangePredicates(
predicate,
prjctIdx,
list,
listFilter.getLastEventDateRange()
);
appendSurveyResultPredicates(predicate, prjctIdx, list, listFilter.getSurveyResultConditions());
appendOtherItemPredicates(predicate, prjctIdx, exactMatchHeaderIds, list, listFilter.getOtherItemConditions());
return predicate;
@@ -622,6 +630,59 @@ public class ListQueryRepositoryImpl implements ListQueryRepository {
}
}
private void appendLastEventDateRangePredicates(
BooleanBuilder predicate,
Long prjctIdx,
QTListEntity list,
List<LastEventDateRangeDto> conditions
) {
if (conditions == null || conditions.isEmpty()) {
return;
}
for (int index = 0; index < conditions.size(); index++) {
LastEventDateRangeDto condition = conditions.get(index);
if (condition == null || condition.getResultCodeType() == null) {
continue;
}
LocalDateTime startDate = condition.getStartDate();
LocalDateTime endDate = condition.getEndDate();
if (startDate == null && endDate == null) {
continue;
}
if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
LocalDateTime swapped = startDate;
startDate = endDate;
endDate = swapped;
}
ResultCodeType resultCodeType = condition.getResultCodeType();
QTListEventLatestEntity latest = new QTListEventLatestEntity("latest_event_date_" + index);
BooleanBuilder latestPredicate = new BooleanBuilder()
.and(latest.prjctIdx.eq(prjctIdx))
.and(latest.sid.eq(list.id.sid))
.and(latest.eventTy.eq(resultCodeType.getCode()));
if (resultCodeType == ResultCodeType.SURVEY) {
latestPredicate.and(latest.prjctSurveyIdx.eq(condition.getPrjctSurveyIdx()));
} else {
latestPredicate.and(latest.prjctSurveyIdx.isNull());
}
if (startDate != null) {
latestPredicate.and(latest.regDt.goe(startDate));
}
if (endDate != null) {
latestPredicate.and(latest.regDt.loe(endDate));
}
predicate.and(JPAExpressions.selectOne()
.from(latest)
.where(latestPredicate)
.exists());
}
}
private void appendSurveyResultPredicates(
BooleanBuilder predicate,
Long prjctIdx,
@@ -899,6 +960,16 @@ public class ListQueryRepositoryImpl implements ListQueryRepository {
if (sortBy != null && sortBy.matches("assign-(13|14|15)")) {
return SortTarget.assign(order, Short.valueOf(sortBy.substring("assign-".length())));
}
if ("result-date-contact".equalsIgnoreCase(sortBy)) {
return SortTarget.resultDate(order, ResultCodeType.CONTACT.getCode(), null);
}
if ("result-date-interview".equalsIgnoreCase(sortBy)) {
return SortTarget.resultDate(order, ResultCodeType.INTERVIEW.getCode(), null);
}
Long dateSurveyIdx = parseSurveyResultDateSort(sortBy);
if (dateSurveyIdx != null) {
return SortTarget.resultDate(order, ResultCodeType.SURVEY.getCode(), dateSurveyIdx);
}
if ("result-contact".equalsIgnoreCase(sortBy)) {
return SortTarget.result(order, ResultCodeType.CONTACT.getCode(), null);
}
@@ -972,7 +1043,10 @@ public class ListQueryRepositoryImpl implements ListQueryRepository {
Long prjctIdx,
SortTarget sortTarget
) {
QTListEventLatestEntity latest = new QTListEventLatestEntity("sort_result_" + sortTarget.resultType());
QTListEventLatestEntity latest = new QTListEventLatestEntity(
(sortTarget.resultDate() ? "sort_result_date_" : "sort_result_")
+ sortTarget.resultType()
);
BooleanBuilder on = new BooleanBuilder()
.and(latest.prjctIdx.eq(prjctIdx))
.and(latest.sid.eq(list.id.sid))
@@ -982,9 +1056,12 @@ public class ListQueryRepositoryImpl implements ListQueryRepository {
} else {
on.and(latest.prjctSurveyIdx.eq(sortTarget.prjctSurveyIdx()));
}
query.leftJoin(latest)
.on(on)
.orderBy(toOrderSpecifier(sortTarget.order(), latest.resultCd));
query.leftJoin(latest).on(on);
if (sortTarget.resultDate()) {
query.orderBy(toOrderSpecifier(sortTarget.order(), latest.regDt));
} else {
query.orderBy(toOrderSpecifier(sortTarget.order(), latest.resultCd));
}
}
private OrderSpecifier<?> toOrderSpecifier(Order order, ComparableExpressionBase<?> expression) {
@@ -1014,6 +1091,18 @@ public class ListQueryRepositoryImpl implements ListQueryRepository {
}
}
private Long parseSurveyResultDateSort(String sortBy) {
String prefix = "result-date-survey-";
if (sortBy == null || !sortBy.toLowerCase().startsWith(prefix)) {
return null;
}
try {
return Long.valueOf(sortBy.substring(prefix.length()));
} catch (NumberFormatException e) {
return null;
}
}
private record SortTarget(
Order order,
ComparableExpressionBase<?> basePath,
@@ -1021,26 +1110,31 @@ public class ListQueryRepositoryImpl implements ListQueryRepository {
Integer listHderId,
Short resultType,
Long prjctSurveyIdx,
boolean resultDate,
boolean naturalSid
) {
private static SortTarget sidNatural(Order order) {
return new SortTarget(order, null, null, null, null, null, true);
return new SortTarget(order, null, null, null, null, null, false, true);
}
private static SortTarget base(Order order, ComparableExpressionBase<?> path) {
return new SortTarget(order, path, null, null, null, null, false);
return new SortTarget(order, path, null, null, null, null, false, false);
}
private static SortTarget assign(Order order, Short assignType) {
return new SortTarget(order, null, assignType, null, null, null, false);
return new SortTarget(order, null, assignType, null, null, null, false, false);
}
private static SortTarget item(Order order, Integer listHderId) {
return new SortTarget(order, null, null, listHderId, null, null, false);
return new SortTarget(order, null, null, listHderId, null, null, false, false);
}
private static SortTarget result(Order order, Short resultType, Long prjctSurveyIdx) {
return new SortTarget(order, null, null, null, resultType, prjctSurveyIdx, false);
return new SortTarget(order, null, null, null, resultType, prjctSurveyIdx, false, false);
}
private static SortTarget resultDate(Order order, Short resultType, Long prjctSurveyIdx) {
return new SortTarget(order, null, null, null, resultType, prjctSurveyIdx, true, false);
}
}

View File

@@ -1,18 +1,81 @@
package com.kri.contact.server.persistence.repository;
import com.kri.contact.server.persistence.entity.TListResveEntity;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface ListReserveRepository extends JpaRepository<TListResveEntity, Long> {
List<TListResveEntity> findByPrjctIdxAndResveUserOrderByResveDtAscListResveIdxAsc(
Long prjctIdx,
String resveUser
@Modifying
@Query("""
update TListResveEntity r
set r.cnfirm = true
where r.prjctIdx = :prjctIdx
and r.sid = :sid
and r.resveUser = :resveUser
and r.cnfirm = false
""")
int confirmByProjectSidAndUser(
@Param("prjctIdx") Long prjctIdx,
@Param("sid") String sid,
@Param("resveUser") String resveUser
);
List<TListResveEntity> findByPrjctIdxAndSidOrderByResveDtAscListResveIdxAsc(
Long prjctIdx,
String sid
@Query("""
select r
from TListResveEntity r
where r.prjctIdx = :prjctIdx
and r.resveUser = :resveUser
and r.cnfirm = false
order by r.resveDt asc, r.sid asc
""")
List<TListResveEntity> findUnconfirmedByUser(
@Param("prjctIdx") Long prjctIdx,
@Param("resveUser") String resveUser
);
@Query("""
select r
from TListResveEntity r
where r.prjctIdx = :prjctIdx
and r.sid = :sid
and r.cnfirm = false
order by r.resveDt asc, r.sid asc
""")
List<TListResveEntity> findUnconfirmedBySid(
@Param("prjctIdx") Long prjctIdx,
@Param("sid") String sid
);
@Query("""
select r
from TListResveEntity r
where r.resveUser = :resveUser
and r.cnfirm = false
and r.resveDt between :startDt and :endDt
order by r.resveDt desc, r.prjctIdx desc, r.sid asc
""")
List<TListResveEntity> findNotifications(
@Param("resveUser") String resveUser,
@Param("startDt") LocalDateTime startDt,
@Param("endDt") LocalDateTime endDt
);
@Query("""
select r
from TListResveEntity r
where r.resveUser = :resveUser
and r.cnfirm = false
and r.resveDt between :fromDt and :toDt
order by r.resveDt asc, r.prjctIdx asc, r.sid asc, r.listResveIdx asc
""")
List<TListResveEntity> findByUserAndDateRange(
@Param("resveUser") String resveUser,
@Param("fromDt") LocalDateTime fromDt,
@Param("toDt") LocalDateTime toDt
);
}

View File

@@ -3,6 +3,11 @@ package com.kri.contact.server.service;
import com.kri.common.feature.web.BusinessException;
import com.kri.contact.server.common.consts.ContactConstant;
import com.kri.contact.server.common.enums.ListAssignType;
import com.kri.contact.server.common.enums.ListHeaderTypeAssign;
import com.kri.contact.server.dto.assign.CompanyAssignSummaryItemDto;
import com.kri.contact.server.dto.assign.FieldworkAssignSummaryItemDto;
import com.kri.contact.server.dto.assign.ProjectCompanyAssignSummaryDto;
import com.kri.contact.server.dto.assign.ProjectFieldworkAssignSummaryDto;
import com.kri.contact.server.dto.list.ListAssignRequestDto;
import com.kri.contact.server.dto.list.ListAssignResetRequestDto;
import com.kri.contact.server.dto.list.ListFilterDto;
@@ -12,6 +17,8 @@ import com.kri.contact.server.persistence.entity.TPrjctAssignCmpnEntity;
import com.kri.contact.server.persistence.entity.TPrjctAssignUserEntity;
import com.kri.contact.server.persistence.entity.TUserEntity;
import com.kri.contact.server.persistence.jdbc.ListAssignJdbcSupport;
import com.kri.contact.server.persistence.query.AssignSummaryQuerySupport;
import com.kri.contact.server.persistence.query.AssignSummaryQuerySupport.ScopeCountRow;
import com.kri.contact.server.persistence.repository.ListAssignCmpnRepository;
import com.kri.contact.server.persistence.repository.ListAssignUserRepository;
import com.kri.contact.server.persistence.repository.ListAssignUserRoleMapRepository;
@@ -46,6 +53,97 @@ public class AssignService {
private final ListRepository listRepository;
private final ListHeaderService listHeaderService;
private final UserRepository userRepository;
private final AssignSummaryQuerySupport assignSummaryQuerySupport;
@Transactional(readOnly = true)
public ProjectCompanyAssignSummaryDto getProjectCompanyAssignSummary(
Long prjctIdx,
Integer userRole
) {
if (userRole == null || userRole >= ContactConstant.OUTSOURCE_USER_ROLE) {
throw BusinessException.forbidden(
"PROJECT_COMPANY_ASSIGN_SUMMARY_FORBIDDEN",
"외주사 배정 현황을 조회할 권한이 없습니다."
);
}
long totalCount = assignSummaryQuerySupport.countProjectLists(prjctIdx);
List<CompanyAssignSummaryItemDto> assignees = assignSummaryQuerySupport
.findCompanyAssignees(prjctIdx)
.stream()
.map(row -> CompanyAssignSummaryItemDto.builder()
.cmpnId(row.companyId())
.cmpnAlias(row.companyAlias())
.assignedCount(row.assignedCount())
.build())
.toList();
long assignedCount = assignees.stream()
.mapToLong(CompanyAssignSummaryItemDto::getAssignedCount)
.sum();
validateSummaryCount(totalCount, assignedCount);
return ProjectCompanyAssignSummaryDto.builder()
.totalCount(totalCount)
.unassignedCount(totalCount - assignedCount)
.assignees(assignees)
.build();
}
@Transactional(readOnly = true)
public ProjectFieldworkAssignSummaryDto getProjectFieldworkAssignSummary(
Long prjctIdx,
Short assignType,
Collection<String> requestedCompanyIds,
String userCmpn,
Integer userRole
) {
Short validatedAssignType = requireFieldworkSummaryAssignType(assignType);
Set<Integer> allowedUserRoles = resolveAllowedUserRoles(validatedAssignType);
List<String> companyIds = resolveSummaryCompanyIds(
requestedCompanyIds,
userCmpn,
userRole
);
boolean externalUser = userRole >= ContactConstant.OUTSOURCE_USER_ROLE;
ScopeCountRow scopeCounts = assignSummaryQuerySupport.findFieldworkScopeCounts(
prjctIdx,
validatedAssignType,
allowedUserRoles,
companyIds,
externalUser
);
List<FieldworkAssignSummaryItemDto> assignees = assignSummaryQuerySupport
.findFieldworkAssignees(
prjctIdx,
validatedAssignType,
allowedUserRoles,
companyIds,
externalUser
)
.stream()
.map(row -> FieldworkAssignSummaryItemDto.builder()
.userId(row.userId())
.userName(row.userName())
.userCmpn(row.userCompany())
.assignedCount(row.assignedCount())
.build())
.toList();
long responseAssignedCount = assignees.stream()
.mapToLong(FieldworkAssignSummaryItemDto::getAssignedCount)
.sum();
if (scopeCounts.totalCount() != scopeCounts.unassignedCount() + responseAssignedCount) {
throw BusinessException.internalError("필드워커 배정 현황을 계산할 수 없습니다.");
}
return ProjectFieldworkAssignSummaryDto.builder()
.totalCount(scopeCounts.totalCount())
.unassignedCount(scopeCounts.unassignedCount())
.assignees(assignees)
.build();
}
public List<String> getPrjctFieldworkAssign(Long prjctIdx) {
return projectAssignUserRepository.findAssignUserIdByPrjctIdxAndRoleRange(
@@ -346,6 +444,76 @@ public class AssignService {
listAssignUserRepository.deleteByPrjctIdxAndUserCmpnIn(prjctIdx, removedExternalCmpnIds);
}
private Short requireFieldworkSummaryAssignType(Short assignType) {
if (Objects.equals(assignType, ListHeaderTypeAssign.CONTACT_INTERVIEWER.getCode())
|| Objects.equals(assignType, ListHeaderTypeAssign.FIELD_INTERVIEWER.getCode())) {
return assignType;
}
throw BusinessException.badRequest(
"INVALID_FIELDWORK_ASSIGN_TYPE",
"assignType은 14 또는 15만 허용됩니다."
).with("assignType", assignType);
}
private Set<Integer> resolveAllowedUserRoles(Short assignType) {
Set<String> configuredRoles = findAllowedUserRolesByAssignRole(Set.of(assignType))
.getOrDefault(assignType, Collections.emptySet());
Set<Integer> allowedRoles = configuredRoles.stream()
.map(role -> {
try {
return Integer.valueOf(role);
} catch (NumberFormatException ignored) {
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (allowedRoles.isEmpty()) {
throw BusinessException.internalError("필드워커 배정 역할 설정을 찾을 수 없습니다.");
}
return allowedRoles;
}
private List<String> resolveSummaryCompanyIds(
Collection<String> requestedCompanyIds,
String userCmpn,
Integer userRole
) {
if (userRole == null) {
throw BusinessException.forbidden(
"ASSIGN_COMPANY_SCOPE_FORBIDDEN",
"배정 현황을 조회할 권한이 없습니다."
);
}
if (userRole >= ContactConstant.OUTSOURCE_USER_ROLE) {
if (userCmpn == null || userCmpn.isBlank()) {
throw BusinessException.forbidden(
"ASSIGN_COMPANY_SCOPE_FORBIDDEN",
"사용자의 소속 회사를 확인할 수 없습니다."
);
}
return List.of(userCmpn.trim());
}
if (requestedCompanyIds == null || requestedCompanyIds.isEmpty()) {
return Collections.emptyList();
}
return requestedCompanyIds.stream()
.filter(Objects::nonNull)
.flatMap(value -> List.of(value.split(",")).stream())
.map(String::trim)
.filter(value -> !value.isBlank())
.distinct()
.toList();
}
private void validateSummaryCount(long totalCount, long assignedCount) {
if (assignedCount < 0 || assignedCount > totalCount) {
throw BusinessException.internalError("리스트 배정 현황을 계산할 수 없습니다.");
}
}
private List<String> normalizeAssignIds(List<String> assignIds) {
if (assignIds == null || assignIds.isEmpty()) {
return Collections.emptyList();

View File

@@ -37,6 +37,8 @@ import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor
public class ListHeaderService {
private static final int FIRST_COMMON_HEADER_ID = 101;
private final ListHeaderRepository listHeaderRepository;
private final ListItemRepository listItemRepository;
private final ListContentItemService listContentItemService;
@@ -152,11 +154,12 @@ public class ListHeaderService {
result.add(ListHeaderDto.fromDto(prjctIdx, existing != null ? existing : src));
}
int nextId = existingHeaders.stream()
int maxExistingHeaderId = existingHeaders.stream()
.map(ListHeaderDto::getListHderId)
.filter(Objects::nonNull)
.max(Integer::compareTo)
.orElse(defaultHeaders.size()) + 1;
.orElse(0);
int nextId = Math.max(maxExistingHeaderId + 1, FIRST_COMMON_HEADER_ID);
for (String headerName : excelHeaders) {
if (defaultByName.containsKey(headerName)) {
continue;
@@ -221,7 +224,9 @@ public class ListHeaderService {
deleteHderIdNotIn(prjctIdx, headerIdList);
AtomicInteger maxListHderId = new AtomicInteger(getMaxListHderId(prjctIdx));
AtomicInteger maxListHderId = new AtomicInteger(
Math.max(getMaxListHderId(prjctIdx), FIRST_COMMON_HEADER_ID - 1)
);
headerList.stream()
.filter(h -> h.getListHderId() < 0)

View File

@@ -38,6 +38,7 @@ import com.kri.contact.server.persistence.repository.ProjectSurveyRepository;
import com.kri.contact.server.service.file.ListItemFileService;
import jakarta.persistence.EntityManager;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
@@ -46,6 +47,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -55,6 +57,9 @@ import org.springframework.transaction.annotation.Transactional;
public class ListUpdateService {
private static final String FILE_DELETE = "FILE_DELETE";
private static final String USER_DIRECT_DELETE_PREFIX = "USER_DIRECT_";
private static final DateTimeFormatter USER_DIRECT_DELETE_DATE_FORMAT =
DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
private final ListHeaderRepository listHeaderRepository;
private final ListSearchService listSearchService;
@@ -67,6 +72,7 @@ public class ListUpdateService {
private final ListItemFileService listItemFileService;
private final ResultCodeService resultCodeService;
private final ListCallHistService listCallHistService;
private final ReserveService reserveService;
private final ObjectMapper objectMapper;
private final EntityManager entityManager;
@@ -138,6 +144,52 @@ public class ListUpdateService {
return totalUpdatedCount;
}
@Transactional
public void deleteEventHistory(
Long listEventHistIdx,
String delUser,
Integer userRole,
LocalDateTime delDt
) {
if (userRole == null || userRole >= ContactConstant.OUTSOURCE_USER_ROLE) {
throw BusinessException.forbidden(
"EVENT_HISTORY_DELETE_FORBIDDEN",
"내부 사용자만 이벤트 이력을 삭제할 수 있습니다."
);
}
if (delUser == null || delUser.isBlank()) {
throw BusinessException.forbidden(
"EVENT_HISTORY_DELETE_FORBIDDEN",
"삭제 사용자 정보를 확인할 수 없습니다."
);
}
TListEventHistEntity eventHistory = listEventHistRepository.findById(listEventHistIdx)
.orElseThrow(() -> BusinessException.notFound(
"EVENT_HISTORY_NOT_FOUND",
"이벤트 이력을 찾을 수 없습니다."
).with("listEventHistIdx", listEventHistIdx));
if (!Objects.equals(eventHistory.getEventTy(), ResultCodeType.CONTACT.getCode())
&& !Objects.equals(eventHistory.getEventTy(), ResultCodeType.INTERVIEW.getCode())) {
throw BusinessException.badRequest(
"EVENT_HISTORY_DELETE_NOT_ALLOWED",
"컨택 또는 면접 이벤트 이력만 삭제할 수 있습니다."
)
.with("listEventHistIdx", listEventHistIdx)
.with("eventTy", eventHistory.getEventTy());
}
String directDeleteId = createUserDirectDeleteId(delDt);
try {
setEventHistoryDeleteContext(directDeleteId, delUser, delDt);
listEventHistRepository.delete(eventHistory);
entityManager.flush();
} finally {
clearEventHistoryDeleteContext();
}
}
@Transactional
public void putSurveyHistory(
ListEventHistFromSurveyDto request,
@@ -267,6 +319,14 @@ public class ListUpdateService {
regUser,
regDt
));
if (request.getResultCodeType() == ResultCodeType.CONTACT) {
reserveService.confirmByProjectSidAndUser(
request.getPrjctIdx(),
request.getSid(),
regUser
);
}
}
private void validateResultCode(ListEventHistInsertRequestDto request) {
@@ -539,6 +599,36 @@ public class ListUpdateService {
entityManager.createNativeQuery("SET @skip_delete_backup = NULL").executeUpdate();
}
private String createUserDirectDeleteId(LocalDateTime delDt) {
String date = delDt.format(USER_DIRECT_DELETE_DATE_FORMAT);
String random = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
return USER_DIRECT_DELETE_PREFIX + date + "_" + random;
}
private void setEventHistoryDeleteContext(
String directDeleteId,
String delUser,
LocalDateTime delDt
) {
entityManager.createNativeQuery("SET @skip_delete_backup = NULL").executeUpdate();
entityManager.createNativeQuery("SET @list_reset_log_id = :directDeleteId")
.setParameter("directDeleteId", directDeleteId)
.executeUpdate();
entityManager.createNativeQuery("SET @del_user = :delUser")
.setParameter("delUser", delUser)
.executeUpdate();
entityManager.createNativeQuery("SET @del_dt = :delDt")
.setParameter("delDt", delDt)
.executeUpdate();
}
private void clearEventHistoryDeleteContext() {
entityManager.createNativeQuery("SET @list_reset_log_id = NULL").executeUpdate();
entityManager.createNativeQuery("SET @del_user = NULL").executeUpdate();
entityManager.createNativeQuery("SET @del_dt = NULL").executeUpdate();
entityManager.createNativeQuery("SET @skip_delete_backup = NULL").executeUpdate();
}
private short parseIsUseCode(String value) {
String normalized = defaultString(normalizeBlank(value)).toUpperCase();
return switch (normalized) {

View File

@@ -1,6 +1,7 @@
package com.kri.contact.server.service;
import com.kri.common.feature.web.BusinessException;
import com.kri.contact.server.common.enums.ListHeaderTypeAssign;
import com.kri.contact.server.common.enums.ResultCodeType;
import com.kri.contact.server.dto.progress.ProgressDateResponseDto;
import com.kri.contact.server.dto.progress.ProgressSearchRequestDto;
@@ -13,8 +14,12 @@ import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -22,7 +27,10 @@ import org.springframework.stereotype.Service;
@RequiredArgsConstructor
public class ProgressService {
private static final String UNASSIGNED_USER_ID = "UNASSIGNED";
private final ProgressQuerySupport progressQuerySupport;
private final AssignService assignService;
public List<ProgressUserResponseDto> getUserProgress(
Long prjctIdx,
@@ -31,18 +39,42 @@ public class ProgressService {
) {
validateEventTy(eventTy);
SearchCondition condition = SearchCondition.from(request);
AssignmentScope assignmentScope = resolveAssignmentScope(eventTy);
Map<String, ProgressUserAccumulator> result = new LinkedHashMap<>();
for (UserProgressRow row : progressQuerySupport.findUserProgress(
prjctIdx,
eventTy,
assignmentScope.assignRole(),
assignmentScope.allowedUserRoles(),
condition.userId(),
condition.cmpnId(),
condition.startDt(),
condition.endDt()
)) {
result.computeIfAbsent(row.userId(), ProgressUserAccumulator::new)
.add(row.resultCode(), row.resultCount());
ProgressUserAccumulator accumulator = result.computeIfAbsent(
row.userId(),
ProgressUserAccumulator::new
);
if (row.resultCount() > 0) {
accumulator.add(row.resultCode(), row.resultCount());
}
}
if (condition.userId() == null) {
ProgressUserAccumulator unassigned = new ProgressUserAccumulator(UNASSIGNED_USER_ID);
for (UserProgressRow row : progressQuerySupport.findUnassignedProgress(
prjctIdx,
eventTy,
assignmentScope.assignRole(),
condition.startDt(),
condition.endDt()
)) {
if (row.resultCount() > 0) {
unassigned.add(row.resultCode(), row.resultCount());
}
}
result.put(UNASSIGNED_USER_ID, unassigned);
}
return result.values().stream()
@@ -57,9 +89,12 @@ public class ProgressService {
) {
validateEventTy(eventTy);
SearchCondition condition = SearchCondition.from(request);
AssignmentScope assignmentScope = resolveAssignmentScope(eventTy);
return toDateDtos(progressQuerySupport.findDateProgress(
prjctIdx,
eventTy,
assignmentScope.assignRole(),
assignmentScope.allowedUserRoles(),
condition.userId(),
condition.cmpnId(),
condition.startDt(),
@@ -74,9 +109,12 @@ public class ProgressService {
) {
validateEventTy(eventTy);
SearchCondition condition = SearchCondition.from(request);
AssignmentScope assignmentScope = resolveAssignmentScope(eventTy);
return toDateDtos(progressQuerySupport.findLastDateProgress(
prjctIdx,
eventTy,
assignmentScope.assignRole(),
assignmentScope.allowedUserRoles(),
condition.userId(),
condition.cmpnId(),
condition.startDt(),
@@ -113,6 +151,30 @@ public class ProgressService {
}
}
private AssignmentScope resolveAssignmentScope(Short eventTy) {
Short assignRole = Objects.equals(eventTy, ResultCodeType.CONTACT.getCode())
? ListHeaderTypeAssign.CONTACT_INTERVIEWER.getCode()
: ListHeaderTypeAssign.FIELD_INTERVIEWER.getCode();
Set<Integer> allowedUserRoles = assignService
.findAllowedUserRolesByAssignRole(Set.of(assignRole))
.getOrDefault(assignRole, Set.of())
.stream()
.map(role -> {
try {
return Integer.valueOf(role);
} catch (NumberFormatException ignored) {
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (allowedUserRoles.isEmpty()) {
throw BusinessException.internalError("진행 현황 배정 역할 설정을 찾을 수 없습니다.");
}
return new AssignmentScope(assignRole, allowedUserRoles);
}
private record SearchCondition(
String userId,
String cmpnId,
@@ -132,6 +194,8 @@ public class ProgressService {
}
}
private record AssignmentScope(Short assignRole, Set<Integer> allowedUserRoles) {}
private static String normalizeBlank(String value) {
return value == null || value.isBlank() ? null : value.trim();
}

View File

@@ -7,8 +7,14 @@ import com.kri.contact.server.dto.reserve.ListReserveRequestDto;
import com.kri.contact.server.persistence.entity.TListResveEntity;
import com.kri.contact.server.persistence.repository.ListRepository;
import com.kri.contact.server.persistence.repository.ListReserveRepository;
import com.kri.contact.server.persistence.repository.ProjectRepository;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -17,8 +23,11 @@ import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor
public class ReserveService {
private static final long NOTIFICATION_RANGE_MINUTES = 5L;
private final ListRepository listRepository;
private final ListReserveRepository listReserveRepository;
private final ProjectRepository projectRepository;
@Transactional
public ListReserveDto reserve(ListReserveRequestDto request, String regUser, LocalDateTime regDt) {
@@ -37,22 +46,88 @@ public class ReserveService {
entity.setResveUser(request.getUserId().trim());
entity.setRegUser(regUser == null || regUser.isBlank() ? ContactConstant.SYSTEM_USER_NAME : regUser);
entity.setRegDt(regDt);
return ListReserveDto.from(listReserveRepository.save(entity));
TListResveEntity saved = listReserveRepository.save(entity);
String prjctName = projectRepository.findById(saved.getPrjctIdx())
.map(project -> project.getPrjctNm())
.orElse(null);
return ListReserveDto.from(saved, prjctName);
}
@Transactional(readOnly = true)
public List<ListReserveDto> findByUser(Long prjctIdx, String userId) {
return listReserveRepository.findByPrjctIdxAndResveUserOrderByResveDtAscListResveIdxAsc(prjctIdx, userId)
.stream()
.map(ListReserveDto::from)
.toList();
return toDtosWithProjectNames(listReserveRepository.findUnconfirmedByUser(prjctIdx, userId));
}
@Transactional(readOnly = true)
public List<ListReserveDto> findBySid(Long prjctIdx, String sid) {
return listReserveRepository.findByPrjctIdxAndSidOrderByResveDtAscListResveIdxAsc(prjctIdx, sid)
.stream()
.map(ListReserveDto::from)
return toDtosWithProjectNames(listReserveRepository.findUnconfirmedBySid(prjctIdx, sid));
}
@Transactional(readOnly = true)
public List<ListReserveDto> findNotifications(
String userId,
boolean requestPast,
LocalDateTime now
) {
LocalDateTime startDt = requestPast ? now.minusMinutes(NOTIFICATION_RANGE_MINUTES) : now;
LocalDateTime endDt = now.plusMinutes(NOTIFICATION_RANGE_MINUTES);
return toDtosWithProjectNames(
listReserveRepository.findNotifications(userId, startDt, endDt)
);
}
@Transactional(readOnly = true)
public List<ListReserveDto> findByUserAndDateRange(
String userId,
LocalDate fromDt,
LocalDate toDt
) {
if (fromDt.isAfter(toDt)) {
throw BusinessException.badRequest(
"INVALID_RESERVE_DATE_RANGE",
"예약 조회 시작일은 종료일보다 늦을 수 없습니다."
).with("fromDt", fromDt).with("toDt", toDt);
}
return toDtosWithProjectNames(listReserveRepository.findByUserAndDateRange(
userId,
fromDt.atStartOfDay(),
toDt.atTime(LocalTime.MAX)
));
}
@Transactional
public void confirm(Long listResveIdx, String userId) {
TListResveEntity entity = listReserveRepository.findById(listResveIdx)
.filter(reserve -> Objects.equals(reserve.getResveUser(), userId))
.orElseThrow(() -> BusinessException.notFound(
"RESERVE_NOT_FOUND",
"예약 정보를 찾을 수 없습니다."
).with("listResveIdx", listResveIdx));
entity.setCnfirm(true);
}
@Transactional
public int confirmByProjectSidAndUser(Long prjctIdx, String sid, String resveUser) {
return listReserveRepository.confirmByProjectSidAndUser(prjctIdx, sid, resveUser);
}
private List<ListReserveDto> toDtosWithProjectNames(List<TListResveEntity> reserves) {
List<Long> prjctIdxList = reserves.stream()
.map(TListResveEntity::getPrjctIdx)
.distinct()
.toList();
Map<Long, String> prjctNameByIdx = new HashMap<>();
projectRepository.findAllById(prjctIdxList)
.forEach(project -> prjctNameByIdx.put(project.getPrjctIdx(), project.getPrjctNm()));
return reserves.stream()
.map(reserve -> ListReserveDto.from(
reserve,
prjctNameByIdx.get(reserve.getPrjctIdx())
))
.toList();
}
}

View File

@@ -241,6 +241,8 @@ public class UserService {
throw BusinessException.notFound("USER_NOT_FOUND", "사용자를 찾을 수 없습니다.")
.with("userId", userId);
}
assignService.deleteListAssignWithUser(userId);
}
/*******************************private*******************************/
@@ -308,12 +310,14 @@ public class UserService {
));
} else {
// 예시: 8~20자, 영문 + 숫자 반드시 포함, 특수문자 허용
String pwPattern = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d!@#$%^&*()_+\\-={}\\[\\]:;\"'<>,.?/]{8,20}$";
//String pwPattern = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d!@#$%^&*()_+\\-={}\\[\\]:;\"'<>,.?/]{8,20}$";
// 1~20자, 영문·숫자·특수문자 허용
String pwPattern = "^[A-Za-z\\d!@#$%^&*()_+\\-={}\\[\\]:;\"'<>,.?/]{1,20}$";
if (!userPw.matches(pwPattern)) {
result.add(new DataVerificationDto(
false,
"사용자 PW",
"비밀번호는 영문과 숫자를 포함한 8~20자로 입력해야 합니다."
"비밀번호는 영문, 숫자, 허용된 특수문자를 사용하여 1~20자로 입력해야 합니다."
));
}
}