Skip to content
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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ domain/{도메인}/
- 회원은 `User.create(email, nickname, profileImageUrl)`로 만든다. 닉네임 정리(앞뒤 공백 제거, 50자 자르기, 비면 이메일 앞부분)는 가입 서비스가 하고, `create`는 길이·필수 값만 검사한다. 테스트에서는 `UserFixture`를 쓴다
- 롬복 허용: `@Getter`, `@NoArgsConstructor(access = PROTECTED)`, `@Builder(access = PRIVATE)`(정적 팩토리 안에서만), `@RequiredArgsConstructor`, `@Slf4j`
- 롬복 금지: `@Setter`, `@Data`, `@AllArgsConstructor`, 엔티티의 `@ToString`·`@EqualsAndHashCode`
- 트랜잭션: 서비스 클래스에 `@Transactional(readOnly = true)`, 쓰기 메서드에만 `@Transactional`
- 트랜잭션: 조회 서비스(`{도메인}QueryService`)는 클래스에 `@Transactional(readOnly = true)`. 명령 서비스(`{도메인}CommandService`)는 클래스에 붙이지 않고 쓰기 메서드마다 `@Transactional` (클래스에 `readOnly`를 두면 메서드에 빠뜨렸을 때 쓰기가 읽기 전용 트랜잭션으로 실행된다)
- 검증: 형식 검증은 요청 객체(빈 검증), 업무 규칙 검증은 서비스

## 응답·예외
Expand Down
4 changes: 4 additions & 0 deletions docs/s1-api-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -1798,13 +1798,15 @@ POST /api/v1/trash/templates/18/restore
| --- | --- | --- | --- |
| 403 | TEMPLATE403_1 | 템플릿 저장 한도에 도달했어요. | 활성 템플릿 수가 한도(50개) 이상. 한도 모달은 기획에서 삭제됨. 화면 처리 미정 (프론트·기획 논의 중) |
| 409 | TEMPLATE409_2 | 사용할 수 있는 단축어 번호가 없어요. | 자동 번호 2~99가 모두 사용 중 |
| 409 | TEMPLATE409_1 | 이미 사용 중인 단축어예요. | 고른 단축어를 저장하는 사이 다른 탭의 수정과 겹친 경우 (드묾). 복구되지 않고 휴지통에 그대로 있으며, 다시 시도하면 자동 번호로 복구됨 |
| 404 | TRASH404_1 | 휴지통에서 템플릿을 찾을 수 없어요. | 휴지통에 없는 템플릿(이미 복구·영구 삭제됨, 다른 사람 템플릿) |

##### 비고

- 한도(50개) 도달 시 복구하지 않고 TEMPLATE403_1. 한도 모달(BIN-07)은 기획에서 삭제됐습니다.
- 자동 번호 규칙: 원본 뒤에 2부터 99까지 붙여 비어 있는 첫 번호 사용. "/" 뒤가 10자를 넘으면 원본을 뒤에서 잘라 맞춤. 예) /견적요청서작성안내문 → /견적요청서작성안내2
- 숫자로 끝나는 단축어(/견적2)는 원본 뒤에 붙입니다(/견적22). (개발팀 결정)
- 단축어는 서버가 비어 있는 것으로 고르지만, 같은 순간 다른 탭에서 다른 템플릿을 같은 단축어로 수정하면 TEMPLATE409_1이 날 수 있습니다. 사용자가 입력한 값이 없으므로 화면은 입력창 에러가 아니라 "다시 시도" 안내로 처리합니다. 다시 요청하면 자동 번호가 붙어 성공합니다 (개발팀 결정).
- editedAt·최근 사용 시각·생성 시각은 삭제 전 값 그대로 돌아옵니다. 목록은 생성 순이라 원래 자리로 돌아갑니다.

