Skip to content

Commit

Permalink
Merge pull request #408 from jesusantguerrero/fix/meals-flow
Browse files Browse the repository at this point in the history
Fix/meals flow
  • Loading branch information
jesusantguerrero authored Jun 1, 2024
2 parents 61ed31c + abdaa5d commit 23b3ec8
Show file tree
Hide file tree
Showing 51 changed files with 1,101 additions and 495 deletions.
2 changes: 0 additions & 2 deletions app/Console/Commands/TestMessaging.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
namespace App\Console\Commands;

use Exception;
use App\Models\UserDevice;
use Illuminate\Console\Command;
use App\Events\BudgetCalculated;
use App\Services\MessagingService;

class TestMessaging extends Command
{
Expand Down
6 changes: 4 additions & 2 deletions app/Domains/Automation/Services/LogerAutomationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace App\Domains\Automation\Services;

use Google\Service\Gmail;
use App\Domains\Integration\Actions\BHD;
use App\Domains\Automation\Models\Automation;
use App\Domains\Integration\Actions\BHDAlert;
use App\Domains\Transaction\Services\BHDService;
use App\Domains\Automation\Models\AutomationTask;
use App\Domains\Integration\Actions\OccurrenceAutomation;
use App\Domains\Integration\Actions\TransactionCreateEntry;
Expand Down Expand Up @@ -40,8 +42,8 @@ public static function run(Automation $automation, $eventData = null)
public static function setupService($serviceId, $service)
{
$taskTypes = [
'triggers' => 'trigger',
'components' => 'component',
'triggers' => 'trigger',
'components' => 'component',
'actions' => 'action'
];
foreach ($taskTypes as $taskTypeName => $taskType) {
Expand Down
4 changes: 3 additions & 1 deletion app/Domains/Budget/Models/Budget.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

namespace App\Domains\Budget\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Insane\Journal\Models\Core\Account;
use App\Domains\AppCore\Models\Category;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Budget extends Model
{
Expand Down
3 changes: 2 additions & 1 deletion app/Domains/Budget/Models/BudgetMonth.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
use Insane\Journal\Models\Core\Account;
use App\Domains\AppCore\Models\Category;
use App\Domains\Budget\Data\BudgetReservedNames;
use App\Domains\Budget\Models\Traits\BudgetMonthTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class BudgetMonth extends Model
{
use HasFactory;
use HasFactory, BudgetMonthTrait;

protected $fillable = [
'team_id',
Expand Down
101 changes: 101 additions & 0 deletions app/Domains/Budget/Models/Traits/BudgetMonthTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

namespace App\Domains\Budget\Models\Traits;

use Illuminate\Support\Facades\DB;
use Insane\Journal\Models\Core\Transaction;
use App\Domains\Budget\Data\BudgetReservedNames;

trait BudgetMonthTrait
{
public function scopeByTeam($query, $teamId)
{
return $query->where('budget_months.team_id', $teamId);
}


public function scopeInDateFrame($query, $startDate = null, $endDate = null, $orderByDate = true)
{
return $query
->when($startDate && ! $endDate, function ($query) use ($startDate) {
$query->where('budget_months.month', '=', $startDate);
})
->when($startDate && $endDate, function ($query) use ($startDate, $endDate) {
$query->where('budget_months.month', '>=', $startDate);
$query->where('budget_months.month', '<=', $endDate);
})
->when($orderByDate, function ($query) {
$query->orderBy('budget_months.month', 'desc');
});
}

public function scopeExpenses($query)
{
return $query->where([
'transactions.direction' => Transaction::DIRECTION_CREDIT,
'transactions.status' => 'verified',
])
->whereNotNull('budget_months.category_id');
}

public function scopeBalance($query)
{
$transactionsTotalSum = 'sum(budget_months.budgeted) as total_amount, group_concat(distinct(categories.name)) as cat_name';

return $query
->whereNotNull('budget_months.category_id')
->where('budget_months.budgeted', '<>', 0)
->selectRaw($transactionsTotalSum);
}

public function scopeForAccount($query, $accountId)
{
return $query->where(DB::raw("(account_id = $accountId)"));
}

public function scopeCategories($query, array $categories)
{
return $query->whereIn('budget_months.category_id', $categories)
->join('categories', 'budget_months.category_id', '=', 'categories.id')
->when($categories, fn ($query) => $query->whereIn('budget_months.category_id', $categories));
}

public function scopeExpenseCategories($query, array $categories = null)
{
$query->whereNot('categories.name', BudgetReservedNames::READY_TO_ASSIGN->value)
->join('categories', 'budget_months.category_id', '=', 'categories.id');

$categories = collect($categories);
$excluded = $categories->filter( fn ($id) => $id < 0)->all();
$included = $categories->filter( fn ($id) => $id > 0)->all();

if (count($excluded)) {
$query->whereNotIn('budget_months.category_id', $excluded);
}
if (count($included)) {
$query->whereIn('budget_months.category_id', $included);
}

return $query;
}

public function scopeAllCategories($query, array $categories = null)
{
$query
->whereNot('categories.name', BudgetReservedNames::READY_TO_ASSIGN->value)
->join('categories', 'budget_months.category_id', '=', 'categories.id');

$categories = collect($categories);
$excluded = $categories->filter( fn ($id) => $id < 0)->all();
$included = $categories->filter( fn ($id) => $id > 0)->all();

if (count($excluded)) {
$query->whereNotIn('budget_months.category_id', $excluded);
}
if (count($included)) {
$query->whereIn('budget_months.category_id', $included);
}

return $query;
}
}
2 changes: 1 addition & 1 deletion app/Domains/Integration/Actions/GmailReceived.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ public static function handle(Automation $automation, $lastData = null, $task =
$config = json_decode($trigger->values);
$client = GoogleService::getClient($automation->integration_id);
$service = new ServiceGmail($client);
$notification = BHDService::EMAIL_NOTIFICATION;
$condition = isset($config->conditionType) && $config->value ? "$config->conditionType:$config->value" : '';
if (! $condition) {
$condition = $config->value ?? '';
Expand All @@ -35,6 +34,7 @@ public static function handle(Automation $automation, $lastData = null, $task =
foreach ($results->getThreads() as $index => $thread) {
$theadResponse = $service->users_threads->get('me', $thread->id, ['format' => 'MINIMAL']);
foreach ($theadResponse->getMessages() as $message) {

if ($message && $message->getHistoryId() > $trackId) {
$raw = $service->users_messages->get('me', $message->id, ['format' => 'raw']);
$parser = self::parseEmail($raw);
Expand Down
11 changes: 9 additions & 2 deletions app/Domains/Integration/Actions/TransactionCreateEntry.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,23 +38,28 @@ public static function handle(
$counterAccountId = $payee->account_id;
}

$description = FormulaHelper::parseFormula($taskData->description, $payload);

$transactionData = [
'team_id' => $automation->team_id,
'user_id' => $automation->user_id,
'account_id' => $accountId,
'payee_id' => $payeeId,
'payee_name' => $payee?->name,
'counter_account_id' => $counterAccountId ?? null,
'date' => FormulaHelper::parseFormula($taskData->date, $payload),
'currency_code' => FormulaHelper::parseFormula($taskData->currency_code, $payload),
'category_id' => $transactionCategoryId ?? null,
'description' => FormulaHelper::parseFormula($taskData->description, $payload),
'description' => $description,
'reference' => $description,
'direction' => FormulaHelper::parseFormula($taskData->direction, $payload),
'total' => FormulaHelper::parseFormula($taskData->total, $payload),
'items' => [],
'metaData' => [
'meta_data' => [
'resource_id' => $payload['id'],
'resource_origin' => $previousTask->name,
'resource_type' => $trigger->name,
'resource_description' => $description
],
];

Expand All @@ -72,6 +77,8 @@ public static function handle(
return $transaction;
}

print_r($transactionData);

$transaction = Transaction::createTransaction($transactionData);
User::find($automation->user_id)->notify(new EntryGenerated($transaction));

Expand Down
25 changes: 25 additions & 0 deletions app/Domains/Meal/Services/MealService.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
use Illuminate\Support\Carbon;
use App\Domains\Meal\Models\Meal;
use App\Domains\Meal\Models\Product;
use Modules\Plan\Entities\PlanTypes;
use App\Domains\Meal\Models\MealPlan;
use Modules\Plan\Services\PlanService;
use App\Domains\AppCore\Models\Planner;

class MealService
Expand Down Expand Up @@ -125,4 +127,27 @@ public function addIngredientLabel(Product $product, mixed $postData, User $user

return $label;
}

// shopping list
public function addToShoppingList($ingredients = [])
{
$planService = new PlanService();
$user = request()->user();
$team = request()->user()->currentTeam;
$shoppingList = $planService->getPlanTypeModel($team->id, PlanTypes::SHOPPING_LIST, request());
if (!$shoppingList) {
$shoppingList = $planService->createPlanBoard($team, PlanTypes::SHOPPING_LIST, PlanTypes::SHOPPING_LIST->name);
}

foreach ($ingredients as $ingredient) {
$shoppingList->addItem($user, [
"title" => $ingredient["name"],
"board_id" => null,
"stage_id" => $shoppingList->stages->first()->id,
"fields" => [],
"order" => 1
]);
}

}
}
42 changes: 42 additions & 0 deletions app/Domains/Transaction/Services/ReportService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Domains\Budget\Models\BudgetMonth;
use App\Domains\Transaction\Models\Transaction;
use App\Domains\Transaction\Models\TransactionLine;

Expand Down Expand Up @@ -57,6 +58,23 @@ public static function generateExpensesByPeriod($teamId, $startDate, $timeUnitDi
}, $resultGroup)->sortBy('date');
}

public static function getAssignedByPeriod($teamId, $startDate, $timeUnitDiff = 2, $timeUnit = 'month', $categories = null)
{
$rangeEndAt = Carbon::createFromFormat('Y-m-d', $startDate)->endOfMonth()->format('Y-m-d');
$rangeStartAt = Carbon::now()->subMonth($timeUnitDiff)->startOfMonth()->format('Y-m-d');

$results = self::getAssignedByCategoriesInPeriod($teamId, $rangeStartAt, $rangeEndAt, $categories);
$resultGroup = $results->groupBy('date');

return $resultGroup->map(function ($monthItems) {
return [
'date' => $monthItems->first()->date,
'data' => $monthItems->sortByDesc('total_amount')->values(),
'total' => $monthItems->sum('total_amount'),
];
}, $resultGroup)->sortBy('date');
}

public static function getIncomeVsExpenses($teamId, $timeUnitDiff = 2, $startDate = null, $timeUnit = 'month')
{
$endDate = Carbon::now()->endOfMonth()->format('Y-m-d');
Expand Down Expand Up @@ -175,6 +193,30 @@ public static function getExpensesByCategoriesInPeriod($teamId, $startDate, $end
return $cats;
}

public static function getAssignedByCategoriesInPeriod($teamId, $startDate, $endDate, $categories = null)
{
$cats = BudgetMonth::byTeam($teamId)
->balance()
->inDateFrame($startDate, $endDate)
->expenseCategories($categories)
->selectRaw("
date_format(budget_months.month,
'%Y-%m-01') as date,
date_format(budget_months.month, '%Y-%m-01') as month,
year(budget_months.month) as year,
categories.name,
categories.id,
budget_targets.target_type
"
)
->groupByRaw('date_format(budget_months.month, "%Y-%m"), categories.id')
->orderBy('date')
->leftJoin('budget_targets', 'budget_targets.category_id', 'categories.id')
->get();

return $cats;
}

public static function getExpensesInPeriod($teamId, $startDate, $endDate)
{
return TransactionLine::byTeam($teamId)
Expand Down
28 changes: 28 additions & 0 deletions app/Http/Controllers/Finance/FinanceTrendController.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class FinanceTrendController extends Controller
'spending-year' => [
"handler" => 'spendingYear'
],
'assigned-year' => [
"handler" => 'assignedInYear'
],
'income-expenses-graph' => [
"handler" => 'IncomeExpensesGraph'
],
Expand Down Expand Up @@ -204,6 +207,31 @@ public function spendingYear()
];
}

public function assignedInYear()
{
$queryParams = request()->query();
$filters = isset($queryParams['filter']) ? $queryParams['filter'] : [];
[$startDate] = $this->getFilterDates($filters);
$teamId = request()->user()->current_team_id;
$excludedAccounts = null;
if (isset($filters['category'])) {
$excludedAccounts = collect(explode(',', $filters['category']))->map(fn ($id) => "-$id")->all();
}

// dd(ReportService::generateExpensesByPeriod($teamId, $startDate, 12, 'month', $excludedAccounts), ReportService::getAssignedByPeriod($teamId, $startDate, 12, 'month', $excludedAccounts));

return [
'data' => ReportService::getAssignedByPeriod($teamId, $startDate, 12, 'month', $excludedAccounts),
'metaData' => [
'name' => 'assignedYear',
'title' => 'Assigned in year',
'props' => [
'headerTemplate' => 'grid',
],
],
];
}



public function yearSummary()
Expand Down
Loading

0 comments on commit 23b3ec8

Please sign in to comment.