Files
grocy/services/HabitsService.php

73 lines
2.0 KiB
PHP
Raw Normal View History

2017-07-25 20:03:31 +02:00
<?php
2018-04-11 19:49:35 +02:00
namespace Grocy\Services;
class HabitsService extends BaseService
2017-07-25 20:03:31 +02:00
{
const HABIT_TYPE_MANUALLY = 'manually';
const HABIT_TYPE_DYNAMIC_REGULAR = 'dynamic-regular';
public function GetCurrent()
2017-07-25 20:03:31 +02:00
{
$sql = 'SELECT * from habits_current';
2018-04-11 19:49:35 +02:00
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
2017-07-25 20:03:31 +02:00
}
2018-04-11 19:49:35 +02:00
public function GetHabitDetails(int $habitId)
2017-07-25 20:03:31 +02:00
{
if (!$this->HabitExists($habitId))
{
throw new \Exception('Habit does not exist');
}
2018-04-11 19:49:35 +02:00
$habit = $this->Database->habits($habitId);
$habitTrackedCount = $this->Database->habits_log()->where('habit_id', $habitId)->count();
$habitLastTrackedTime = $this->Database->habits_log()->where('habit_id', $habitId)->max('tracked_time');
2018-07-25 19:28:15 +02:00
$lastHabitLogRow = $this->Database->habits_log()->where('habit_id = :1 AND tracked_time = :2', $habitId, $habitLastTrackedTime)->fetch();
$lastDoneByUser = null;
if ($lastHabitLogRow !== null && !empty($lastHabitLogRow))
2018-07-25 19:28:15 +02:00
{
$usersService = new UsersService();
$users = $usersService->GetUsersAsDto();
$lastDoneByUser = FindObjectInArrayByPropertyValue($users, 'id', $lastHabitLogRow->done_by_user_id);
2018-07-25 19:28:15 +02:00
}
2017-07-25 20:03:31 +02:00
return array(
'habit' => $habit,
'last_tracked' => $habitLastTrackedTime,
2018-07-25 19:28:15 +02:00
'tracked_count' => $habitTrackedCount,
'last_done_by' => $lastDoneByUser
2017-07-25 20:03:31 +02:00
);
}
public function TrackHabit(int $habitId, string $trackedTime, $doneBy = GROCY_USER_ID)
2017-07-25 20:03:31 +02:00
{
if (!$this->HabitExists($habitId))
{
throw new \Exception('Habit does not exist');
}
$userRow = $this->Database->users()->where('id = :1', $doneBy)->fetch();
if ($userRow === null)
{
throw new \Exception('User does not exist');
}
2018-04-11 19:49:35 +02:00
$logRow = $this->Database->habits_log()->createRow(array(
2017-07-25 20:03:31 +02:00
'habit_id' => $habitId,
'tracked_time' => $trackedTime,
'done_by_user_id' => $doneBy
2017-07-25 20:03:31 +02:00
));
$logRow->save();
return true;
}
private function HabitExists($habitId)
{
$habitRow = $this->Database->habits()->where('id = :1', $habitId)->fetch();
return $habitRow !== null;
}
2017-07-25 20:03:31 +02:00
}