Skip to content

Commit

Permalink
działa logika dzielenia wydatków z różną walutą
Browse files Browse the repository at this point in the history
  • Loading branch information
JanisBe committed Jun 5, 2024
1 parent 209856a commit 127668e
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 52 deletions.
43 changes: 2 additions & 41 deletions src/main/frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ <h2 mat-dialog-title>Rozliczenie dla grupy {{ data.group.groupName }}</h2>
<mat-dialog-content>
@if (data.debts) {
<div>
@for (settlement of data.debts | keyvalue; track settlement) {
@for (settlement of settlement | keyvalue; track settlement.value) {
<p> {{ settlement.key }}
@if (settlement.key !== 'PLN') {
<mat-checkbox (change)="calculate($event.checked)">przelicz do PLN</mat-checkbox>
<mat-checkbox (change)="calculateExchange($event.checked)">przelicz do PLN</mat-checkbox>
}
</p>
@for (debt of settlement.value; track debt) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {Debt} from "../../../model/debt";
})
export class SettlementDialogComponent implements OnInit {
private wasChanged: boolean;
private settlement: Settlement;
settlement: Settlement;

constructor(
public dialogRef: MatDialogRef<SettlementDialogComponent>,
Expand All @@ -51,7 +51,7 @@ export class SettlementDialogComponent implements OnInit {
// return debts.reduce((accumulator, curValue) => accumulator + curValue.amount, 0) > 0;
// } || calculateDebts(data.debts)

calculate(change: boolean) {
calculateExchange(change: boolean) {
if (change && !this.wasChanged) {
this.wasChanged = true;
let debts: Debt[] = []
Expand All @@ -67,11 +67,32 @@ export class SettlementDialogComponent implements OnInit {
result.forEach(transaction => {
this.settlement[transaction.currency].push(transaction);
});
this.recalculateDebts();
});
}

}

private recalculateDebts() {
Object.keys(this.settlement).forEach(currency => {
console.log(this.settlement[currency]);
let groupedTransactions = this.settlement[currency].reduce((acc, transaction) => {
const key = `${transaction.from.id}-${transaction.to.id}-${transaction.currency}`;
if (!acc[key]) {
acc[key] = {
from: transaction.from,
to: transaction.to,
amount: 0,
currency: transaction.currency
};
}
acc[key].amount += transaction.amount;
return acc;
}, {} as { [key: string]: Debt });

this.settlement[currency] = Object.values(groupedTransactions);
});
}
}

export interface SettlementDialogData {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/pl/janis/komornik/entities/Expense.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
@SqlResultSetMapping(name = "debtMapper",
classes = {@ConstructorResult(targetClass = UserBalance.class,
columns = {@ColumnResult(name = "userId"),
@ColumnResult(name = "balance")})
@ColumnResult(name = "balance"),
@ColumnResult(name = "currency")})
})
public class Expense {
// select debt.userTo.id as userId, sum(debt.amount) as balance from Expense e inner join e.debt debt " +
Expand Down
43 changes: 37 additions & 6 deletions src/main/java/pl/janis/komornik/service/NBPExchangeService.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package pl.janis.komornik.service;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import pl.janis.komornik.dto.DebtDto;
Expand All @@ -16,19 +18,48 @@
@Log4j2
@Service
public class NBPExchangeService {
LocalDate today = LocalDate.now();


public List<DebtDto> getExchangeRate(List<DebtDto> debts) throws RestClientException {
LocalDate today = LocalDate.now().minusDays(1);
String formattedDate = today.format(DateTimeFormatter.ISO_LOCAL_DATE);

List<DebtDto> result = new ArrayList<>();
debts.forEach(amount -> {
try {
DebtDto response = callNbpApi(amount);
if (response != null) {
result.add(response);
}
} catch (HttpClientErrorException e) {
throw new RuntimeException(e);
}
});
return result;
}

private DebtDto callNbpApi(DebtDto amount) {
int retryCount = 0;
DebtDto result = null;
int MAX_RETRIES = 5;
while (retryCount < MAX_RETRIES) {
String formattedDate = today.format(DateTimeFormatter.ISO_LOCAL_DATE);
String url = String.format("https://api.nbp.pl/api/exchangerates/rates/a/%s/%s/?format=json", amount.currency(), formattedDate);
RestTemplate restTemplate = new RestTemplate();
ExchangeRateResponse response = restTemplate.getForObject(url, ExchangeRateResponse.class);
if (response != null) {
result.add(new DebtDto(amount.from(), amount.to(), response.rates()[0].mid().multiply(amount.amount()).setScale(2, RoundingMode.DOWN), amount.currency()));
try {
ExchangeRateResponse response = restTemplate.getForObject(url, ExchangeRateResponse.class);
if (response != null) {
result = new DebtDto(amount.from(), amount.to(), response.rates()[0].mid().multiply(amount.amount()).setScale(2, RoundingMode.DOWN), "PLN");
break;
}
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
today = today.minusDays(1);
retryCount++;
} else {
throw e;
}
}
});
}
return result;
}
}

0 comments on commit 127668e

Please sign in to comment.