---
Expand Down Expand Up @@ -2234,6 +2236,7 @@ POST /api/v1/gallery/templates/3/save
| --- | --- | --- | --- |
| 403 | TEMPLATE403_1 | 템플릿 저장 한도에 도달했어요. | 활성 템플릿 수가 한도(50개) 이상. 한도 모달은 기획에서 삭제됨. 화면 처리 미정 (프론트·기획 논의 중) |
| 409 | TEMPLATE409_2 | 사용할 수 있는 단축어 번호가 없어요. | 자동 번호 2~99가 모두 사용 중 |
| 409 | TEMPLATE409_1 | 이미 사용 중인 단축어예요. | 고른 단축어를 저장하는 사이 다른 탭의 수정과 겹친 경우 (드묾). 저장되지 않으며, 다시 시도하면 자동 번호로 저장됨 |
| 404 | GALLERY404_1 | 갤러리 템플릿을 찾을 수 없어요. | 없거나 비공개 처리된 갤러리 템플릿 |

##### 비고
Expand All @@ -2245,6 +2248,7 @@ POST /api/v1/gallery/templates/3/save
- 비로그인 사용자는 화면에서 로그인으로 유도만 합니다(가입 후 자동 저장 없음).
- **같은 갤러리 템플릿을 여러 번 저장할 수 있습니다(기획 확정).** 저장할 때마다 내 템플릿이 새로 하나씩 생기고, 각각 템플릿 한도(50개)를 한 칸씩 차지합니다.
- 단축어가 이미 있으면 자동 번호를 붙여 저장합니다(`/견적` → `/견적2` → `/견적3`). 2~99가 모두 쓰이면 TEMPLATE409_2.
- 같은 순간 다른 탭의 수정과 단축어가 겹치면 TEMPLATE409_1이 날 수 있습니다. 화면 처리는 복구 API(16번)와 같습니다.
- 갤러리에서 가져온 템플릿은 내용만 복사하고 원본과 동기화하지 않습니다. `source_gallery_template_id`는 출처 기록·집계용입니다(원본이 삭제되면 비워짐).
- 화면에 "저장됨" 표시는 없습니다. 저장 버튼은 항상 그대로 동작합니다.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@

