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
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package kr.ac.kookmin.stream.api.app.welfare.rental;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import kr.ac.kookmin.stream.api.app.AppApiUser;
import kr.ac.kookmin.stream.api.app.welfare.rental.request.ItemListParams;
import kr.ac.kookmin.stream.api.app.welfare.rental.request.RentalHistoryListParams;
import kr.ac.kookmin.stream.api.app.welfare.rental.response.ItemListItemResponse;
import kr.ac.kookmin.stream.api.app.welfare.rental.response.RentalHistoryListResponse;
import kr.ac.kookmin.stream.api.app.welfare.rental.response.ReturnRequiredListResponse;
import kr.ac.kookmin.stream.api.common.dto.ApiResponse;
import kr.ac.kookmin.stream.api.common.dto.CursorSliceResponse;
import kr.ac.kookmin.stream.api.common.openapi.ApiErrorCode;
import kr.ac.kookmin.stream.common.CommonErrorCode;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalErrorCode;
import org.springdoc.core.annotations.ParameterObject;

/**
* 학생 앱 빌릴게(물품 대여) API의 문서 명세. 구현은 {@link AppRentalController}가 맡는다.
* <p>
* 스웨거 문서용 어노테이션만 이쪽에 두고 컨트롤러에는 라우팅과 본문만 남긴다. 경로 매핑과
* 파라미터 바인딩(@{@code ModelAttribute} 등)은 구현체에 둔다.
*/
@Tag(name = "빌릴게", description = "학생 앱 빌릴게 물품·대여 이력 조회")
public interface AppRentalApi {

/** 물품 목록. 이름순 커서 페이지네이션이며 카테고리·검색어로 거른다. */
@Operation(summary = "물품 목록 조회",
description = "물품을 이름순으로 커서 기반 조회한다. category로 분류를, keyword로 이름 검색을 거르고 "
+ "cursor/size로 다음 페이지를 넘긴다. 반납 정책(returnPolicy)은 대여품(RENTAL)에만 내려가고 소모품은 null이다.")
@ApiErrorCode(type = CommonErrorCode.class, codes = {"INVALID_INPUT"})
@ApiErrorCode(type = RentalErrorCode.class, codes = {"ITEM_INVALID_CURSOR"})
ApiResponse<CursorSliceResponse<ItemListItemResponse>> getItems(@ParameterObject ItemListParams params);

/** 내 대여 이력. 최근 신청순이며 상태로 거른다. */
@Operation(summary = "내 대여 이력 조회",
description = "내 대여 이력을 최근 신청순으로 조회한다. status를 생략하면 전체 상태를 조회한다.")
@ApiErrorCode(type = CommonErrorCode.class, codes = {"INVALID_INPUT"})
ApiResponse<RentalHistoryListResponse> getHistories(
AppApiUser apiUser,
@ParameterObject RentalHistoryListParams params
);

/** 지금 반납해야 하는 대여와 반납 기한. */
@Operation(summary = "반납 필요 대여 조회",
description = "지금 반납해야 하는 대여(대여 중 상태)와 반납 기한(dueAt)을 조회한다. "
+ "반납 기한은 대여일에 최대 대여 일수를 더한 날의 반납 마감 시각이다. 없으면 빈 배열이다.")
ApiResponse<ReturnRequiredListResponse> getReturnRequired(AppApiUser apiUser);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package kr.ac.kookmin.stream.api.app.welfare.rental;

import jakarta.validation.Valid;
import kr.ac.kookmin.stream.api.app.AppApiUser;
import kr.ac.kookmin.stream.api.app.welfare.rental.request.ItemListParams;
import kr.ac.kookmin.stream.api.app.welfare.rental.request.RentalHistoryListParams;
import kr.ac.kookmin.stream.api.app.welfare.rental.response.ItemListItemResponse;
import kr.ac.kookmin.stream.api.app.welfare.rental.response.RentalHistoryListResponse;
import kr.ac.kookmin.stream.api.app.welfare.rental.response.ReturnRequiredListResponse;
import kr.ac.kookmin.stream.api.common.dto.ApiResponse;
import kr.ac.kookmin.stream.api.common.dto.CursorSliceResponse;
import kr.ac.kookmin.stream.common.CursorSliceResult;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.Item;
import kr.ac.kookmin.stream.welfare.domain.rental.service.ItemService;
import kr.ac.kookmin.stream.welfare.domain.rental.service.RentalHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1/app/billilge")
@RequiredArgsConstructor
public class AppRentalController implements AppRentalApi {

private final ItemService itemService;
private final RentalHistoryService rentalHistoryService;

@Override
@GetMapping("/items")
public ApiResponse<CursorSliceResponse<ItemListItemResponse>> getItems(
@Valid @ModelAttribute ItemListParams params
) {
CursorSliceResult<Item> result = itemService.getItems(
params.toCategory(), params.toKeyword(), params.toCursor(), params.sizeOrDefault()
);
return ApiResponse.success(CursorSliceResponse.from(result, ItemListItemResponse::from));
}

@Override
@GetMapping("/histories")
public ApiResponse<RentalHistoryListResponse> getHistories(
AppApiUser apiUser,
@Valid @ModelAttribute RentalHistoryListParams params
) {
return ApiResponse.success(RentalHistoryListResponse.from(
rentalHistoryService.getHistories(apiUser.userId(), params.toStatus())
));
}

@Override
@GetMapping("/histories/return-required")
public ApiResponse<ReturnRequiredListResponse> getReturnRequired(AppApiUser apiUser) {
return ApiResponse.success(ReturnRequiredListResponse.from(
rentalHistoryService.getReturnRequiredRentals(apiUser.userId())
));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package kr.ac.kookmin.stream.api.app.welfare.rental.request;

import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import kr.ac.kookmin.stream.api.common.CursorCodec;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.ItemCategory;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.ItemCursor;

public record ItemListParams(
String category,

String keyword,

String cursor,

@Min(value = 1, message = "조회 개수는 1 이상 100 이하여야 합니다.")
@Max(value = 100, message = "조회 개수는 1 이상 100 이하여야 합니다.")
Integer size
) {

private static final int DEFAULT_SIZE = 20;

public ItemCategory toCategory() {
return ItemCategory.from(category);
}

// 공백뿐인 검색어는 검색하지 않는 것과 같다
public String toKeyword() {
return keyword == null || keyword.isBlank() ? null : keyword.strip();
}

public ItemCursor toCursor() {
return cursor == null ? null : ItemCursor.from(CursorCodec.decode(cursor));
}

public int sizeOrDefault() {
return size == null ? DEFAULT_SIZE : size;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package kr.ac.kookmin.stream.api.app.welfare.rental.request;

import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalStatus;

public record RentalHistoryListParams(String status) {

public RentalStatus toStatus() {
return RentalStatus.from(status);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package kr.ac.kookmin.stream.api.app.welfare.rental.response;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
* 물품 이미지 파일 키를 공개 URL로 바꾸는 지점.
* <p>
* 파일 키 → 공개 URL 조립이 아직 없어 현재는 항상 null이다. 조립이 생기면 이 메서드만 채우면 된다.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
final class ItemImageUrl {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

ItemImageUrl말고 ImageUrl이나 FileUrl같이 공통으로 쓸 수 있는 객체를 하나 만들어서 합치는 건 어떨까요? 이제 실제 저장소인 r2를 연동했으니까 새로 이슈 파서 key와 url을 결합하는 걸 작업해보시면 좋을듯 합니다.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

공통 객체를 만들어서 합치는 의견에 동의합니다. 이후에 별도 이슈로 분리해서 처리하겠습니다!


static String from(String imageKey) {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package kr.ac.kookmin.stream.api.app.welfare.rental.response;

import java.time.format.DateTimeFormatter;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.Item;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.ItemCategory;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.ItemType;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.ReturnPolicy;

public record ItemListItemResponse(
Long itemId,
String name,
ItemCategory category,
ItemType type,
int count,
String imageUrl,
ReturnPolicyResponse returnPolicy
) {

public static ItemListItemResponse from(Item item) {
ReturnPolicy returnPolicy = item.getReturnPolicy();
return new ItemListItemResponse(
item.getId(),
item.getName(),
item.getCategory(),
item.getType(),
item.getCount(),
ItemImageUrl.from(item.getImageKey()),
returnPolicy == null ? null : ReturnPolicyResponse.from(returnPolicy)
);
}

public record ReturnPolicyResponse(int maxRentalDays, String returnDeadline) {

private static final DateTimeFormatter DEADLINE_FORMAT = DateTimeFormatter.ofPattern("HH:mm");

public static ReturnPolicyResponse from(ReturnPolicy returnPolicy) {
return new ReturnPolicyResponse(
returnPolicy.maxRentalDays(),
returnPolicy.returnDeadline().format(DEADLINE_FORMAT)
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package kr.ac.kookmin.stream.api.app.welfare.rental.response;

import java.time.LocalDateTime;
import java.util.List;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalHistory;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalRecord;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalStatus;

public record RentalHistoryListResponse(List<History> histories) {

public static RentalHistoryListResponse from(List<RentalRecord> records) {
return new RentalHistoryListResponse(records.stream().map(History::from).toList());
}

public record History(
Long rentalHistoryId,
String itemName,
String itemImageUrl,
LocalDateTime rentAt,
LocalDateTime returnedAt,
RentalStatus status
) {

public static History from(RentalRecord record) {
RentalHistory history = record.history();
return new History(
history.getId(),
record.itemName(),
ItemImageUrl.from(record.itemImageKey()),
history.getRentAt(),
history.getReturnedAt(),
history.getRentalStatus()
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package kr.ac.kookmin.stream.api.app.welfare.rental.response;

import java.time.LocalDateTime;
import java.util.List;
import kr.ac.kookmin.stream.welfare.domain.rental.domain.RentalRecord;

public record ReturnRequiredListResponse(List<Rental> rentalHistories) {

public static ReturnRequiredListResponse from(List<RentalRecord> records) {
return new ReturnRequiredListResponse(records.stream().map(Rental::from).toList());
}

public record Rental(
Long rentalHistoryId,
String itemName,
String itemImageUrl,
LocalDateTime dueAt
) {

public static Rental from(RentalRecord record) {
return new Rental(
record.history().getId(),
record.itemName(),
ItemImageUrl.from(record.itemImageKey()),
record.dueAt()
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,24 @@ public class Item {

private Long id;
private String name;
private ItemCategory category;
private ItemType type;
private int count;
private String imageKey;
/** 대여품(RENTAL)의 반납 정책. 소모품이거나 정책이 채워지지 않았으면 null이다. */
private ReturnPolicy returnPolicy;

public static Item of(Long id, String name, ItemType type, int count, String imageKey) {
return new Item(id, name, type, count, imageKey);
public static Item of(
Long id,
String name,
ItemCategory category,
ItemType type,
int count,
String imageKey,
ReturnPolicy returnPolicy
) {
// 소모품은 반납하지 않으므로 저장된 값이 있어도 반납 정책을 갖지 않는다
ReturnPolicy applicablePolicy = type == ItemType.RENTAL ? returnPolicy : null;
return new Item(id, name, category, type, count, imageKey, applicablePolicy);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package kr.ac.kookmin.stream.welfare.domain.rental.domain;

import kr.ac.kookmin.stream.common.BusinessException;
import kr.ac.kookmin.stream.common.CommonErrorCode;

public enum ItemCategory {
ELECTRONICS,
DAILY_SUPPLIES,
MEDICINE,
HYGIENE;

public static ItemCategory from(String value) {
if (value == null) {
return null;
}
try {
return ItemCategory.valueOf(value);
} catch (IllegalArgumentException e) {
throw new BusinessException(CommonErrorCode.INVALID_INPUT);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package kr.ac.kookmin.stream.welfare.domain.rental.domain;

import kr.ac.kookmin.stream.common.BusinessException;
import kr.ac.kookmin.stream.common.Cursor;

/**
* 물품 목록의 keyset 커서. 정렬 기준(이름 오름차순 + itemId 오름차순)과 짝을 이룬다.
*/
public record ItemCursor(String name, Long id) implements Cursor {

private static final char JOIN = '|';

public static ItemCursor of(Item item) {
return new ItemCursor(item.getName(), item.getId());
}

// 이름에 구분자가 들어 있어도 되도록 id가 오는 마지막 구분자를 기준으로 나눈다(id는 숫자라 구분자를 포함하지 않는다)
public static ItemCursor from(String raw) {
int separator = raw.lastIndexOf(JOIN);
if (separator < 0) {
throw new BusinessException(RentalErrorCode.ITEM_INVALID_CURSOR);
}
try {
return new ItemCursor(raw.substring(0, separator), Long.valueOf(raw.substring(separator + 1)));
} catch (NumberFormatException e) {
throw new BusinessException(RentalErrorCode.ITEM_INVALID_CURSOR);
}
}

@Override
public String format() {
return name + JOIN + id;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package kr.ac.kookmin.stream.welfare.domain.rental.domain;

import kr.ac.kookmin.stream.common.ErrorCode;
import kr.ac.kookmin.stream.common.ErrorStatus;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.Accessors;

@Getter
@Accessors(fluent = true)
@AllArgsConstructor
public enum RentalErrorCode implements ErrorCode {

ITEM_INVALID_CURSOR(ErrorStatus.BAD_REQUEST, "유효하지 않은 커서입니다.");

private final int status;
private final String message;
}
Loading