Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,22 @@
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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.RestController;

import com.sniptext.domain.template.controller.dto.TemplateCreateRequest;
import com.sniptext.domain.template.controller.dto.TemplateCreateResponse;
import com.sniptext.domain.template.controller.dto.TemplateDetailResponse;
import com.sniptext.domain.template.controller.dto.TemplateUpdateRequest;
import com.sniptext.domain.template.controller.dto.TemplateUpdateResponse;
import com.sniptext.domain.template.service.TemplateCommandService;
import com.sniptext.domain.template.service.TemplateQueryService;
import com.sniptext.domain.template.service.dto.query.TemplateDetailQuery;
import com.sniptext.domain.template.service.dto.result.TemplateCreateResult;
import com.sniptext.domain.template.service.dto.result.TemplateDetailResult;
import com.sniptext.domain.template.service.dto.result.TemplateUpdateResult;
import com.sniptext.global.response.ApiResponse;
import com.sniptext.global.security.LoginUser;

Expand Down Expand Up @@ -53,4 +57,15 @@ public ResponseEntity<ApiResponse<TemplateCreateResponse>> createTemplate(
return ApiResponse.success(TemplateSuccessCode.TEMPLATE_CREATED, TemplateCreateResponse.from(result));
}

@PutMapping("/{templateId}")
public ResponseEntity<ApiResponse<TemplateUpdateResponse>> updateTemplate(
@LoginUser Long userId,
@PathVariable Long templateId,
@Valid @RequestBody TemplateUpdateRequest request) {

TemplateUpdateResult result = templateCommandService.update(request.toCommand(userId, templateId));

return ApiResponse.success(TemplateSuccessCode.TEMPLATE_UPDATED, TemplateUpdateResponse.from(result));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
public enum TemplateSuccessCode implements ResultCode {

TEMPLATE_FOUND(HttpStatus.OK, "TEMPLATE200_2", "템플릿 조회에 성공했습니다."),
TEMPLATE_UPDATED(HttpStatus.OK, "TEMPLATE200_3", "수정 내용이 저장되었습니다."),
TEMPLATE_CREATED(HttpStatus.CREATED, "TEMPLATE201_1", "템플릿이 저장되었습니다.");

private final HttpStatus httpStatus;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.sniptext.domain.template.controller.dto;

import com.sniptext.domain.template.annotation.ValidShortcut;
import com.sniptext.domain.template.annotation.ValidTemplateContent;
import com.sniptext.domain.template.annotation.ValidTemplateTitle;
import com.sniptext.domain.template.service.dto.command.TemplateUpdateCommand;

/**
* 템플릿 수정 (명세 11번). 세 필드를 모두 보내는 전체 수정이다.
* 여러 개가 틀리면 선언 순서상 첫 에러 하나만 내려주므로 이름 → 단축어 → 내용 순서를 지킨다.
* 공백·길이 기준이 화면과 같도록 @NotBlank·@Size 대신 값 객체 규칙을 쓰는 검증만 붙인다.
*/
public record TemplateUpdateRequest(
@ValidTemplateTitle String title,
@ValidShortcut String shortcut,
@ValidTemplateContent String content
) {

public TemplateUpdateCommand toCommand(Long userId, Long templateId) {
return new TemplateUpdateCommand(userId, templateId, title, shortcut, content);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.sniptext.domain.template.controller.dto;

import java.time.LocalDateTime;
import java.util.List;

import com.sniptext.domain.template.service.dto.result.TemplateUpdateResult;

/** 템플릿 수정 결과 (명세 11번). 시각은 전역 직렬화 설정이 +09:00을 붙여 내보낸다. */
public record TemplateUpdateResponse(
Long templateId,
String title,
String shortcut,
String content,
List<String> variables,
LocalDateTime lastUsedAt,
LocalDateTime createdAt,
LocalDateTime editedAt
) {

public static TemplateUpdateResponse from(TemplateUpdateResult result) {
return new TemplateUpdateResponse(
result.templateId(),
result.title(),
result.shortcut(),
result.content(),
result.variables(),
result.lastUsedAt(),
result.createdAt(),
result.editedAt()
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.time.LocalDateTime;

import org.hibernate.annotations.DynamicUpdate;

import com.sniptext.global.entity.BaseTimeEntity;

import jakarta.persistence.Column;
Expand All @@ -22,9 +24,11 @@
* edited_at은 이름·단축어·본문 수정, last_used_at은 사용 기록, deleted_at은 휴지통 이동에서만 바뀐다.
* updated_at은 모든 변경에서 감사 기능이 기록한다 (확장 동기화 기준).
* 이름·단축어·본문의 규칙은 각 값 객체가 갖고, 여기서는 필수 값만 검사한다.
* UPDATE는 바뀐 컬럼만 쓴다. 전체 컬럼을 쓰면 수정 요청이 읽은 뒤 기록된 휴지통 이동·사용 시각을 옛 값으로 되돌린다.
*/
@Getter
@Entity
@DynamicUpdate
@Table(name = "templates")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Template extends BaseTimeEntity {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public interface TemplateRepository extends JpaRepository<Template, Long> {
*/
boolean existsByUserIdAndActiveShortcutKey(Long userId, String activeShortcutKey);

/** existsByUserIdAndActiveShortcutKey에서 한 템플릿을 뺀 것. 자기 자신의 단축어는 중복이 아니므로 수정이 쓴다 */
boolean existsByUserIdAndActiveShortcutKeyAndIdNot(Long userId, String activeShortcutKey, Long id);

/**
* 넘긴 비교 키 중 활성 템플릿(휴지통 제외)이 이미 쓰는 키. 자동 번호 후보를 한 번에 확인할 때 쓴다.
* existsByUserIdAndActiveShortcutKey와 같이 생성 컬럼이라 휴지통 조건이 따로 없고, 유니크 인덱스를 그대로 탄다
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.sniptext.domain.template.service;

import java.time.Clock;
import java.time.LocalDateTime;
import java.util.Set;

import org.hibernate.exception.ConstraintViolationException;
Expand All @@ -18,8 +20,10 @@
import com.sniptext.domain.template.repository.TemplateRepository;
import com.sniptext.domain.template.service.dto.command.TemplateCreateCommand;
import com.sniptext.domain.template.service.dto.command.TemplateCreateFromGalleryCommand;
import com.sniptext.domain.template.service.dto.command.TemplateUpdateCommand;
import com.sniptext.domain.template.service.dto.result.TemplateCreateResult;
import com.sniptext.domain.template.service.dto.result.TemplateShortcutAssignResult;
import com.sniptext.domain.template.service.dto.result.TemplateUpdateResult;
import com.sniptext.domain.user.service.UserCommandService;
import com.sniptext.global.exception.BusinessException;
import com.sniptext.global.policy.UsageLimits;
Expand All @@ -36,7 +40,10 @@ public class TemplateCommandService {

private final UserCommandService userCommandService;

private final TemplateQueryService templateQueryService;

private final TransactionTemplate transactionTemplate;
private final Clock clock;

/**
* 새 템플릿 저장. 회원 행을 먼저 잠가 같은 회원의 생성·복구·갤러리 저장을 한 줄로 세운 뒤 한도를 검사한다.
Expand Down Expand Up @@ -91,6 +98,27 @@ public TemplateShortcutAssignResult createFromGallery(TemplateCreateFromGalleryC
});
}

/**
* 템플릿 수정. 없거나 다른 회원 것이면 TEMPLATE404_1, 휴지통에 있으면 TEMPLATE404_2, 내 다른 활성 템플릿과 단축어가 겹치면 TEMPLATE409_1.
* 개수가 바뀌지 않으므로 회원을 잠그지 않고, 동시에 고치면 나중 저장이 덮어쓴다.
* 조회 뒤 저장 전에 휴지통으로 옮겨지면 TEMPLATE404_2 대신 200이고 수정은 휴지통 행에 남는다.
* 휴지통은 단축어를 점유하지 않아 충돌이 없고 복구하면 고친 내용이 남는 정도라 허용한다.
* 막아야 하면 수정용 조회만 FOR UPDATE로 잠근다. 변경 감지는 그대로 두고, 휴지통 이동이 먼저 끝난 경우 TEMPLATE404_2를 낼 수 있다.
*/
@Transactional
public TemplateUpdateResult update(TemplateUpdateCommand command) {
Template template = templateQueryService.getActiveTemplate(command.userId(), command.templateId());

TemplateTitle title = TemplateTitle.create(command.title());
Shortcut shortcut = Shortcut.create(command.shortcut());
validateShortcutAvailable(command.userId(), shortcut, template.getId());
TemplateContent content = TemplateContent.create(command.content());

template.edit(title, shortcut, content, LocalDateTime.now(clock));

return TemplateUpdateResult.from(save(template));
}
Comment on lines +110 to +120

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

조회와 저장 사이에 다른 탭에서 휴지통으로 옮기면, 휴지통 템플릿에 수정이 들어가고 200이 나갈 것 같은데 맞을까요?!
창이 아주 짧아서 지금은 허용해도 될 것 같은데, 허용한다면 주석에 한 줄 남겨 주면 좋겠습니다! 막으려면 UPDATE 조건에 deleted_at IS NULL을 거는 방법도 방법 고려해주시면 좋을 거 같아요!

@oTAETAEo oTAETAEo Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chjpooh2002 말씀해 주신 부분으로 다시한번 보니까 일어날수 있는 상황인것 같습니당 👏

... templateQueryService.getActiveTemplate(command.userId(), command.templateId());
해당 라인이 실행이 되어서 조회 후에 마지막 return 사이에 발생할수 있는 문제 인걸로 이해 했습니다

조회와 저장 사이에 휴지통으로 옮기면 200이 동작은 서비스 이용에는 큰 문제는 없을것 같은 생각이기도 하구
@DynamicUpdate로 deleted_at은 되돌아가지 않아서 삭제한 게 다시 풀리지는 않고, 구간이 짧아서 괜찮을 것 같습니다.

deleted_at IS NULL 조건은 변경 감지 대신 @Modifying으로 바꿔야 해서 넣지 않았고, 주석에 남겨 두려고 하는데 다른 의견 있으시면 남겨주세여 !

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 그 판단이 맞다고 봅니다! 휴지통 템플릿은 단축어 점유가 풀려 있어서 충돌도 없고, 복구하면 고친 내용이 남는 정도라 실제 피해가 거의 없네요.
말씀대로 제가 처음 말한 조건부 UPDATE는 변경 감지를 버려야 해서 과했던 것 같아요. 나중에 막아야 하는 상황이 오면 수정용 조회만 FOR UPDATE로 잠그는 방법이 있어서, 변경 감지는 그대로 두고 휴지통 이동이 먼저 끝난 경우 404_2를 낼 수 있어요. 주석에 그 선택지도 같이 적어 두면 좋겠습니다!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋습니다 !


private static void requireNoOuterTransaction() {
if (TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("갤러리 저장은 호출자 트랜잭션 밖에서 불러야 한다");
Expand All @@ -109,6 +137,12 @@ private void validateShortcutAvailable(Long userId, Shortcut shortcut) {
}
}

private void validateShortcutAvailable(Long userId, Shortcut shortcut, Long excludeTemplateId) {
if (templateRepository.existsByUserIdAndActiveShortcutKeyAndIdNot(userId, shortcut.getKey(), excludeTemplateId)) {
throw new BusinessException(TemplateErrorCode.SHORTCUT_DUPLICATED);
}
}

/**
* 미리 조회를 통과해도 유니크 제약 위반은 날 수 있다. 회원 잠금은 생성·복구·갤러리 저장끼리만 줄을 세우므로,
* 잠금을 잡지 않는 수정 요청이 같은 단축어로 바꾸면 조회와 저장 사이에 끼어든다. 그 경우도 TEMPLATE409_1로 바꾼다.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.sniptext.domain.template.service.dto.command;

/** 템플릿 수정 입력. 값은 요청 단계에서 형식 검증을 마친 입력 그대로이고, 정규화는 값 객체가 한다. */
public record TemplateUpdateCommand(
Long userId,
Long templateId,
String title,
String shortcut,
String content
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.sniptext.domain.template.service.dto.result;

import java.time.LocalDateTime;
import java.util.List;

import com.sniptext.domain.template.entity.Template;
import com.sniptext.domain.template.support.TemplateVariableExtractor;

/** 수정한 템플릿. 변수 목록은 저장하지 않고 본문에서 뽑는다. */
public record TemplateUpdateResult(
Long templateId,
String title,
String shortcut,
String content,
List<String> variables,
LocalDateTime lastUsedAt,
LocalDateTime createdAt,
LocalDateTime editedAt
) {

public static TemplateUpdateResult from(Template template) {
String content = template.getContent().getValue();
return new TemplateUpdateResult(
template.getId(),
template.getTitle().getValue(),
template.getShortcut().getValue(),
content,
TemplateVariableExtractor.extract(content),
template.getLastUsedAt(),
template.getCreatedAt(),
template.getEditedAt()
);
}

}
Loading