Add file uploading to transaction creation

This commit is contained in:
2020-04-10 02:20:34 +02:00
parent 6ebbc47396
commit d8d75f67b4
33 changed files with 417 additions and 39 deletions

View File

@@ -0,0 +1,33 @@
package de.financer.controller;
import de.financer.model.File;
import de.financer.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FileController {
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionController.class);
@Autowired
private FileService fileService;
@GetMapping("/file")
public File getFile(Long fileId) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("GET /file got parameter: %s", fileId));
}
final File file = this.fileService.getFile(fileId);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("GET /file returns with %s", file.getName()));
}
return file;
}
}

View File

@@ -46,13 +46,14 @@ public class TransactionController {
String limit,
String order,
String taxRelevant,
String accountsAnd) {
String accountsAnd,
String hasFile) {
final String fromDecoded = ControllerUtil.urlDecode(fromAccountKey);
final String toDecoded = ControllerUtil.urlDecode(toAccountKey);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("GET /transactions/ got parameter: %s, %s, %s, %s, %s, %s - with order %s",
fromDecoded, toDecoded, periodId, limit, taxRelevant, accountsAnd, order));
LOGGER.debug(String.format("GET /transactions/ got parameter: %s, %s, %s, %s, %s, %s, %s - with order %s",
fromDecoded, toDecoded, periodId, limit, taxRelevant, accountsAnd, hasFile, order));
}
// Wrap the url parameters into a proper POJO so the service parameter list wont get polluted
@@ -66,6 +67,7 @@ public class TransactionController {
parameter.setOrder(order);
parameter.setTaxRelevant(taxRelevant);
parameter.setAccountsAnd(accountsAnd);
parameter.setHasFile(hasFile);
final Iterable<SearchTransactionsResponseDto> transactionSearchResponse =
this.transactionService.searchTransactions(parameter);
@@ -92,7 +94,9 @@ public class TransactionController {
Long.valueOf(requestDto.getAmount()),
requestDto.getDate(),
requestDto.getDescription(),
requestDto.getTaxRelevant());
requestDto.getTaxRelevant(),
requestDto.getFileName(),
requestDto.getFileContent());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("POST /transactions returns with %s", responseReason.name()));

View File

@@ -0,0 +1,7 @@
package de.financer.dba;
import de.financer.model.File;
import org.springframework.data.repository.CrudRepository;
public interface FileRepository extends CrudRepository<File, Long> {
}

View File

@@ -12,7 +12,8 @@ public interface TransactionRepositoryCustom {
Integer limit,
Order order,
Boolean taxRelevant,
boolean accountsAnd);
boolean accountsAnd,
Boolean hasFile);
Iterable<SearchTransactionsResponseDto> searchTransactions(String fql);
}

View File

@@ -30,11 +30,13 @@ public class TransactionRepositoryCustomImpl implements TransactionRepositoryCus
Integer limit,
Order order,
Boolean taxRelevant,
boolean accountsAnd) {
boolean accountsAnd,
Boolean hasFile) {
final CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
final CriteriaQuery<SearchTransactionsResponseDto> criteriaQuery = criteriaBuilder
.createQuery(SearchTransactionsResponseDto.class);
final Root<Transaction> fromTransaction = criteriaQuery.from(Transaction.class);
final SetJoin<Transaction, File> fileJoin = fromTransaction.join(Transaction_.files, JoinType.LEFT);
final List<Predicate> predicates = new ArrayList<>();
Predicate fromAccountPredicate = null;
@@ -74,6 +76,15 @@ public class TransactionRepositoryCustomImpl implements TransactionRepositoryCus
}
// else: both null, nothing to do
if (hasFile != null) {
if (hasFile) {
predicates.add(criteriaBuilder.isNotNull(fileJoin.get(File_.id)));
}
else {
predicates.add(criteriaBuilder.isNull(fileJoin.get(File_.id)));
}
}
criteriaQuery.where(predicates.toArray(new Predicate[]{}));
switch(order) {
@@ -92,7 +103,9 @@ public class TransactionRepositoryCustomImpl implements TransactionRepositoryCus
fromTransaction.get(Transaction_.description),
fromTransaction.get(Transaction_.amount),
fromTransaction.get(Transaction_.taxRelevant),
criteriaBuilder.isNotNull(fromTransaction.get(Transaction_.recurringTransaction))));
criteriaBuilder.isNotNull(fromTransaction.get(Transaction_.recurringTransaction)),
// This is kinda hacky as the relation between transaction and file is one-to-many
fileJoin.get(File_.id)));
final TypedQuery<SearchTransactionsResponseDto> query = this.entityManager.createQuery(criteriaQuery);

View File

