d4eb3effa7cec510a8b7fcd2c572f29b15613434
[demos/kafka/demos-kafka-payment-system-transfer] / src / main / java / de / juplo / kafka / payment / transfer / ports / TransferService.java
1 package de.juplo.kafka.payment.transfer.ports;
2
3
4 import de.juplo.kafka.payment.transfer.domain.Transfer;
5 import lombok.RequiredArgsConstructor;
6 import lombok.extern.slf4j.Slf4j;
7
8 import java.util.Optional;
9
10 import static de.juplo.kafka.payment.transfer.domain.Transfer.State.CHECKED;
11 import static de.juplo.kafka.payment.transfer.domain.Transfer.State.CREATED;
12
13
14 @Slf4j
15 @RequiredArgsConstructor
16 public class TransferService implements CreateTransferUseCase, HandleStateChangeUseCase, GetTransferUseCase
17 {
18   private final TransferRepository repository;
19   private final MessagingService messagingService;
20
21   @Override
22   public void create(Long id, Long payer, Long payee, Integer amount)
23   {
24     repository
25         .get(id)
26         .ifPresentOrElse(
27             stored -> log.info(
28                 "transfer already exisits: {}, ignoring: id={}, payer={}, payee={}, amount={}",
29                 stored,
30                 payer,
31                 payee,
32                 amount),
33             () ->
34             {
35               Transfer transfer =
36                   Transfer
37                       .builder()
38                       .id(id)
39                       .payer(payer)
40                       .payee(payee)
41                       .amount(amount)
42                       .build();
43
44               log.info("creating transfer: {}", transfer);
45               repository.store(transfer);
46               messagingService.send(transfer.getId(), CREATED);
47             });
48   }
49
50   @Override
51   public void handleStateChange(Long id, Transfer.State state)
52   {
53     get(id)
54         .ifPresentOrElse(
55             transfer ->
56             {
57               switch (state)
58               {
59                 case CREATED:
60
61                   transfer.setState(CREATED);
62                   repository.store(transfer);
63                   check(transfer);
64                   break;
65
66                 case CHECKED:
67
68                   transfer.setState(CHECKED);
69                   repository.store(transfer);
70                   // TODO: What's next...?
71                   break;
72
73                 default:
74
75                   log.warn("TODO: handle {} state {}", state.foreign ? "foreign" : "domain", state);
76               }
77             },
78             () -> log.error("unknown transfer: {}", id));
79   }
80
81   private void check(Transfer transfer)
82   {
83     // TODO: Do some time consuming checks...
84     messagingService.send(transfer.getId(), CHECKED);
85   }
86
87   public Optional<Transfer> get(Long id)
88   {
89     return repository.get(id);
90   }
91 }