import org.springframework.http.ResponseEntity;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sniptext.domain.template.controller.dto.TrashListResponse;
import com.sniptext.domain.template.controller.dto.TrashRestoreResponse;
import com.sniptext.domain.template.service.TrashCommandService;
import com.sniptext.domain.template.service.TrashQueryService;
import com.sniptext.domain.template.service.dto.command.TrashRestoreCommand;
import com.sniptext.domain.template.service.dto.query.TrashListQuery;
import com.sniptext.global.response.ApiResponse;
import com.sniptext.global.security.LoginUser;
Expand All @@ -26,6 +31,8 @@ public class TrashController {

private final TrashQueryService trashQueryService;

private final TrashCommandService trashCommandService;

@GetMapping
public ResponseEntity<ApiResponse<TrashListResponse>> getTrash(
@LoginUser Long userId,
Expand All @@ -39,4 +46,15 @@ public ResponseEntity<ApiResponse<TrashListResponse>> getTrash(
return ApiResponse.success(TrashSuccessCode.TRASH_LIST_FOUND, response);
}

@PostMapping("/{templateId}/restore")
public ResponseEntity<ApiResponse<TrashRestoreResponse>> restore(
@LoginUser Long userId,
@PathVariable Long templateId) {

TrashRestoreResponse response = TrashRestoreResponse.from(
trashCommandService.restore(new TrashRestoreCommand(userId, templateId)));

return ApiResponse.success(TrashSuccessCode.TRASH_RESTORED, response);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
@RequiredArgsConstructor
public enum TrashSuccessCode implements ResultCode {

TRASH_LIST_FOUND(HttpStatus.OK, "TRASH200_1", "휴지통 조회에 성공했습니다.");
TRASH_LIST_FOUND(HttpStatus.OK, "TRASH200_1", "휴지통 조회에 성공했습니다."),
TRASH_RESTORED(HttpStatus.OK, "TRASH200_2", "템플릿을 복구했습니다.");

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

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

/** 휴지통 복구 결과 (명세 16번). shortcutChanged면 화면이 자동 번호 안내 토스트를 띄운다 */
public record TrashRestoreResponse(
Long templateId,
String title,
String shortcut,
String originalShortcut,
boolean shortcutChanged
) {

public static TrashRestoreResponse from(TemplateShortcutAssignResult result) {
return new TrashRestoreResponse(
result.templateId(),
result.title(),
result.shortcut(),
result.originalShortcut(),
result.shortcutChanged()
);
}

}
13 changes: 13 additions & 0 deletions src/main/java/com/sniptext/domain/template/entity/Template.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,19 @@ public void moveToTrash(LocalDateTime now) {
this.deletedAt = now;
}

/**
* 휴지통에서 꺼낸다. shortcut은 삭제 당시 단축어이거나, 겹쳐서 자동 번호를 붙인 단축어다 (고르는 건 서비스가 한다).
* 수정·사용 시각은 삭제 전 값 그대로 둔다. 휴지통이 아닌 템플릿에 부르면 조회 조건을 빠뜨린 코드 실수다.
*/
public void restore(Shortcut shortcut) {
require(shortcut != null, "단축어가 없다");
if (!isInTrash()) {
throw new IllegalStateException("휴지통에 없는 템플릿은 복구할 수 없다");
}
this.shortcut = shortcut;
this.deletedAt = null;
}

public boolean isInTrash() {
return deletedAt != null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
public enum TrashErrorCode implements ResultCode {

/** 커서를 해석할 수 없거나 size가 1~50 밖 */
INVALID_PAGE_REQUEST(HttpStatus.BAD_REQUEST, "TRASH400_1", "잘못된 페이지 요청이에요.");
INVALID_PAGE_REQUEST(HttpStatus.BAD_REQUEST, "TRASH400_1", "잘못된 페이지 요청이에요."),
/** 휴지통에 없는 템플릿 (없는 ID, 다른 회원의 템플릿, 이미 복구·영구 삭제됨) */
TRASHED_TEMPLATE_NOT_FOUND(HttpStatus.NOT_FOUND, "TRASH404_1", "휴지통에서 템플릿을 찾을 수 없어요.");

private final HttpStatus httpStatus;
private final String code;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,29 @@

import org.springframework.data.domain.Limit;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import com.sniptext.domain.template.entity.Template;
import com.sniptext.domain.template.repository.dto.TrashTemplateRow;

import jakarta.persistence.LockModeType;

public interface TemplateRepository extends JpaRepository<Template, Long> {

/** 본인 소유 조회. 휴지통 템플릿도 찾으므로 내 휴지통과 다른 회원 것을 호출자가 구분할 수 있다 */
Optional<Template> findByIdAndUserId(Long id, Long userId);

/**
* 본인의 휴지통 템플릿을 비관적 쓰기 잠금으로 찾는다 (SELECT ... FOR UPDATE). 복구가 쓴다.
* 회원을 잠그지 않는 정리 배치·영구 삭제가 먼저 지우고 있으면 기다렸다가 빈 값을 받는다.
* 잠금 순서는 회원 행 → 템플릿 행이다. 템플릿을 먼저 잠그고 회원을 잠그는 쪽이 생기면 교착이 날 수 있다
*/
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select t from Template t where t.id = :id and t.userId = :userId and t.deletedAt is not null")
Optional<Template> findTrashedByIdAndUserIdForUpdate(@Param("id") Long id, @Param("userId") Long userId);

/** 휴지통을 제외한 보유 개수. idx_templates_user_deleted (user_id, deleted_at)를 탄다 */
long countByUserIdAndDeletedAtIsNull(Long userId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ public TemplateShortcutAssignResult createFromGallery(TemplateCreateFromGalleryC
validateTemplateLimit(command.userId());

Shortcut original = Shortcut.create(command.shortcut());
Set<String> usedKeys = templateRepository.findActiveShortcutKeys(command.userId(), original.candidateKeys());
Shortcut assigned = original.findAvailable(usedKeys)
.orElseThrow(() -> new BusinessException(TemplateErrorCode.SHORTCUT_NUMBER_EXHAUSTED));
Shortcut assigned = assignShortcut(command.userId(), original);

Template template = Template.createFromGallery(
command.userId(),
Expand Down Expand Up @@ -125,12 +123,27 @@ private static void requireNoOuterTransaction() {
}
}

private void validateTemplateLimit(Long userId) {
/*
* 아래 패키지 범위 메서드 3개는 휴지통 복구(TrashCommandService)가 같이 쓴다. 생성·갤러리 저장과 규칙이 같아야 하기 때문이다.
* 셋 다 트랜잭션을 따로 열지 않으므로, 호출자가 lockUser를 첫 조회로 부른 트랜잭션 안에서 불러야 한다.
* save는 엔티티를 받고 돌려주고, 순서를 지키지 않으면 한도를 넘을 수 있어 template 도메인 안에서만 부른다
* (패키지 범위라 service 패키지 밖에서는 부를 수 없다).
*/

/** 활성 템플릿(휴지통 제외)이 한도 이상이면 TEMPLATE403_1 */
void validateTemplateLimit(Long userId) {
if (templateRepository.countByUserIdAndDeletedAtIsNull(userId) >= UsageLimits.TEMPLATE_LIMIT) {
throw new BusinessException(TemplateErrorCode.TEMPLATE_LIMIT_REACHED);
}
}

/** 활성 템플릿과 겹치지 않으면 원본, 겹치면 자동 번호를 붙인 단축어. 2~99가 모두 차면 TEMPLATE409_2 */
Shortcut assignShortcut(Long userId, Shortcut original) {
Set<String> usedKeys = templateRepository.findActiveShortcutKeys(userId, original.candidateKeys());
return original.findAvailable(usedKeys)
.orElseThrow(() -> new BusinessException(TemplateErrorCode.SHORTCUT_NUMBER_EXHAUSTED));
}
Comment on lines +126 to +145

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.

(선택, 후속 이슈로 넘겨도 돼요) 한도 검사·자동 번호·저장을 이제 세 곳(생성·갤러리 저장·복구)이 같은 규칙으로 쓰게 됐는데, 지금은 TrashCommandService가 TemplateCommandService의 패키지 범위 메서드를 직접 부르는 구조라 서비스끼리 의존하게 됐어요.
이 세 메서드를 패키지 범위 컴포넌트(예: TemplateSaveSupport)로 따로 빼면, 두 서비스가 같은 도우미에 기대는 형태가 되고 "회원 잠금을 먼저 잡은 트랜잭션 안에서 불러야 한다"는 규칙도 한 클래스 주석에 모을 수 있을 것 같아요.
동작은 지금도 문제없어서 이번 PR에서 꼭 바꿀 필요는 없다고 생각합니다!

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.

의견 감사합니당 🙂

확인해 보니 이 세 메서드를 쓰는 곳은 생성, 갤러리 저장, 복구 세 곳으로 끝이고 지금은 같은 패키지 안에서만 부르고
있다보니 괜찮을것 같습니다 !

쓰는 곳이 더 생기거나 TemplateCommandService가 커지면 그때 분리하는것도 좋을것 같아요 !

해당 부분은 남은 API 추가 후 리팩토링 지점으로 두겠습니다


private void validateShortcutAvailable(Long userId, Shortcut shortcut) {
if (templateRepository.existsByUserIdAndActiveShortcutKey(userId, shortcut.getKey())) {
throw new BusinessException(TemplateErrorCode.SHORTCUT_DUPLICATED);
Expand All @@ -149,7 +162,7 @@ private void validateShortcutAvailable(Long userId, Shortcut shortcut, Long excl
* 단축어 유니크가 아닌 무결성 위반은 코드 실수라 그대로 던진다 (500).
* 위반 예외 메시지에는 겹친 단축어가 들어 있으므로 원인으로 붙이거나 로그에 남기지 않는다.
*/
private Template save(Template template) {
Template save(Template template) {
try {
return templateRepository.saveAndFlush(template);
} catch (DataIntegrityViolationException e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.sniptext.domain.template.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sniptext.domain.template.entity.Shortcut;
import com.sniptext.domain.template.entity.Template;
import com.sniptext.domain.template.exception.TrashErrorCode;
import com.sniptext.domain.template.repository.TemplateRepository;
import com.sniptext.domain.template.service.dto.command.TrashRestoreCommand;
import com.sniptext.domain.template.service.dto.result.TemplateShortcutAssignResult;
import com.sniptext.domain.user.service.UserCommandService;
import com.sniptext.global.exception.BusinessException;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class TrashCommandService {

private final TemplateRepository templateRepository;

private final UserCommandService userCommandService;

private final TemplateCommandService templateCommandService;

/**
* 휴지통 템플릿을 내 템플릿으로 되돌린다. 한도·자동 번호·저장 규칙은 생성·갤러리 저장과 같다.
* 휴지통에 없으면 TRASH404_1, 한도 도달이면 TEMPLATE403_1, 번호 2~99가 모두 차면 TEMPLATE409_2 (앞의 것이 먼저다).
* 회원 잠금이 트랜잭션의 첫 조회여야 한다. MySQL 기본 격리 수준(REPEATABLE READ)은 첫 일반 조회 시점의 스냅샷을 끝까지 쓰므로,
* 템플릿을 먼저 읽으면 잠금을 기다리는 사이 커밋된 생성·복구를 개수 검사와 단축어 조회가 보지 못한다.
* 같은 템플릿을 동시에 복구해도 잠금으로 줄을 서므로, 뒤에 온 요청은 이미 꺼낸 템플릿을 읽어 TRASH404_1이 된다.
* 템플릿 행도 잠가 읽는다. 정리 배치·영구 삭제는 회원을 잠그지 않아, 일반 조회로 읽으면 저장 전에 행이 지워져 500이 나기 때문이다.
* 잠금 조회는 스냅샷을 만들지 않으므로 이어지는 개수 검사가 옛 값을 보는 문제는 생기지 않는다.
* 엔티티를 읽으므로 본문 복호화에 실패하는 행은 복구도 500이다.
*/
@Transactional
public TemplateShortcutAssignResult restore(TrashRestoreCommand command) {
userCommandService.lockUser(command.userId());

Template template = templateRepository.findTrashedByIdAndUserIdForUpdate(command.templateId(), command.userId())
.orElseThrow(() -> new BusinessException(TrashErrorCode.TRASHED_TEMPLATE_NOT_FOUND));

templateCommandService.validateTemplateLimit(command.userId());

Shortcut original = template.getShortcut();
template.restore(templateCommandService.assignShortcut(command.userId(), original));

return TemplateShortcutAssignResult.of(templateCommandService.save(template), original);

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.

수정 API는 회원을 잠그지 않아서, assignShortcut으로 번호를 고른 뒤 저장 전에 다른 탭에서 같은 단축어로 수정하면 여기서 유니크 위반이 나고 save()가 TEMPLATE409_1로 바꿔 내보낼 것 같아요!
그런데 명세 16번 에러 표에는 409_1이 없고, 복구는 사용자가 단축어를 고르는 게 아니라서 "이미 사용 중인 단축어예요." 문구도 안 맞아요. 갤러리 저장(21번)도 같은 경로라 같은 상황이고요.

거의 안 일어나는 경우라 코드를 바꾸기보다는, 명세 16번·21번 에러 표에 409_1을 "동시 수정과 겹친 경우, 다시 시도하면 됨"으로 추가하고 프론트에 공유하는 정도면 충분할 것 같은데 어떻게 생각하시나요?!

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.

좋습니다 해당 부분은 명세 16, 21번에 반영하구 프론트에 공유 드리겠습니다 👏

}

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

public record TrashRestoreCommand(Long userId, Long templateId) {
}
Loading
Loading