Skip to content

Commit

Permalink
Merge pull request #447 from TrandPick/development
Browse files Browse the repository at this point in the history
코드 통합
  • Loading branch information
jooooonj authored Sep 20, 2023
2 parents 4520639 + a3ad7e1 commit 8c3667d
Show file tree
Hide file tree
Showing 13 changed files with 81 additions and 31 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
docker-compose.yml

### STS ###
.apt_generated
Expand Down
33 changes: 33 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
version: '2.1'

services:
zoo1:
image: confluentinc/cp-zookeeper:7.3.2
hostname: zoo1
container_name: zoo1
ports:
- "2181:2181"
environment:
ZOOKEEPER_CLIENT_PORT: 2181
ZOOKEEPER_SERVER_ID: 1
ZOOKEEPER_SERVERS: zoo1:2888:3888


kafka1:
image: confluentinc/cp-kafka:7.3.2
hostname: kafka1
container_name: kafka1
ports:
- "9092:9092"
- "29092:29092"
environment:
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka1:19092,EXTERNAL://${DOCKER_HOST_IP:-127.0.0.1}:9092,DOCKER://host.docker.internal:29092
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,DOCKER:PLAINTEXT
KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
KAFKA_ZOOKEEPER_CONNECT: "zoo1:2181"
KAFKA_BROKER_ID: 1
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
depends_on:
- zoo1
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package project.trendpick_pro.domain.cart.controller;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand Down Expand Up @@ -38,13 +39,14 @@ public String showCart(Model model) {

@PreAuthorize("hasAuthority({'MEMBER'})")
@PostMapping("/add")
public String addItem(@ModelAttribute @Valid CartItemRequest cartItemRequests) {
public String addItem(@ModelAttribute @Valid CartItemRequest cartItemRequests, HttpServletRequest req) {
RsData<CartItem> result = cartService.addCartItem(rq.getMember(), cartItemRequests);

if(result.isFail())
return rq.redirectWithMsg("/trendpick/products/list?main-category=상의",result);
return rq.historyBack(result);

return rq.redirectWithMsg("/trendpick/usr/cart/list", result);
String referer = req.getHeader("referer");
return rq.redirectWithMsg(referer, result);
}

@PreAuthorize("hasAuthority({'MEMBER'})")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,14 @@ public class OrderController {
@PreAuthorize("hasAuthority({'MEMBER'})")
@GetMapping("{orderId}/form")
public String showOrderForm(@PathVariable("orderId") Long orderId, Model model){
Order order = orderService.findById(orderId);
if(order.getPaymentKey() != null || order.getOrderState().equals("주문취소"))
RsData<Order> result = orderService.getOrderFormData(orderId);
if(result.getResultCode().equals("F-1"))
return rq.historyBack("주문중 오류가 발생했습니다. 다시 한 번 시도해주세요.");

if(result.getResultCode().equals("F-2"))
return rq.redirectWithMsg("/", "이미 처리된 주문입니다.");
model.addAttribute("order", order);

model.addAttribute("order", result.getData());
return "trendpick/orders/order-form";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,6 @@ public void cancel() {
orderItem.cancel();
}

public void cancelTemp() {
this.orderStatus = OrderStatus.TEMP;
this.delivery.canceledDelivery();
for (OrderItem orderItem : this.orderItems) {
orderItem.cancel();
}
}

public String getOrderState(){
return switch (orderStatus.getValue()){
case "ORDERED"->"결제완료";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package project.trendpick_pro.domain.orders.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import project.trendpick_pro.domain.orders.entity.Order;

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

public interface OrderRepository extends JpaRepository<Order, Long>, OrderRepositoryCustom {

@Query("select o from Order o " +
"where o.paymentKey IS NULL " +
"and o.createdDate <= :expireDate")
List<Order> findAllByPaymentKeyIsNullAndCreatedDateIsBefore(@Param("expireDate") LocalDateTime expireDate, Pageable pageable);
Page<Order> findAllByPaymentKeyIsNullAndCreatedDateIsBefore(@Param("expireDate") LocalDateTime expireDate, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ public interface OrderService {
Order findById(Long id);
Page<OrderResponse> findCanceledOrders(Member member, int offset);
List<OrderItem> findAllByCreatedDateBetweenOrderByIdAsc(LocalDateTime fromDate, LocalDateTime toDate);
RsData<Order> getOrderFormData(Long orderId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,22 @@ public List<OrderItem> findAllByCreatedDateBetweenOrderByIdAsc(LocalDateTime fro
return orderItemRepository.findAllByCreatedDateBetween(fromDate, toDate);
}

public RsData<Order> getOrderFormData(Long orderId) {
Order order;
try{
order = findById(orderId);
if(order.getPaymentKey() != null || order.getOrderState().equals("주문취소"))
return RsData.of("F-2", "이미 처리된 주문입니다.");

if(order.getOrderItems().isEmpty())
return RsData.of("F-1", "주문 중에 오류가 발생했습니다. 다시 시도해주세요");
} catch (OrderNotFoundException e){
return RsData.of("F-1", "주문 중에 오류가 발생했습니다. 다시 시도해주세요");
}

return RsData.of("S-1", "유효성 검증 성공", order);
}

private Page<OrderResponse> settingOrderByMemberStatus(Member member, int offset) {
Page<OrderResponse> findOrders;
PageRequest pageable = PageRequest.of(offset, 10);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,16 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.beans.factory.annotation.Qualifier;

import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

Expand All @@ -26,7 +22,7 @@
@Component
@RequiredArgsConstructor
@Slf4j
public class JobConfig {
public class JobScheduler {
private final JobLauncher jobLauncher; //job을 실행시키는 주체
@Qualifier("makeRecommendProductJob")
private final Job makeRecommendProductJob;
Expand Down Expand Up @@ -55,11 +51,11 @@ public void performMakeRecommendProductJob() throws Exception {
log.info(execution.getStatus().toString());
}

// 매일 02시에 전날 생성된 주문 객체중 결제 처리가 안된 객체를 일괄 삭제 처리한다.
@Scheduled(cron = "0 0 2 * * *")
// 10분마다 체크해서 주문이 생성된지 30분 이상 지났는데 결제 처리가 없으면 주문을 취소상태로 변경한다.
@Scheduled(fixedRate = 1000 * 60 * 10)
public void performCancelOrderJob() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
LocalDateTime date = LocalDateTime.now().minusDays(1).with(LocalTime.MAX); //전날 11:59
// LocalDateTime fake = LocalDateTime.now().plusDays(1); //테스트용
LocalDateTime date = LocalDateTime.now().minusMinutes(30);
// LocalDateTime date = LocalDateTime.now().plusDays(1); //테스트용

JobParameters param = new JobParametersBuilder()
.addLocalDateTime("date", date) //전날 11:59
Expand All @@ -69,7 +65,7 @@ public void performCancelOrderJob() throws JobInstanceAlreadyCompleteException,

}

// 매일 04시에 일일정산을 통해 월 정산을 갱신해준다.
// 매일 04시에 당월의 주문 목록을 복사해서 정산용 주문 목록으로 만들어 저장한다.
@Scheduled(cron = "0 0 4 * * *") // 실제 코드
public void performMakeRebateDataJob() throws Exception {
String yearMonth = getPerformMakeRebateDataJobParam1Value(); // 실제 코드
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public class CancelOrderJobConfig{
public Job cancelOrderJob(Step cancelOrderStep, JobRepository jobRepository) throws Exception {
return new JobBuilder("cancelOrderJob", jobRepository)
.start(cancelOrderStep)
// .incrementer(new RunIdIncrementer()) //계속해서 id 업데이트 (내용이같아도)
.incrementer(new RunIdIncrementer()) //계속해서 id 업데이트 (내용이같아도)
.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ public OrderMaterial(Long productId, Integer quantity, String size, String color
}

public OrderMaterial(CartItem cartItem, String code){
new OrderMaterial(cartItem.getProduct().getId(), cartItem.getQuantity(), cartItem.getSize(), cartItem.getColor(), code);
this.productId = cartItem.getProduct().getId();
this.quantity = cartItem.getQuantity();
this.size = cartItem.getSize();
this.color = cartItem.getColor();
this.code = code;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,12 @@ public List<OrderMaterial> findOrderMaterial(String code){
}

//주문 객쳉 생성 메시지 발행
@Transactional
public void publishOrderCreationMessage(String topic, String key, List<OrderMaterial> orderMaterials, String code) {
outboxMessageRepository.save(new OutboxMessage(topic, key, key, orderMaterials, code));
}

@Transactional
//주문 처리 메시지 발행
public void publishOrderProcessMessage(String topic, String message, String payload, String email) {
outboxMessageRepository.save(new OutboxMessage(topic, message, payload, email));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,11 @@ public RsData processPayment(String paymentKey, Long orderId, Integer amount, St

private void successPaymentProcess(String method, String paymentKey, Order order) {
order.connectPayment("TossPayments" + method, paymentKey);

for (OrderItem orderItem : order.getOrderItems()) {
favoriteTagService.updateTag(order.getMember(), orderItem.getProduct(), TagType.ORDER);
orderItem.getCouponCard().use(LocalDateTime.now()); //실제 쿠폰 사용 처리

if(orderItem.getCouponCard() != null)
orderItem.getCouponCard().use(LocalDateTime.now()); //실제 쿠폰 사용 처리
}
}

Expand Down

0 comments on commit 8c3667d

Please sign in to comment.