diff --git a/src/main/java/model/InvalidOperationException.java b/src/main/java/model/InvalidOperationException.java new file mode 100644 index 0000000..df49fc7 --- /dev/null +++ b/src/main/java/model/InvalidOperationException.java @@ -0,0 +1,7 @@ +package model; + +public class InvalidOperationException extends RuntimeException { + public InvalidOperationException(String message) { + super(message); + } +} diff --git a/src/main/java/model/Operation.java b/src/main/java/model/Operation.java index 72174b5..ac2db75 100644 --- a/src/main/java/model/Operation.java +++ b/src/main/java/model/Operation.java @@ -21,7 +21,7 @@ public class Operation { } if (date == null) { - throw new IllegalArgumentException("Не указана дата документа"); + throw new InvalidOperationException("Не указана дата документа"); } if (type == null) { @@ -99,11 +99,11 @@ public class Operation { public static Operation openingBalance(LocalDate date, Long id, Account destinationAccount, BigDecimal total) { if (destinationAccount == null) { - throw new IllegalArgumentException("Не указан счёт-приёмник"); + throw new InvalidOperationException("Не указан счёт-приёмник"); } if (total == null) { - throw new IllegalArgumentException("Не указана сумма документа"); + throw new InvalidOperationException("Не указана сумма документа"); } return new Operation(date, id, OperationType.OPENING_BALANCE, null, destinationAccount, total); diff --git a/src/main/java/net/sytes/kashey/easymoney/api/ApiExceptionHandler.java b/src/main/java/net/sytes/kashey/easymoney/api/ApiExceptionHandler.java index 89133b5..8b88d7e 100644 --- a/src/main/java/net/sytes/kashey/easymoney/api/ApiExceptionHandler.java +++ b/src/main/java/net/sytes/kashey/easymoney/api/ApiExceptionHandler.java @@ -1,6 +1,7 @@ package net.sytes.kashey.easymoney.api; import model.InvalidAccountNameException; +import model.InvalidOperationException; import org.springframework.http.HttpStatus; import org.springframework.http.ProblemDetail; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -26,4 +27,9 @@ public class ApiExceptionHandler { public ProblemDetail handleInvalidAccountName(InvalidAccountNameException exception) { return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, exception.getMessage()); } + + @ExceptionHandler(InvalidOperationException.class) + public ProblemDetail handleInvalidOperation(InvalidOperationException exception) { + return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, exception.getMessage()); + } } \ No newline at end of file diff --git a/src/main/java/net/sytes/kashey/easymoney/api/CreateOpeningBalanceRequest.java b/src/main/java/net/sytes/kashey/easymoney/api/CreateOpeningBalanceRequest.java new file mode 100644 index 0000000..5c252c7 --- /dev/null +++ b/src/main/java/net/sytes/kashey/easymoney/api/CreateOpeningBalanceRequest.java @@ -0,0 +1,7 @@ +package net.sytes.kashey.easymoney.api; + +import java.math.BigDecimal; +import java.time.LocalDate; + +public record CreateOpeningBalanceRequest(LocalDate date, Long accountId, BigDecimal amount) { +} diff --git a/src/main/java/net/sytes/kashey/easymoney/api/OperationController.java b/src/main/java/net/sytes/kashey/easymoney/api/OperationController.java index 977d40b..5ae6cbc 100644 --- a/src/main/java/net/sytes/kashey/easymoney/api/OperationController.java +++ b/src/main/java/net/sytes/kashey/easymoney/api/OperationController.java @@ -1,26 +1,48 @@ package net.sytes.kashey.easymoney.api; +import model.Account; +import model.InvalidOperationException; import model.Operation; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; +import org.jspecify.annotations.NonNull; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import service.AccountService; import service.OperationService; +import java.net.URI; + @RestController @RequestMapping("/api/operations") public class OperationController { - private final OperationService service; - public OperationController(OperationService service) { - this.service = service; + private final OperationService operationService; + private final AccountService accountService; + + public OperationController(OperationService service, AccountService accountService) { + this.operationService = service; + this.accountService = accountService; } @GetMapping("/{id}") public OperationResponse getById(@PathVariable("id") Long id) { - Operation operation = service.getById(id); + Operation operation = operationService.getById(id); + return getOperationResponse(operation); + } + @PostMapping("/opening-balance") + public ResponseEntity<@NonNull OperationResponse> createOpeningBalance(@RequestBody CreateOpeningBalanceRequest request) { + if (request.accountId() == null) { + throw new InvalidOperationException("Не указан ID счёта"); + } + Account account = accountService.getById(request.accountId()); + Operation operation = operationService.createOpeningBalance(request.date(), account, request.amount()); + OperationResponse response = getOperationResponse(operation); + URI location = URI.create("/api/operations/" + operation.getId()); + return ResponseEntity.created(location).body(response); + } + + private OperationResponse getOperationResponse(Operation operation) { return new OperationResponse( operation.getId(), operation.getDate(), @@ -28,7 +50,6 @@ public class OperationController { operation.getSourceAccount() == null ? null : operation.getSourceAccount().getId(), operation.getDestinationAccount() == null ? null : operation.getDestinationAccount().getId(), operation.getTotal(), - service.isPosted(operation) - ); + operationService.isPosted(operation)); } } \ No newline at end of file diff --git a/src/main/java/service/AccountService.java b/src/main/java/service/AccountService.java index b9491a8..7d10b05 100644 --- a/src/main/java/service/AccountService.java +++ b/src/main/java/service/AccountService.java @@ -12,13 +12,13 @@ public class AccountService { this.accountJournal = accountJournal; } - public Account create(String name) { + public synchronized Account create(String name) { Account newAccount = new Account(counterId++, name); accountJournal.saveAccount(newAccount); return newAccount; } - public Account getById(Long id) { + public synchronized Account getById(Long id) { Account account = accountJournal.getAccountById(id); if (account == null) { throw new AccountNotFoundException(id); diff --git a/src/main/java/service/OperationService.java b/src/main/java/service/OperationService.java index 9fea421..a03e346 100644 --- a/src/main/java/service/OperationService.java +++ b/src/main/java/service/OperationService.java @@ -1,14 +1,18 @@ package service; +import model.Account; import model.Operation; import model.OperationJournal; +import java.math.BigDecimal; +import java.time.LocalDate; import java.util.Objects; public class OperationService { private final OperationJournal journal; private final Ledger ledger; + private Long counterId = 0L; public OperationService(OperationJournal journal, Ledger ledger) { @@ -20,34 +24,40 @@ public class OperationService { ); } - public void save(Operation operation) { + public synchronized void save(Operation operation) { journal.saveOperation(operation); } - public void post(Long operationId) { + public synchronized void post(Long operationId) { post(requiredOperation(operationId)); } - public void post(Operation operation) { + public synchronized void post(Operation operation) { ledger.post(operation); journal.saveOperation(operation); } - public void unpost(Long operationId) { + public synchronized void unpost(Long operationId) { ledger.unpost(requiredOperation(operationId).getId()); } - public boolean isPosted(Operation operation) { + public synchronized boolean isPosted(Operation operation) { if (operation == null) { throw new IllegalArgumentException("Не указан документ"); } return ledger.isPosted(operation.getId()); } - public Operation getById(Long operationId) { + public synchronized Operation getById(Long operationId) { return requiredOperation(operationId); } + public synchronized Operation createOpeningBalance(LocalDate date, Account account, BigDecimal amount) { + Operation operation = Operation.openingBalance(date, counterId++, account, amount); + journal.saveOperation(operation); + return operation; + } + private Operation requiredOperation(Long operationId) { Operation operation = journal.getOperationById(operationId); diff --git a/src/test/java/net/sytes/kashey/easymoney/api/OperationControllerTest.java b/src/test/java/net/sytes/kashey/easymoney/api/OperationControllerTest.java index 5b867d0..a7f1f39 100644 --- a/src/test/java/net/sytes/kashey/easymoney/api/OperationControllerTest.java +++ b/src/test/java/net/sytes/kashey/easymoney/api/OperationControllerTest.java @@ -1,5 +1,8 @@ package net.sytes.kashey.easymoney.api; +import model.Account; +import model.Operation; +import model.OperationType; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; @@ -7,9 +10,20 @@ import org.springframework.context.annotation.Import; import net.sytes.kashey.easymoney.config.AccountingConfig; +import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import service.AccountService; +import service.Ledger; +import service.OperationService; +import tools.jackson.databind.ObjectMapper; +import java.math.BigDecimal; +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @WebMvcTest(OperationController.class) @@ -18,6 +32,15 @@ class OperationControllerTest { @Autowired private MockMvc mockMvc; + @Autowired + private AccountService accountService; + @Autowired + private ObjectMapper objectMapper; + @Autowired + private OperationService operationService; + @Autowired + private Ledger ledger; + @Test void gettingUnknownOperationReturnsNotFound() throws Exception { @@ -28,4 +51,113 @@ class OperationControllerTest { .andExpect(jsonPath("$.detail") .value("Операция не найдена: 999")); } + + @Test + void creatingOpeningBalanceStoresUnpostedOperation() throws Exception { + // Given + LocalDate date = LocalDate.of(2026, 10, 22); + Account account = accountService.create("Карта"); + CreateOpeningBalanceRequest openingBalanceRequest = + new CreateOpeningBalanceRequest(date, account.getId(), new BigDecimal(15000)); + String body = objectMapper.writeValueAsString(openingBalanceRequest); + + // When / Then + MvcResult result = mockMvc.perform(post("/api/operations/opening-balance") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) + .andExpect(status().isCreated()) + .andExpect(header().exists("Location")) + .andExpect(jsonPath("$.date").value(date.toString())) + .andExpect(jsonPath("$.type").value(OperationType.OPENING_BALANCE.toString())) + .andExpect(jsonPath("$.destinationAccountId", Long.class).value(account.getId())) + .andExpect(jsonPath("$.sourceAccountId").doesNotExist()) + .andExpect(jsonPath("$.total", BigDecimal.class).value(new BigDecimal(15000))) + .andExpect(jsonPath("$.posted").value(false)) + .andReturn(); + + OperationResponse operationResponse = objectMapper.readValue(result.getResponse().getContentAsString(), + OperationResponse.class); + + Long operationResponseId = operationResponse.id(); + + String location = result.getResponse().getHeader("Location"); + assertEquals("/api/operations/" + operationResponseId, location); + + Operation savedOperation = operationService.getById(operationResponseId); + + assertEquals(date, savedOperation.getDate()); + assertEquals(account, savedOperation.getDestinationAccount()); + assertEquals(0, new BigDecimal("15000").compareTo(savedOperation.getTotal())); + assertEquals(0, BigDecimal.ZERO.compareTo(ledger.balance(account, date)), + "Создание документа без проведения не должно менять остаток"); + } + + @Test + void creatingOpeningBalanceWithoutDateReturnsBadRequest() throws Exception { + // Given + Account account = accountService.create("Карта"); + CreateOpeningBalanceRequest openingBalanceRequest = + new CreateOpeningBalanceRequest(null, account.getId(), new BigDecimal(15000)); + String body = objectMapper.writeValueAsString(openingBalanceRequest); + + // When / Then + mockMvc.perform(post("/api/operations/opening-balance") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail").value("Не указана дата документа")) + .andExpect(jsonPath("$.status").value(400)); + } + + @Test + void creatingOpeningBalanceWithoutAmountReturnsBadRequest() throws Exception { + // Given + LocalDate date = LocalDate.of(2026, 10, 22); + Account account = accountService.create("Карта"); + CreateOpeningBalanceRequest openingBalanceRequest = + new CreateOpeningBalanceRequest(date, account.getId(), null); + String body = objectMapper.writeValueAsString(openingBalanceRequest); + + // When / Then + mockMvc.perform(post("/api/operations/opening-balance") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail").value("Не указана сумма документа")) + .andExpect(jsonPath("$.status").value(400)); + } + + @Test + void creatingOpeningBalanceWithoutAccountIdReturnsBadRequest() throws Exception { + // Given + LocalDate date = LocalDate.of(2026, 10, 22); + CreateOpeningBalanceRequest openingBalanceRequest = + new CreateOpeningBalanceRequest(date, null, new BigDecimal(15000)); + String body = objectMapper.writeValueAsString(openingBalanceRequest); + + // When / Then + mockMvc.perform(post("/api/operations/opening-balance") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.detail").value("Не указан ID счёта")) + .andExpect(jsonPath("$.status").value(400)); + } + + @Test + void creatingOpeningBalanceWithUnknownAccountIdReturnsNotFound() throws Exception { + // Given + LocalDate date = LocalDate.of(2026, 10, 22); + CreateOpeningBalanceRequest openingBalanceRequest = + new CreateOpeningBalanceRequest(date, 999L, new BigDecimal(15000)); + String body = objectMapper.writeValueAsString(openingBalanceRequest); + + // When / Then + mockMvc.perform(post("/api/operations/opening-balance") + .contentType(MediaType.APPLICATION_JSON) + .content(body)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.detail").value("Счет не найден: 999")) + .andExpect(jsonPath("$.status").value(404)); + } } \ No newline at end of file diff --git a/src/test/java/service/AccountServiceTest.java b/src/test/java/service/AccountServiceTest.java new file mode 100644 index 0000000..f957513 --- /dev/null +++ b/src/test/java/service/AccountServiceTest.java @@ -0,0 +1,56 @@ +package service; + +import model.Account; +import model.AccountJournal; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.*; + +class AccountServiceTest { + + @Test + void concurrentAccountCreationAssignsUniqueIdsAndStoresAllAccounts() throws Exception { + // Given + AccountService service = new AccountService(new AccountJournal()); + int taskCount = 100; + CountDownLatch start = new CountDownLatch(1); + List accounts = new ArrayList<>(); + + try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { + List> futures = new ArrayList<>(); + for (int i = 0; i < taskCount; i++) { + String name = "Счёт " + i; + futures.add(executor.submit(() -> { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Не получен сигнал старта"); + } + return service.create(name); + })); + } + + // When + start.countDown(); + for (Future future : futures) { + accounts.add(future.get(10, TimeUnit.SECONDS)); + } + } + + // Then + var ids = new HashSet(); + for (Account account : accounts) { + assertNotNull(account.getId(), "Каждый счёт должен получить ID"); + ids.add(account.getId()); + assertSame(account, service.getById(account.getId()), + "Каждый созданный счёт должен сохраняться под своим ID"); + } + assertEquals(taskCount, ids.size(), "ID параллельно созданных счетов должны быть уникальными"); + } +}