finnow/finnow-api/source/util/validation/draft.d

59 lines
2.5 KiB
D

module util.validation.draft;
import handy_http_primitives;
import std.datetime;
import transaction.data;
import transaction.dto;
import util.validation.common;
import account.data;
void validateDraftPayload(
TransactionVendorRepository vendorRepo,
TransactionCategoryRepository categoryRepo,
AccountRepository accountRepo,
in TransactionDraftPayload payload
) {
if (payload.amount && !payload.currencyCode) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Currency is required when saving an amount.");
}
if (payload.amount && payload.amount.value == 0) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Amount should be greater than 0.");
}
if (payload.timestamp) {
validateTimestampFormat(payload.timestamp.value);
}
if (payload.vendorId && !vendorRepo.existsById(payload.vendorId.value)) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Vendor doesn't exist.");
}
if (payload.categoryId && !categoryRepo.existsById(payload.categoryId.value)) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Category doesn't exist.");
}
if (payload.creditedAccountId && !accountRepo.existsById(payload.creditedAccountId.value)) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Credited account doesn't exist.");
}
if (payload.debitedAccountId && !accountRepo.existsById(payload.debitedAccountId.value)) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Debited account doesn't exist.");
}
validateTags(payload.tags);
if (payload.lineItems.length > 0) {
long lineItemsTotal = 0;
foreach (lineItem; payload.lineItems) {
if (lineItem.categoryId && !categoryRepo.existsById(lineItem.categoryId.value)) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Line item's category doesn't exist.");
}
if (lineItem.quantity == 0) {
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "Line item's quantity should greater than zero.");
}
for (ulong i = 0; i < lineItem.quantity; i++) {
lineItemsTotal += lineItem.valuePerItem;
}
}
if (payload.amount && lineItemsTotal != payload.amount.value) {
throw new HttpStatusException(
HttpStatus.BAD_REQUEST,
"Total of all line items doesn't equal the transaction's total."
);
}
}
}