@@ -27,6 +27,9 @@ public class FQLVisitorImpl extends FQLBaseVisitor<Predicate> {
this.froms = new HashMap<>();
this.froms.put(JoinKey.of(Transaction.class), this.criteriaRoot);
// We always need to join the join for HAS_FILE because it required for the select clause
FieldMapping.HAS_FILE.getJoinHandler().apply(this.froms, FieldMapping.HAS_FILE);
}
public CriteriaQuery<SearchTransactionsResponseDto> getCriteriaQuery() {
@@ -58,7 +61,8 @@ public class FQLVisitorImpl extends FQLBaseVisitor<Predicate> {
this.criteriaRoot.get(Transaction_.description),
this.criteriaRoot.get(Transaction_.amount),
this.criteriaRoot.get(Transaction_.taxRelevant),
criteriaBuilder.isNotNull(this.criteriaRoot.get(Transaction_.recurringTransaction))));
this.criteriaBuilder.isNotNull(this.criteriaRoot.get(Transaction_.recurringTransaction)),
this.froms.get(FieldMapping.HAS_FILE.getJoinKey()).get(FieldMapping.HAS_FILE.getAttributeName())));
}
@Override

View File

@@ -30,7 +30,9 @@ public enum FieldMapping {
JoinKey.of(Transaction.class), null, NotNullSyntheticHandler.class),
TAX_RELEVANT("taxRelevant", Transaction_.TAX_RELEVANT, Transaction.class, NoopJoinHandler.class,
JoinKey.of(Transaction.class), null, BooleanHandler.class);
JoinKey.of(Transaction.class), null, BooleanHandler.class),
HAS_FILE("hasFile", File_.ID, File.class, FileJoinHandler.class, JoinKey.of(File.class), null, NotNullSyntheticHandler.class);
/**
* The name of the field as used in FQL

View File

@@ -0,0 +1,28 @@
package de.financer.fql.join_handler;
import de.financer.fql.FieldMapping;
import de.financer.model.File;
import de.financer.model.Transaction;
import de.financer.model.Transaction_;
import javax.persistence.criteria.From;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.SetJoin;
import java.util.Map;
public class FileJoinHandler implements JoinHandler {
@Override
public Void apply(Map<JoinKey, From<?, ?>> joinKeyFromMap, FieldMapping fieldMapping) {
if (joinKeyFromMap.get(fieldMapping.getJoinKey()) == null) {
final SetJoin<Transaction, File> periodJoin = ((Root<Transaction>) joinKeyFromMap
.get(JoinKey.of(Transaction.class)))
.join(Transaction_.files, JoinType.LEFT);
joinKeyFromMap.put(fieldMapping.getJoinKey(), periodJoin);
}
return null;
}
}

View File

@@ -0,0 +1,28 @@
package de.financer.service;
import de.financer.ResponseReason;
import de.financer.dba.FileRepository;
import de.financer.model.File;
import de.financer.service.exception.FinancerServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FileService {
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionService.class);
@Autowired
private FileRepository fileRepository;
public File getFile(Long fileId) {
if (fileId == null || !this.fileRepository.existsById(fileId)) {
LOGGER.error(String.format("File with ID %s not found!", fileId));
throw new FinancerServiceException(ResponseReason.FILE_NOT_FOUND);
}
return this.fileRepository.findById(fileId).get();
}
}

View File

@@ -476,7 +476,9 @@ public class RecurringTransactionService {
LocalDate.now().format(DateTimeFormatter.ofPattern(this.financerConfig.getDateFormat())),
recurringTransaction.getDescription(),
recurringTransaction,
recurringTransaction.isTaxRelevant());
recurringTransaction.isTaxRelevant(),
null,
null);
}
@Transactional(propagation = Propagation.REQUIRED)

View File

@@ -55,19 +55,20 @@ public class TransactionService {
@Transactional(propagation = Propagation.REQUIRED)
public ResponseReason createTransaction(String fromAccountKey, String toAccountKey, Long amount, String date,
String description, Boolean taxRelevant
String description, Boolean taxRelevant, String fileName, String fileContent
) {
return this.createTransaction(fromAccountKey, toAccountKey, amount, date, description, null, taxRelevant);
return this.createTransaction(fromAccountKey, toAccountKey, amount, date, description, null,
taxRelevant, fileName, fileContent);
}
@Transactional(propagation = Propagation.REQUIRED)
public ResponseReason createTransaction(String fromAccountKey, String toAccountKey, Long amount, String date,
String description, RecurringTransaction recurringTransaction,
Boolean taxRelevant
Boolean taxRelevant, String fileName, String fileContent
) {
final Account fromAccount = this.accountService.getAccountByKey(fromAccountKey);
final Account toAccount = this.accountService.getAccountByKey(toAccountKey);
ResponseReason response = validateParameters(fromAccount, toAccount, amount, date);
ResponseReason response = validateParameters(fromAccount, toAccount, amount, date, fileName, fileContent);
// If we detected an issue with the given parameters return the first error found to the caller
if (response != null) {
@@ -79,6 +80,7 @@ public class TransactionService {
buildTransaction(fromAccount, toAccount, amount, description, date, recurringTransaction, taxRelevant);
transaction.setPeriods(getRelevantPeriods(transaction));
transaction.setFiles(Collections.singleton(buildFile(fileName, fileContent)));
fromAccount.setCurrentBalance(fromAccount.getCurrentBalance() + (this.ruleService
.getMultiplierFromAccount(fromAccount) * amount));
@@ -110,6 +112,15 @@ public class TransactionService {
return response;
}
private File buildFile(String fileName, String fileContent) {
final File file = new File();
file.setName(fileName);
file.setContent(fileContent);
return file;
}
private Set<Period> getRelevantPeriods(Transaction transaction) {
final Set<Period> periods = new HashSet<>();
final Period expensePeriod = this.periodService.getExpensePeriodForTransaction(transaction);
@@ -158,10 +169,13 @@ public class TransactionService {
* @param toAccount the to account
* @param amount the transaction amount
* @param date the transaction date
* @param fileName the name of the file
* @param fileContent the BASE64 encoded content of the file
*
* @return the first error found or <code>null</code> if all parameters are valid
*/
private ResponseReason validateParameters(Account fromAccount, Account toAccount, Long amount, String date) {
private ResponseReason validateParameters(Account fromAccount, Account toAccount, Long amount, String date,
String fileName, String fileContent) {
ResponseReason response = null;
if (fromAccount == null && toAccount == null) {
@@ -184,6 +198,11 @@ public class TransactionService {
} catch (DateTimeParseException e) {
response = ResponseReason.INVALID_DATE_FORMAT;
}
// A file is only considered valid if both name and content are not empty
} else if (StringUtils.isNotEmpty(fileName) && StringUtils.isEmpty(fileContent)) {
response = ResponseReason.INVALID_FILE_CONTENT;
} else if (StringUtils.isEmpty(fileName) && StringUtils.isNotEmpty(fileContent)) {
response = ResponseReason.INVALID_FILE_NAME;
}
return response;
@@ -298,6 +317,7 @@ public class TransactionService {
Account toAccount = null;
Boolean taxRelevant = null;
Boolean accountsAnd = Boolean.FALSE; // account values are OR conjunct by default
Boolean hasFile = null;
if (StringUtils.isNotEmpty(parameter.getPeriodId())) {
if (!NumberUtils.isCreatable(parameter.getPeriodId())) {
@@ -351,8 +371,16 @@ public class TransactionService {
}
}
if(StringUtils.isNotEmpty(parameter.getHasFile())) {
hasFile = BooleanUtils.toBooleanObject(parameter.getAccountsAnd());
if (hasFile == null) {
throw new FinancerServiceException(ResponseReason.INVALID_HAS_FILE_VALUE);
}
}
return this.transactionRepository.searchTransactions(period, fromAccount, toAccount, limit, order, taxRelevant,
accountsAnd);
accountsAnd, hasFile);
}
public Iterable<SearchTransactionsResponseDto> searchTransactions(String fql) {

View File

@@ -8,6 +8,7 @@ public class SearchTransactionsParameter {
private String order;
private String taxRelevant;
private String accountsAnd;
private String hasFile;
public String getFromAccountKey() {
return fromAccountKey;
@@ -64,4 +65,12 @@ public class SearchTransactionsParameter {
public void setAccountsAnd(String accountsAnd) {
this.accountsAnd = accountsAnd;
}
public String getHasFile() {
return hasFile;
}
public void setHasFile(String hasFile) {
this.hasFile = hasFile;
}
}

View File

@@ -0,0 +1,14 @@
CREATE TABLE file (
id BIGINT NOT NULL PRIMARY KEY IDENTITY,
name NVARCHAR(1000) NOT NULL,
content NVARCHAR(4000) NOT NULL
);
CREATE TABLE link_transaction_file (
id BIGINT NOT NULL PRIMARY KEY IDENTITY,
transaction_id BIGINT NOT NULL,
file_id BIGINT NOT NULL,
CONSTRAINT fk_link_transaction_file_transaction FOREIGN KEY (transaction_id) REFERENCES "transaction" (id),
CONSTRAINT fk_link_transaction_file_file FOREIGN KEY (file_id) REFERENCES file (id)
);

View File

@@ -0,0 +1,14 @@
CREATE TABLE file (
id BIGINT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
name VARCHAR(1000) NOT NULL,
content VARCHAR NOT NULL
);
CREATE TABLE link_transaction_file (
id BIGINT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
transaction_id BIGINT NOT NULL,
file_id BIGINT NOT NULL,
CONSTRAINT fk_link_transaction_file_transaction FOREIGN KEY (transaction_id) REFERENCES "transaction" (id),
CONSTRAINT fk_link_transaction_file_file FOREIGN KEY (file_id) REFERENCES file (id)
);