Skip to content

Commit

Permalink
fix: solve negative budget calc
Browse files Browse the repository at this point in the history
  • Loading branch information
jesusantguerrero committed Feb 17, 2024
1 parent 68ddcab commit f958734
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ protected function index(Request $request) {
return $model->withCurrentSavings($startDate);
}));


return inertia($this->templates['index'],
[
$resourceName => $this->parser($resources),
Expand Down
49 changes: 45 additions & 4 deletions app/Domains/Budget/Services/BudgetCategoryService.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use App\Domains\Budget\Data\CategoryData;
use App\Domains\Budget\Models\BudgetMonth;
use App\Domains\Transaction\Models\Transaction;
use App\Domains\Budget\Data\BudgetReservedNames;

class BudgetCategoryService
{
Expand Down Expand Up @@ -221,14 +222,53 @@ public function getCategoryActivity(Category $category, string $month)
$activity = 0;

if ($category->account) {
$transactions = $category->account->getMonthBalance($monthDate->format('Y-m'))->balance;
$transactions = $this->getCreditCardBalance($category->account, $monthDate->format('Y-m'))->balance;
} else {
$activity = $category->getMonthBalance($monthDate->format('Y-m'))?->balance;
}

// if ($monthDate->format('Y-m') == '2024-01') {
// dd($transactions, $activity);
// }

return ($activity + $transactions) ?? 0;
}

public function getCreditCardBalance(Account $account, string $yearMonth, bool $hasCategories = false)
{
if (!$account->resource_type_id) {
return $account->transactionLines()
->whereHas('transaction', fn ($q) => $q->where('status', Transaction::STATUS_VERIFIED))
->whereRaw("date_format(transaction_lines.date, '%Y-%m') = '$yearMonth'")
->selectRaw("COALESCE(SUM(amount * transaction_lines.type), 0) as balance")
->whereNot('categories.name', BudgetReservedNames::READY_TO_ASSIGN->value)
->leftJoin('categories', 'categories.id', '=', 'transaction_lines.category_id')
->when($hasCategories, fn ($q) => $q->whereRaw('(category_id IS NOT NULL AND category_id != 0)'))
->first();
} else {
return $account->creditLines()
->leftJoin('categories', 'categories.id', '=', 'transaction_lines.category_id')
->whereNot('categories.name', BudgetReservedNames::READY_TO_ASSIGN->value)
->whereRaw("date_format(date, '%Y-%m') = '$yearMonth'")
->sum(DB::raw("amount * type"));
}
}

public function getMonthPayments(Account $account, string $yearMonth)
{
if (!$account->resource_type_id) {
$result = $account->getVerifiedTransactionLines()
// ->where(fn ($q) =>
// $q->where('transaction_lines.category_id', 0)
// ->orWhereNull('transaction_lines.category_id')
// )
->whereRaw("date_format(transaction_lines.date, '%Y-%m') = '$yearMonth'")
->where('transaction_lines.type', 1);

return $result->first();
}
}

public function getCategoryInflow(Category $category, string $month)
{
$yearMonth = Carbon::createFromFormat('Y-m-d', $month)->format('Y-m');
Expand All @@ -239,7 +279,7 @@ public function getCategoryInflow(Category $category, string $month)
->whereHas('transaction', fn ($q) => $q->where('status', Transaction::STATUS_VERIFIED))
->whereRaw("date_format(transaction_lines.date, '%Y-%m') = '$yearMonth'")
->selectRaw("COALESCE(SUM(amount * type), 0) as balance")
->where('type', 1)
// ->where('type', 1)
->first()?->balance;
} else {
return $category->creditLines()
Expand All @@ -263,16 +303,17 @@ public function updateFundedSpending(Category $category, string $month)
{
$monthDate = Carbon::createFromFormat('Y-m-d', $month);
$transactions = 0;
$activity = 0;
$fromBudgets = 0;

if ($category->account) {
$yearMonth = $monthDate->format('Y-m');
$transactions = $category->account->getMonthFundedSpending($yearMonth)->balance;
$payments = $category->account->getMonthPayments($yearMonth)->balance ?? 0;
$payments = $this->getMonthPayments($category->account, $yearMonth)->balance ?? 0;

$fundedSpending = ($transactions * -1) ?? 0;

echo "$fundedSpending/$payments" . PHP_EOL;

BudgetMonth::updateOrCreate([
'category_id' => $category->id,
'team_id' => $category->team_id,
Expand Down
35 changes: 13 additions & 22 deletions app/Domains/Budget/Services/BudgetRolloverService.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,28 +149,19 @@ private function moveReadyToAssign($teamId, $month, $overspending = 0, $fundedFr
->toFloat();

echo "TBB: " . $TBB . " budgeted: " . $results?->budgeted . " Available: " . $available . " Leftover: ". $leftover . " overspending: " . $overspending . PHP_EOL;
// dd(collect(explode(",", $results->description))->map(function ($line) {

// $cat = explode(":", $line);
// return [
// "index" => $cat[0],
// "name" => $cat[1],
// "value" => $cat[2] ?? 0,
// ];
// }
// )->sortBy("index")->map(fn ($item) => $item['index']. " ". $item["name"] . ":" . $item["value"]));
// dd($results->description);

// if ($overspending > 0 && $leftover > 0) {
// $overspendingCopy = $overspending;
// $overspending = $overspending > $leftover ? $overspending - $leftover : 0;
// $leftover = $overspendingCopy >= $leftover ? 0 : $leftover - $overspendingCopy;
// }

// if ($leftover < 0) {
// $overspending = $overspending > abs($leftover);
// $leftover = 0;
// }

if ($overspending > 0 && $leftover > 0) {
$overspendingCopy = $overspending;
$overspending = $overspending > $leftover ? $overspending - $leftover : 0;
$leftover = $overspendingCopy >= $leftover ? 0 : $leftover - $overspendingCopy;
// 300 = 100 >= 300 ? 0 : 300 - 100 = 200
}

if ($leftover <= 0) {
$leftover = $leftover - $overspending;
}

echo "TBB: " . $TBB . " budgeted: " . $results?->budgeted . " Available: " . $available . " Leftover: ". $leftover . " overspending: " . $overspending . PHP_EOL;

// Close current month

Expand Down
1 change: 0 additions & 1 deletion app/Domains/Transaction/Services/TransactionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,6 @@ public static function getCategoryExpenseDetails($teamId, $startDate, $endDate,
->join('payees', 'payees.id', 'transaction_lines.payee_id')
->leftJoin('categories as group', 'group.id', 'categories.parent_id')
->orderByDesc('transaction_lines.date')
->
->get();

return [
Expand Down
16 changes: 0 additions & 16 deletions resources/js/Pages/Finance/Budget.vue
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,6 @@ const goToday = () => {
pageState.dates.startDate = startOfMonth(new Date());
executeSearchWithDelay();
};
const budgetAccountsTotal = computed(() => {
return props.accounts.reduce((total, account) => {
return account.balance_type == 'CREDIT'
? total
: exactMath.add(total, account?.balance)
}, 0)
})
</script>

<template>
Expand Down Expand Up @@ -243,14 +235,6 @@ const budgetAccountsTotal = computed(() => {
]"

/>
<div class="p-4 space-y-2 border border-transparent rounded bg-base-lvl-3">
<p v-for="(typeTotal, typeName) in distribution">
<span class="font-bold capitalize">
{{ typeName }}:
</span>
<MoneyPresenter :value="typeTotal" />
</p>
</div>
</div>
</template>
</FinanceTemplate>
Expand Down
2 changes: 1 addition & 1 deletion resources/js/Pages/Finance/Partials/BudgetCategories.vue
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const saveReorder = (categories: ICategory[]) => {
@cancel=""
/>
<Draggable
class="w-full space-y-2 overflow-auto dragArea list-group ic-scroller"
class="w-full space-y-0.5 overflow-auto dragArea list-group ic-scroller"
:list="visibleCategories"
handle=".handle"
@end="saveReorder(visibleCategories)"
Expand Down
6 changes: 3 additions & 3 deletions resources/js/domains/budget/budgetTotals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const getCategoriesTotals = (categories: Record<string, any>, config = {
categoryTotals.budgetedSpending = ExactMath.add(categoryTotals.budgetedSpending ?? 0, !category.account_id && category.name !== InflowCategories.READY_TO_ASSIGN ? (category.activity || 0) : 0)
categoryTotals.payments = ExactMath.add(categoryTotals.payments ?? 0, category.name !== InflowCategories.READY_TO_ASSIGN ? category.payments : 0)
categoryTotals.fundedSpending = ExactMath.add(categoryTotals.fundedSpending ?? 0, category.name !== InflowCategories.READY_TO_ASSIGN ? category.funded_spending : 0)
categoryTotals.fundedSpendingPreviousMonth = ExactMath.add(categoryTotals.fundedSpendingPreviousMonth ?? 0, category.account_id && category.name !== InflowCategories.READY_TO_ASSIGN ? category.available : 0)
categoryTotals.fundedSpendingPreviousMonth = ExactMath.add(categoryTotals.fundedSpendingPreviousMonth || 0, category.account_id && category.name !== InflowCategories.READY_TO_ASSIGN ? (category.available || 0): 0)

if (Number(category.available) < 0 && category.name !== 'Inflow') {
category.budgeted
Expand Down Expand Up @@ -98,8 +98,8 @@ export const getGroupTotals = (groups: Record<string, any>) => {



groupTotals.monthlyGoals.target = ExactMath.add(groupTotals.monthlyGoals.target, group.monthlyGoals.target)
groupTotals.monthlyGoals.balance = ExactMath.add(groupTotals.monthlyGoals.balance, group.monthlyGoals.balance)
groupTotals.monthlyGoals.target = ExactMath.add(groupTotals.monthlyGoals.target || 0, group.monthlyGoals.target || 0)
groupTotals.monthlyGoals.balance = ExactMath.add(groupTotals.monthlyGoals.balance || 0, group.monthlyGoals.balance || 0)

return groupTotals;
}, {
Expand Down
2 changes: 1 addition & 1 deletion resources/js/domains/budget/components/BudgetGroupItem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ const fetchDetails = async (category: ICategory) => {

<template>
<article>
<header class="flex justify-between px-4 py-2 text-body-1/80">
<header class="flex justify-between px-4 py-0.5 text-body-1/80 text-xs">
<div class="flex items-center space-x-2">
<div class="cursor-grab" v-if="isMobile && allowDrag">
<IconDrag class="handle" />
Expand Down
2 changes: 1 addition & 1 deletion resources/js/domains/budget/useBudget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export const BudgetState = reactive({
const assigned = parseFloat(budgetTotals.budgeted ?? 0);
const leftOver = parseFloat(category.left_from_last_month ?? 0)
const movedFromLastMonth = parseFloat(category.moved_from_last_month ?? 0)
const balance = (parseFloat(category.activity ?? 0) + parseFloat(category.left_from_last_month ?? 0) - assigned)
const balance = (parseFloat(category.activity ?? 0) + parseFloat(category.left_from_last_month ?? 0) - assigned)

return {
availableForFunding,
Expand Down
13 changes: 13 additions & 0 deletions resources/types/generated.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
declare namespace App.Domains.Automation.Enums {
export type AutomationTaskType = ;
}
declare namespace App.Domains.Budget.Data {
export type BudgetReservedNames = 'Ready to Assign' | 'Inflow' | 'Credit Card Payments';
export type CategoryResourceType = 'transactions';
}
declare namespace App.Domains.Housing.Contracts {
export type OccurrenceNotifyTypes = 'avg' | 'last';
}
declare namespace App.Domains.LogerProfile.Data {
export type ProfileEntityType = 'category' | 'occurrence_check' | 'plan' | 'account' | 'menu' | 'schedule';
}

0 comments on commit f958734

Please sign in to comment.