Добавил тесты проведения, повторного проведения и изменения сумм операций

This commit is contained in:
Kashey committed 2026-10-19 14:05:42 +03:00
1 parent d264ed6583
commit 8af851a49a
18 files changed
+303 -35

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
import model.*;
import service.Ledger;
import service.OperationService;
import java.math.BigDecimal;
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
Account card = new Account(1L, "Сбер карта");
Account cash = new Account(2L, "Наличные");
Operation operation1 = Operation.openingBalance(LocalDate.now(), 101L, card, new BigDecimal(15000));
Operation operation2 = Operation.openingBalance(LocalDate.now(), 201L, cash, new BigDecimal(3000));
Ledger ledger = new Ledger();
OperationJournal journal = new OperationJournal();
OperationService operationService = new OperationService(journal, ledger);
operationService.post(operation1);
operationService.post(operation2);
System.out.println("Ввод начального остатка");
printAccountBalance(card, ledger);
printAccountBalance(cash, ledger);
Operation operation3 = Operation.transfer(LocalDate.now(), 301L, card, cash, new BigDecimal(2000));
operationService.post(operation3);
System.out.println("Перемещение");
printAccountBalance(card, ledger);
printAccountBalance(cash, ledger);
Operation operation4 = Operation.expense(LocalDate.now(), 401L, card);
OperationLine operationLine = new OperationLine(new Category(1L, "Coca cola"), new BigDecimal(200));
operation4.addLine(operationLine);
operationLine = new OperationLine(new Category(2L, "Pizza"), new BigDecimal(800));
operation4.addLine(operationLine);
operationService.post(operation4);
Operation operation5 = Operation.expense(LocalDate.now(), 404L, cash);
operationLine = new OperationLine(new Category(3L, "Mineral water"), new BigDecimal(60));
operation5.addLine(operationLine);
operationService.post(operation5);
System.out.println("Расход");
printAccountBalance(card, ledger);
printAccountBalance(cash, ledger);
operationLine = new OperationLine(new Category(3L, "Mineral water"), new BigDecimal(100));
operation5.replaceLine(0, operationLine);
operationService.post(operation5);
System.out.println("Замена строки");
printAccountBalance(card, ledger);
printAccountBalance(cash, ledger);
// operation5.removeLine(0);
// operationService.post(operation5);
// System.out.println("Удаление строк");
Operation operation6 = Operation.income(LocalDate.now(), 504L, card);
operationLine = new OperationLine(new Category(4L, "Salary"), new BigDecimal(20000));
operation6.addLine(operationLine);
operationService.post(operation6);
System.out.println("Приход");
printAccountBalance(card, ledger);
printAccountBalance(cash, ledger);
printPosted(operation6, operationService);
System.out.println("Распроведение прихода");
operationService.unpost(operation6.getId());
printAccountBalance(card, ledger);
printAccountBalance(cash, ledger);
printPosted(operation6, operationService);
}
public static void printAccountBalance(Account account, Ledger ledger) {
System.out.println("Баланс " + account.getName() + " = " + ledger.balance(account, LocalDate.now()));
}
public static void printPosted(Operation operation, OperationService operationService) {
System.out.println("Документ с id = " + operation.getId() +
(operationService.isPosted(operation) ? " проведен" : " не проведен"));
}
}
+40
View File
@@ -0,0 +1,40 @@
package model;
import java.util.Objects;
public class Account {
private String name;
private final Long id;
public Account(Long id, String name) {
this.id = Objects.requireNonNull(id, "Не указан идентификатор");
setName(name);
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Не указано имя счёта");
}
this.name = name;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return Objects.equals(id, account.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
+41
View File
@@ -0,0 +1,41 @@
package model;
import java.util.Objects;
public class Category {
private String name;
private final Long id;
public Category(Long id, String name) {
this.id = Objects.requireNonNull(id, "Не указан идентификатор");
setName(name);
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Не указано имя категории");
}
this.name = name;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
return Objects.equals(id, category.id);
}
@Override
public int hashCode() {
return id.hashCode();
}
}
+52
View File
@@ -0,0 +1,52 @@
package model;
import java.math.BigDecimal;
import java.time.LocalDate;
public class LedgerEntry {
private final LocalDate date;
private final Long operationId;
private final Account account;
private final Category category;
private final BigDecimal deltaAmount;
public LedgerEntry(LocalDate date, Long operationId, Account account, Category category, BigDecimal deltaAmount) {
if (date == null) {
throw new IllegalArgumentException("Не указана дата движения");
}
if (operationId == null) {
throw new IllegalArgumentException("Не указан ID операции");
}
if (account == null) {
throw new IllegalArgumentException("Не указан счёт движения");
}
if (deltaAmount == null) {
throw new IllegalArgumentException("Не указана сумма движения");
}
this.date = date;
this.operationId = operationId;
this.account = account;
this.category = category;
this.deltaAmount = deltaAmount;
}
public BigDecimal getDeltaAmount() {
return deltaAmount;
}
public LocalDate getDate() {
return date;
}
public Account getAccount() {
return account;
}
public Long getOperationId() {
return operationId;
}
}
+156
View File
@@ -0,0 +1,156 @@
package model;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
public class Operation {
private final LocalDate date;
private final Long id;
private final OperationType type;
private final Account sourceAccount;
private final Account destinationAccount;
private final BigDecimal total;
private final List<OperationLine> lines = new ArrayList<>();
private Operation(LocalDate date, Long id, OperationType type, Account sourceAccount, Account destinationAccount, BigDecimal total) {
if (id == null) {
throw new IllegalArgumentException("Не указан ID документа");
}
if (date == null) {
throw new IllegalArgumentException("Не указана дата документа");
}
if (type == null) {
throw new IllegalArgumentException("Не указан вид документа");
}
this.date = date;
this.id = id;
this.type = type;
this.sourceAccount = sourceAccount;
this.destinationAccount = destinationAccount;
this.total = total;
}
public LocalDate getDate() {
return date;
}
public Long getId() {
return id;
}
public OperationType getType() {
return type;
}
public Account getSourceAccount() {
return sourceAccount;
}
public Account getDestinationAccount() {
return destinationAccount;
}
public BigDecimal getTotal() {
if (type == OperationType.INFLOW || type == OperationType.OUTFLOW) {
BigDecimal result = BigDecimal.ZERO;
for (OperationLine line : lines) {
result = result.add(line.getAmount());
}
return result;
}
return total;
}
public List<OperationLine> getLines() {
return Collections.unmodifiableList(lines);
}
public void addLine(OperationLine line) {
if (line == null) {
throw new IllegalArgumentException("Не указана строка документа");
}
if (type != OperationType.INFLOW
&& type != OperationType.OUTFLOW) {
throw new IllegalArgumentException("Строки разрешены только для доходов и расходов");
}
lines.add(line);
}
public void replaceLine(int index, OperationLine line) {
if (line == null) {
throw new IllegalArgumentException("Не указана строка документа");
}
lines.set(index, line);
}
public void removeLine(int index) {
lines.remove(index);
}
public static Operation openingBalance(LocalDate date, Long id, Account destinationAccount, BigDecimal total) {
if (destinationAccount == null) {
throw new IllegalArgumentException("Не указан счёт-приёмник");
}
if (total == null) {
throw new IllegalArgumentException("Не указана сумма документа");
}
return new Operation(date, id, OperationType.OPENING_BALANCE, null, destinationAccount, total);
}
public static Operation income(LocalDate date, Long id, Account destinationAccount) {
if (destinationAccount == null) {
throw new IllegalArgumentException("Не указан счёт-приёмник");
}
return new Operation(date, id, OperationType.INFLOW, null, destinationAccount, null);
}
public static Operation expense(LocalDate date, Long id, Account sourceAccount) {
if (sourceAccount == null) {
throw new IllegalArgumentException("Не указан счёт-источник");
}
return new Operation(date, id, OperationType.OUTFLOW, sourceAccount, null, null);
}
public static Operation transfer(LocalDate date, Long id, Account sourceAccount, Account destinationAccount, BigDecimal total) {
if (sourceAccount == null) {
throw new IllegalArgumentException("Не указан счёт-источник");
}
if (destinationAccount == null) {
throw new IllegalArgumentException("Не указан счёт-приёмник");
}
if (sourceAccount
.equals(destinationAccount)) {
throw new IllegalArgumentException(
"Счёт-источник и счёт-приёмник должны различаться"
);
}
if (total == null) {
throw new IllegalArgumentException("Не указана сумма документа");
}
if (total.signum() <= 0) {
throw new IllegalArgumentException(
"Сумма перемещения должна быть больше нуля"
);
}
return new Operation(date, id, OperationType.MOVEMENT, sourceAccount, destinationAccount, total);
}
}
+48
View File
@@ -0,0 +1,48 @@
package model;
import java.time.LocalDate;
import java.util.*;
public class OperationJournal {
private final Map<Long, Operation> operations = new HashMap<>();
public void saveOperation(Operation operation) {
if (operation == null) {
throw new IllegalArgumentException("Не указана операция для сохранения в журнал");
}
operations.put(operation.getId(), operation);
}
public Operation getOperationById(Long id) {
return operations.get(id);
}
public List<Operation> getOperationsBetweenDates(LocalDate dateFrom, LocalDate dateTo) {
if (dateFrom == null || dateTo == null) {
throw new IllegalArgumentException(
"Необходимо указать начало и конец периода"
);
}
if (dateFrom.isAfter(dateTo)) {
throw new IllegalArgumentException(
"Начало периода не может быть позже конца"
);
}
List<Operation> result = new ArrayList<>();
for (Operation operation : operations.values()) {
if (!operation.getDate().isBefore(dateFrom) && !operation.getDate().isAfter(dateTo)) {
result.add(operation);
}
}
result.sort(Comparator.comparing(Operation::getDate).thenComparing(Operation::getId));
return result;
}
}
+34
View File
@@ -0,0 +1,34 @@
package model;
import java.math.BigDecimal;
public class OperationLine {
private final Category category;
private final BigDecimal amount;
public OperationLine(Category category, BigDecimal amount) {
if (category == null) {
throw new IllegalArgumentException("В строке не указана категория");
}
if (amount == null) {
throw new IllegalArgumentException("В строке не указана сумма");
}
if (amount.signum() <= 0) {
throw new IllegalArgumentException("Сумма строки должна быть больше нуля");
}
this.category = category;
this.amount = amount;
}
public Category getCategory() {
return category;
}
public BigDecimal getAmount() {
return amount;
}
}
+8
View File
@@ -0,0 +1,8 @@
package model;
public enum OperationType {
OPENING_BALANCE,
INFLOW,
OUTFLOW,
MOVEMENT
}
+126
View File
@@ -0,0 +1,126 @@
package service;
import model.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.time.LocalDate;
import java.util.List;
public class Ledger {
private final List<LedgerEntry> entries = new ArrayList<>();
public void post(Operation operation) {
if (operation == null) {
throw new IllegalArgumentException("Не указан документ");
}
OperationType operationType = operation.getType();
switch (operationType) {
case OPENING_BALANCE:
postOpeningBalance(operation);
break;
case OUTFLOW:
postOutflow(operation);
break;
case INFLOW:
postInflow(operation);
break;
case MOVEMENT:
postMovement(operation);
break;
default:
throw new IllegalArgumentException("Не поддерживается тип операции: " + operationType);
}
}
public void unpost(Long operationId) {
if (operationId == null) {
throw new IllegalArgumentException("Не указан ID операции");
}
entries.removeIf(entry -> entry.getOperationId().equals(operationId));
}
public boolean isPosted(Long operationId) {
if (operationId == null) {
throw new IllegalArgumentException("Не указан ID операции");
}
return entries.stream()
.anyMatch(entry -> entry.getOperationId().equals(operationId));
}
private void postOutflow(Operation operation) {
if (operation.getLines().isEmpty()) {
throw new IllegalArgumentException("Документ расхода не содержит строк");
}
ArrayList<LedgerEntry> newEntries = new ArrayList<>();
List<OperationLine> operationLines = operation.getLines();
for (OperationLine operationLine : operationLines) {
LedgerEntry ledgerEntry = new LedgerEntry(operation.getDate(), operation.getId(),
operation.getSourceAccount(), operationLine.getCategory(), operationLine.getAmount().negate());
newEntries.add(ledgerEntry);
}
entries.removeIf(entry -> entry.getOperationId().equals(operation.getId()));
entries.addAll(newEntries);
}
private void postInflow(Operation operation) {
if (operation.getLines().isEmpty()) {
throw new IllegalArgumentException("Документ прихода не содержит строк");
}
ArrayList<LedgerEntry> newEntries = new ArrayList<>();
List<OperationLine> operationLines = operation.getLines();
for (OperationLine operationLine : operationLines) {
LedgerEntry ledgerEntry = new LedgerEntry(operation.getDate(), operation.getId(),
operation.getDestinationAccount(), operationLine.getCategory(), operationLine.getAmount());
newEntries.add(ledgerEntry);
}
entries.removeIf(entry -> entry.getOperationId().equals(operation.getId()));
entries.addAll(newEntries);
}
private void postOpeningBalance(Operation operation) {
ArrayList<LedgerEntry> newEntries = new ArrayList<>();
LedgerEntry ledgerEntry = new LedgerEntry(operation.getDate(), operation.getId(),
operation.getDestinationAccount(), null, operation.getTotal());
newEntries.add(ledgerEntry);
entries.removeIf(entry -> entry.getOperationId().equals(operation.getId()));
entries.addAll(newEntries);
}
private void postMovement(Operation operation) {
ArrayList<LedgerEntry> newEntries = new ArrayList<>();
LedgerEntry ledgerEntryExpense = new LedgerEntry(operation.getDate(), operation.getId(),
operation.getSourceAccount(), null, operation.getTotal().negate());
newEntries.add(ledgerEntryExpense);
LedgerEntry ledgerEntryIncome = new LedgerEntry(operation.getDate(), operation.getId(),
operation.getDestinationAccount(), null, operation.getTotal());
newEntries.add(ledgerEntryIncome);
entries.removeIf(entry -> entry.getOperationId().equals(operation.getId()));
entries.addAll(newEntries);
}
public BigDecimal balance(Account account, LocalDate date) {
if (account == null) {
throw new IllegalArgumentException("Не указан счёт");
}
if (date == null) {
throw new IllegalArgumentException("Не указана дата расчёта остатка");
}
BigDecimal result = BigDecimal.ZERO;
for (LedgerEntry entry : entries) {
boolean sameAccount = entry.getAccount().equals(account);
boolean withinPeriod = !entry.getDate().isAfter(date);
if (sameAccount && withinPeriod) {
result = result.add(entry.getDeltaAmount());
}
}
return result;
}
}
@@ -0,0 +1,62 @@
package service;
import model.Operation;
import model.OperationJournal;
import java.util.Objects;
public class OperationService {
private final OperationJournal journal;
private final Ledger ledger;
public OperationService(OperationJournal journal, Ledger ledger) {
this.journal = Objects.requireNonNull(
journal, "Не указан журнал операций"
);
this.ledger = Objects.requireNonNull(
ledger, "Не указан регистр движений"
);
}
public void save(Operation operation) {
journal.saveOperation(operation);
}
public void post(Long operationId) {
post(requiredOperation(operationId));
}
public void post(Operation operation) {
ledger.post(operation);
journal.saveOperation(operation);
}
public void unpost(Long operationId) {
ledger.unpost(requiredOperation(operationId).getId());
}
public boolean isPosted(Operation operation) {
if (operation == null) {
throw new IllegalArgumentException("Не указан документ");
}
return ledger.isPosted(operation.getId());
}
private Operation requiredOperation(Long operationId) {
if (operationId == null) {
throw new IllegalArgumentException("Не указан ID операции");
}
Operation operation = journal.getOperationById(operationId);
if (operation == null) {
throw new IllegalArgumentException(
"Операция не найдена: " + operationId
);
}
return operation;
}
}