Skip to content

Commit

Permalink
Calculate all charge types for limit amount
Browse files Browse the repository at this point in the history
  • Loading branch information
vokomarov committed Oct 20, 2024
1 parent f0122d5 commit 80e83af
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
19 changes: 17 additions & 2 deletions app/src/Service/Limit/LimitService.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,27 @@ public function calculate(array $limits): array
// TODO. Aggregate all limits using 1 query

foreach ($limits as $limit) {
$amount = $this->chargeRepository->totalByWalletPKAndTagPKs(
$tagIds = array_map(fn (Tag $tag) => (int) $tag->id, $limit->getTags());

$limitAmount = $this->chargeRepository->totalByWalletPKAndTagPKs(
$limit->walletId,
array_map(fn (Tag $tag) => (int) $tag->id, $limit->getTags()),
$tagIds,
$limit->type
);

// calculate total for opposite limit type to get the correction amount
$correctionAmount = $this->chargeRepository->totalByWalletPKAndTagPKs(
$limit->walletId,
$tagIds,
$limit->type == Limit::TYPE_INCOME ? Limit::TYPE_EXPENSE : Limit::TYPE_INCOME,
);

$amount = 0;

if ($correctionAmount < $limitAmount) {
$amount = round($limitAmount - $correctionAmount, 2);
}

$list[] = new WalletLimit($limit, $amount);
}

Expand Down
18 changes: 16 additions & 2 deletions tests/Feature/Controller/Wallets/Limits/LimitsControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,21 +110,35 @@ public function testListReturnLimits(): void
$chargesWithTwoTags = $this->chargeFactory->forUser($user)->forWallet($wallet)->withTags($tags->toArray())->createMany(4);

$chargesTotal = 0;
$chargesCorrectionTotal = 0;
foreach ($charges as $charge) {
/** @var \App\Database\Charge $charge */
if ($limit->type === $charge->type) {
$chargesTotal += $charge->amount;
} else {
$chargesCorrectionTotal += $charge->amount;
}
}
$chargesTotal = round($chargesTotal, 2);
if ($chargesCorrectionTotal >= $chargesTotal) {
$chargesTotal = 0.0;
} else {
$chargesTotal = round($chargesTotal - $chargesCorrectionTotal, 2);
}

$chargesWithTwoTagsTotal = 0;
$chargesWithTwoTagsCorrectionTotal = 0;
foreach ($chargesWithTwoTags as $charge) {
if ($limitWithTwoTags->type === $charge->type) {
$chargesWithTwoTagsTotal += $charge->amount;
} else {
$chargesWithTwoTagsCorrectionTotal += $charge->amount;
}
}
$chargesWithTwoTagsTotal = round($chargesWithTwoTagsTotal, 2);
if ($chargesWithTwoTagsCorrectionTotal >= $chargesWithTwoTagsTotal) {
$chargesWithTwoTagsTotal = 0;
} else {
$chargesWithTwoTagsTotal = round($chargesWithTwoTagsTotal - $chargesWithTwoTagsCorrectionTotal, 2);
}

$response = $this->withAuth($auth)->get("/wallets/{$wallet->id}/limits");

Expand Down

0 comments on commit 80e83af

Please sign in to comment.