Convert services to singletons and use lazy loading to improve performance (#479)

* use singletons to reduce need to recreate the same objects

* unable to make the constructor private

* comment out debug printing to log file

* correct typo of treating self() as a var instead of a function

* utilise Localisation service as a singleton

* fix errent line that should have been commented

* remove phpinfo

* correct mistake in stock controller

* try storing app in apcu

* serialise inside the app closures

* get timings for db-changed-time

* get timings for db-changed-time

* store localisation service in apcu

* stor translations in apcu instead of localisation service (due to database connection)

* correct syntax error

* forgot to uncomment instance map

* correct indentation and variable out of scope

* more timings for app execution time

* try apc caching for views

* correct scope for Pot variable

* remove additional fopen

* correct timings for app build time

* correct timings for app object build time

* correct timings for app route build time

* get timings for routing timings

* get more in depth timings for routing loading

* fix more in depth timings for routing loading

* start investigating session auth middleware creation

* start investigating session auth middleware creation

* start investigating Login controller time

* start investigating Login controller time

* in depth look at Logincontroller timings

* comment out debug printing

* lazily obtain valus for page rendering

* correct syntax error

* correct scope of variable

* correct visibiity of methds inherited from BaseController

* missing use for Userfieldsservice

* lazy loading of open api spec

* lazy loading of users service

* lazy loading of batteries service

* lazy loading of services in controllers

* lazy loading of services in services

* correct mistake

* fix userservice

* fix userservice

* fix userfieldservice

* fix chores service

* fix calendar service

* remove Dockerfile used for development

* Remove docker compose file used for development

* Clean up app.php

* remove last diff

* Clean up base controller

* Clean up controllers

* lean up middleware

* Clean up and tuen all services into singletons

* remove debug from routes.php

* remove acpu from localisation

* Complete removal of acpu from localisation

* fixes for things broken

* More fixes following merge

* Fix for start up bug. Re factoring singleton code had brroken due to scope of clas var.

* fix bug where getUsersService is declared twice

* bug fixes following merge

* bug fixes following merge

* bug fixes following merge

* bug fixes following merge

* bug fixes following merge

* Fix all the not working things...

* Deleted off-topic files

* Deleted off-topic files

Co-authored-by: Bernd Bestel <bernd@berrnd.de>
This commit is contained in:
zebardy
2020-03-01 23:47:47 +07:00
committed by GitHub
parent 2b1dc7756d
commit 1a5f3ce926
49 changed files with 875 additions and 837 deletions

View File

@@ -8,10 +8,18 @@ class BaseApiController extends BaseController
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json'));
} }
protected $OpenApiSpec; protected $OpenApiSpec = null;
protected function getOpenApispec()
{
if($this->OpenApiSpec == null)
{
$this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json'));
}
return $this->OpenApiSpec;
}
protected function ApiResponse(\Psr\Http\Message\ResponseInterface $response, $data) protected function ApiResponse(\Psr\Http\Message\ResponseInterface $response, $data)
{ {

View File

@@ -5,36 +5,46 @@ namespace Grocy\Controllers;
use \Grocy\Services\DatabaseService; use \Grocy\Services\DatabaseService;
use \Grocy\Services\ApplicationService; use \Grocy\Services\ApplicationService;
use \Grocy\Services\LocalizationService; use \Grocy\Services\LocalizationService;
use \Grocy\Services\StockService;
use \Grocy\Services\UsersService; use \Grocy\Services\UsersService;
use \Grocy\Services\UserfieldsService;
use \Grocy\Services\BatteriesService;
use \Grocy\Services\CalendarService;
use \Grocy\Services\SessionService;
use \Grocy\Services\RecipesService;
use \Grocy\Services\TasksService;
use \Grocy\Services\FilesService;
use \Grocy\Services\ChoresService;
use \Grocy\Services\ApiKeyService;
class BaseController class BaseController
{ {
public function __construct(\DI\Container $container) { public function __construct(\DI\Container $container) {
$databaseService = new DatabaseService();
$this->Database = $databaseService->GetDbConnection();
$localizationService = new LocalizationService(GROCY_CULTURE); $this->AppContainer = $container;
$this->LocalizationService = $localizationService; $this->View = $container->get('view');
}
$applicationService = new ApplicationService(); protected function render($response, $page, $data = [])
$versionInfo = $applicationService->GetInstalledVersion(); {
$container = $this->AppContainer;
$view = $container->get('view'); $versionInfo = $this->getApplicationService()->GetInstalledVersion();
$this->View = $view; $this->View->set('version', $versionInfo->Version);
$this->View->set('releaseDate', $versionInfo->ReleaseDate);
$view->set('version', $versionInfo->Version); $localizationService = $this->getLocalizationService();
$view->set('releaseDate', $versionInfo->ReleaseDate); $this->View->set('__t', function(string $text, ...$placeholderValues) use($localizationService)
$view->set('__t', function(string $text, ...$placeholderValues) use($localizationService)
{ {
return $localizationService->__t($text, $placeholderValues); return $localizationService->__t($text, $placeholderValues);
}); });
$view->set('__n', function($number, $singularForm, $pluralForm) use($localizationService) $this->View->set('__n', function($number, $singularForm, $pluralForm) use($localizationService)
{ {
return $localizationService->__n($number, $singularForm, $pluralForm); return $localizationService->__n($number, $singularForm, $pluralForm);
}); });
$view->set('GettextPo', $localizationService->GetPoAsJsonString()); $this->View->set('GettextPo', $localizationService->GetPoAsJsonString());
$view->set('U', function($relativePath, $isResource = false) use($container) $this->View->set('U', function($relativePath, $isResource = false) use($container)
{ {
return $container->get('UrlManager')->ConstructUrl($relativePath, $isResource); return $container->get('UrlManager')->ConstructUrl($relativePath, $isResource);
}); });
@@ -44,7 +54,7 @@ class BaseController
{ {
$embedded = true; $embedded = true;
} }
$view->set('embedded', $embedded); $this->View->set('embedded', $embedded);
$constants = get_defined_constants(); $constants = get_defined_constants();
foreach ($constants as $constant => $value) foreach ($constants as $constant => $value)
@@ -54,20 +64,24 @@ class BaseController
unset($constants[$constant]); unset($constants[$constant]);
} }
} }
$view->set('featureFlags', $constants); $this->View->set('featureFlags', $constants);
$view->set('userentitiesForSidebar', $this->Database->userentities()->where('show_in_sidebar_menu = 1')->orderBy('name')); return $this->View->render($response, $page, $data);
}
protected function renderPage($response, $page, $data = [])
{
$this->View->set('userentitiesForSidebar', $this->getDatabase()->userentities()->where('show_in_sidebar_menu = 1')->orderBy('name'));
try try
{ {
$usersService = new UsersService(); $usersService = $this->getUsersService();
if (defined('GROCY_USER_ID')) if (defined('GROCY_USER_ID'))
{ {
$view->set('userSettings', $usersService->GetUserSettings(GROCY_USER_ID)); $this->View->set('userSettings', $usersService->GetUserSettings(GROCY_USER_ID));
} }
else else
{ {
$view->set('userSettings', null); $this->View->set('userSettings', null);
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -75,11 +89,83 @@ class BaseController
// Happens when database is not initialised or migrated... // Happens when database is not initialised or migrated...
} }
$this->AppContainer = $container; return $this->render($response, $page, $data);
}
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getDatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
protected function getLocalizationService()
{
return LocalizationService::getInstance(GROCY_CULTURE);
}
protected function getApplicationservice()
{
return ApplicationService::getInstance();
}
protected function getBatteriesService()
{
return BatteriesService::getInstance();
}
protected function getCalendarService()
{
return CalendarService::getInstance();
}
protected function getSessionService()
{
return SessionService::getInstance();
}
protected function getRecipesService()
{
return RecipesService::getInstance();
}
protected function getStockService()
{
return StockService::getInstance();
}
protected function getTasksService()
{
return TasksService::getInstance();
}
protected function getUsersService()
{
return UsersService::getInstance();
}
protected function getUserfieldsService()
{
return UserfieldsService::getInstance();
}
protected function getApiKeyService()
{
return ApiKeyService::getInstance();
}
protected function getChoresService()
{
return ChoresService::getInstance();
}
protected function getFilesService()
{
return FilesService::getInstance();
} }
protected $AppContainer; protected $AppContainer;
protected $Database;
protected $LocalizationService;
protected $View;
} }

View File

@@ -2,18 +2,13 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\BatteriesService;
class BatteriesApiController extends BaseApiController class BatteriesApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->BatteriesService = new BatteriesService();
} }
protected $BatteriesService;
public function TrackChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TrackChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
@@ -26,8 +21,8 @@ class BatteriesApiController extends BaseApiController
$trackedTime = $requestBody['tracked_time']; $trackedTime = $requestBody['tracked_time'];
} }
$chargeCycleId = $this->BatteriesService->TrackChargeCycle($args['batteryId'], $trackedTime); $chargeCycleId = $this->getBatteriesService()->TrackChargeCycle($args['batteryId'], $trackedTime);
return $this->ApiResponse($response, $this->Database->battery_charge_cycles($chargeCycleId)); return $this->ApiResponse($response, $this->getDatabase()->battery_charge_cycles($chargeCycleId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -39,7 +34,7 @@ class BatteriesApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->BatteriesService->GetBatteryDetails($args['batteryId'])); return $this->ApiResponse($response, $this->getBatteriesService()->GetBatteryDetails($args['batteryId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -49,14 +44,14 @@ class BatteriesApiController extends BaseApiController
public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, $this->BatteriesService->GetCurrent()); return $this->ApiResponse($response, $this->getBatteriesService()->GetCurrent());
} }
public function UndoChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UndoChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
{ {
$this->ApiResponse($response, $this->BatteriesService->UndoChargeCycle($args['chargeCycleId'])); $this->ApiResponse($response, $this->getBatteriesService()->UndoChargeCycle($args['chargeCycleId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@@ -2,49 +2,40 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\BatteriesService;
use \Grocy\Services\UsersService;
use \Grocy\Services\UserfieldsService;
class BatteriesController extends BaseController class BatteriesController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->BatteriesService = new BatteriesService();
$this->UserfieldsService = new UserfieldsService();
} }
protected $BatteriesService;
protected $UserfieldsService;
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$usersService = new UsersService(); $usersService = $this->getUsersService();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['batteries_due_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['batteries_due_soon_days'];
return $this->View->render($response, 'batteriesoverview', [ return $this->renderPage($response, 'batteriesoverview', [
'batteries' => $this->Database->batteries()->orderBy('name'), 'batteries' => $this->getDatabase()->batteries()->orderBy('name'),
'current' => $this->BatteriesService->GetCurrent(), 'current' => $this->getBatteriesService()->GetCurrent(),
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'userfields' => $this->UserfieldsService->GetFields('batteries'), 'userfields' => $this->getUserfieldsService()->GetFields('batteries'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('batteries') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries')
]); ]);
} }
public function TrackChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TrackChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'batterytracking', [ return $this->renderPage($response, 'batterytracking', [
'batteries' => $this->Database->batteries()->orderBy('name') 'batteries' => $this->getDatabase()->batteries()->orderBy('name')
]); ]);
} }
public function BatteriesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function BatteriesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'batteries', [ return $this->renderPage($response, 'batteries', [
'batteries' => $this->Database->batteries()->orderBy('name'), 'batteries' => $this->getDatabase()->batteries()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('batteries'), 'userfields' => $this->getUserfieldsService()->GetFields('batteries'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('batteries') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries')
]); ]);
} }
@@ -52,31 +43,31 @@ class BatteriesController extends BaseController
{ {
if ($args['batteryId'] == 'new') if ($args['batteryId'] == 'new')
{ {
return $this->View->render($response, 'batteryform', [ return $this->renderPage($response, 'batteryform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('batteries') 'userfields' => $this->getUserfieldsService()->GetFields('batteries')
]); ]);
} }
else else
{ {
return $this->View->render($response, 'batteryform', [ return $this->renderPage($response, 'batteryform', [
'battery' => $this->Database->batteries($args['batteryId']), 'battery' => $this->getDatabase()->batteries($args['batteryId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('batteries') 'userfields' => $this->getUserfieldsService()->GetFields('batteries')
]); ]);
} }
} }
public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'batteriesjournal', [ return $this->renderPage($response, 'batteriesjournal', [
'chargeCycles' => $this->Database->battery_charge_cycles()->orderBy('tracked_time', 'DESC'), 'chargeCycles' => $this->getDatabase()->battery_charge_cycles()->orderBy('tracked_time', 'DESC'),
'batteries' => $this->Database->batteries()->orderBy('name') 'batteries' => $this->getDatabase()->batteries()->orderBy('name')
]); ]);
} }
public function BatteriesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function BatteriesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'batteriessettings'); return $this->renderPage($response, 'batteriessettings');
} }
} }

View File

@@ -2,28 +2,20 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\CalendarService;
use \Grocy\Services\ApiKeyService;
class CalendarApiController extends BaseApiController class CalendarApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->CalendarService = new CalendarService();
$this->ApiKeyService = new ApiKeyService();
} }
protected $CalendarService;
protected $ApiKeyService;
public function Ical(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Ical(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
{ {
$vCalendar = new \Eluceo\iCal\Component\Calendar('grocy'); $vCalendar = new \Eluceo\iCal\Component\Calendar('grocy');
$events = $this->CalendarService->GetEvents(); $events = $this->getCalendarService()->GetEvents();
foreach($events as $event) foreach($events as $event)
{ {
$date = new \DateTime($event['start']); $date = new \DateTime($event['start']);
@@ -60,7 +52,7 @@ class CalendarApiController extends BaseApiController
try try
{ {
return $this->ApiResponse($response, array( return $this->ApiResponse($response, array(
'url' => $this->AppContainer->get('UrlManager')->ConstructUrl('/api/calendar/ical?secret=' . $this->ApiKeyService->GetOrCreateApiKey(ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL)) 'url' => $this->AppContainer->get('UrlManager')->ConstructUrl('/api/calendar/ical?secret=' . $this->getApiKeyService()->GetOrCreateApiKey(ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL))
)); ));
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@@ -2,22 +2,17 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\CalendarService;
class CalendarController extends BaseController class CalendarController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->CalendarService = new CalendarService();
} }
protected $CalendarService;
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'calendar', [ return $this->renderPage($response, 'calendar', [
'fullcalendarEventSources' => $this->CalendarService->GetEvents() 'fullcalendarEventSources' => $this->getCalendarService()->GetEvents()
]); ]);
} }
} }

View File

@@ -2,18 +2,13 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\ChoresService;
class ChoresApiController extends BaseApiController class ChoresApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->ChoresService = new ChoresService();
} }
protected $ChoresService;
public function TrackChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TrackChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
@@ -32,8 +27,8 @@ class ChoresApiController extends BaseApiController
$doneBy = $requestBody['done_by']; $doneBy = $requestBody['done_by'];
} }
$choreExecutionId = $this->ChoresService->TrackChore($args['choreId'], $trackedTime, $doneBy); $choreExecutionId = $this->getChoresService()->TrackChore($args['choreId'], $trackedTime, $doneBy);
return $this->ApiResponse($response, $this->Database->chores_log($choreExecutionId)); return $this->ApiResponse($response, $this->getDatabase()->chores_log($choreExecutionId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -45,7 +40,7 @@ class ChoresApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->ChoresService->GetChoreDetails($args['choreId'])); return $this->ApiResponse($response, $this->getChoresService()->GetChoreDetails($args['choreId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -55,14 +50,14 @@ class ChoresApiController extends BaseApiController
public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, $this->ChoresService->GetCurrent()); return $this->ApiResponse($response, $this->getChoresService()->GetCurrent());
} }
public function UndoChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UndoChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
{ {
$this->ApiResponse($response, $this->ChoresService->UndoChoreExecution($args['executionId'])); $this->ApiResponse($response, $this->getChoresService()->UndoChoreExecution($args['executionId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -85,15 +80,15 @@ class ChoresApiController extends BaseApiController
if ($choreId === null) if ($choreId === null)
{ {
$chores = $this->Database->chores(); $chores = $this->getDatabase()->chores();
foreach ($chores as $chore) foreach ($chores as $chore)
{ {
$this->ChoresService->CalculateNextExecutionAssignment($chore->id); $this->getChoresService()->CalculateNextExecutionAssignment($chore->id);
} }
} }
else else
{ {
$this->ChoresService->CalculateNextExecutionAssignment($choreId); $this->getChoresService()->CalculateNextExecutionAssignment($choreId);
} }
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);

View File

@@ -2,95 +2,86 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\ChoresService;
use \Grocy\Services\UsersService;
use \Grocy\Services\UserfieldsService;
class ChoresController extends BaseController class ChoresController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->ChoresService = new ChoresService();
$this->UserfieldsService = new UserfieldsService();
} }
protected $ChoresService;
protected $UserfieldsService;
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$usersService = new UsersService(); $usersService = $this->getUsersService();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['chores_due_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['chores_due_soon_days'];
return $this->View->render($response, 'choresoverview', [ return $this->renderPage($response, 'choresoverview', [
'chores' => $this->Database->chores()->orderBy('name'), 'chores' => $this->getDatabase()->chores()->orderBy('name'),
'currentChores' => $this->ChoresService->GetCurrent(), 'currentChores' => $this->getChoresService()->GetCurrent(),
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'userfields' => $this->UserfieldsService->GetFields('chores'), 'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('chores'), 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores'),
'users' => $usersService->GetUsersAsDto() 'users' => $usersService->GetUsersAsDto()
]); ]);
} }
public function TrackChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TrackChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'choretracking', [ return $this->renderPage($response, 'choretracking', [
'chores' => $this->Database->chores()->orderBy('name'), 'chores' => $this->getDatabase()->chores()->orderBy('name'),
'users' => $this->Database->users()->orderBy('username') 'users' => $this->getDatabase()->users()->orderBy('username')
]); ]);
} }
public function ChoresList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ChoresList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'chores', [ return $this->renderPage($response, 'chores', [
'chores' => $this->Database->chores()->orderBy('name'), 'chores' => $this->getDatabase()->chores()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('chores'), 'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('chores') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores')
]); ]);
} }
public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'choresjournal', [ return $this->renderPage($response, 'choresjournal', [
'choresLog' => $this->Database->chores_log()->orderBy('tracked_time', 'DESC'), 'choresLog' => $this->getDatabase()->chores_log()->orderBy('tracked_time', 'DESC'),
'chores' => $this->Database->chores()->orderBy('name'), 'chores' => $this->getDatabase()->chores()->orderBy('name'),
'users' => $this->Database->users()->orderBy('username') 'users' => $this->getDatabase()->users()->orderBy('username')
]); ]);
} }
public function ChoreEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ChoreEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$usersService = new UsersService(); $usersService = getUsersService();
$users = $usersService->GetUsersAsDto(); $users = $usersService->GetUsersAsDto();
if ($args['choreId'] == 'new') if ($args['choreId'] == 'new')
{ {
return $this->View->render($response, 'choreform', [ return $this->renderPage($response, 'choreform', [
'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'), 'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'),
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('chores'), 'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'), 'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'),
'users' => $users, 'users' => $users,
'products' => $this->Database->products()->orderBy('name') 'products' => $this->getDatabase()->products()->orderBy('name')
]); ]);
} }
else else
{ {
return $this->View->render($response, 'choreform', [ return $this->renderPage($response, 'choreform', [
'chore' => $this->Database->chores($args['choreId']), 'chore' => $this->getDatabase()->chores($args['choreId']),
'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'), 'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('chores'), 'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'), 'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'),
'users' => $users, 'users' => $users,
'products' => $this->Database->products()->orderBy('name') 'products' => $this->getDatabase()->products()->orderBy('name')
]); ]);
} }
} }
public function ChoresSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ChoresSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'choressettings'); return $this->renderPage($response, 'choressettings');
} }
} }

View File

@@ -2,24 +2,21 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\UserfieldsService;
class EquipmentController extends BaseController class EquipmentController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->UserfieldsService = new UserfieldsService();
} }
protected $UserfieldsService; protected $UserfieldsService;
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'equipment', [ return $this->renderPage($response, 'equipment', [
'equipment' => $this->Database->equipment()->orderBy('name'), 'equipment' => $this->getDatabase()->equipment()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('equipment'), 'userfields' => $this->getUserfieldsService()->GetFields('equipment'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('equipment') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('equipment')
]); ]);
} }
@@ -27,17 +24,17 @@ class EquipmentController extends BaseController
{ {
if ($args['equipmentId'] == 'new') if ($args['equipmentId'] == 'new')
{ {
return $this->View->render($response, 'equipmentform', [ return $this->renderPage($response, 'equipmentform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('equipment') 'userfields' => $this->getUserfieldsService()->GetFields('equipment')
]); ]);
} }
else else
{ {
return $this->View->render($response, 'equipmentform', [ return $this->renderPage($response, 'equipmentform', [
'equipment' => $this->Database->equipment($args['equipmentId']), 'equipment' => $this->getDatabase()->equipment($args['equipmentId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('equipment') 'userfields' => $this->getUserfieldsService()->GetFields('equipment')
]); ]);
} }
} }

View File

@@ -2,18 +2,13 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\FilesService;
class FilesApiController extends BaseApiController class FilesApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->FilesService = new FilesService();
} }
protected $FilesService;
public function UploadFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UploadFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
@@ -28,7 +23,7 @@ class FilesApiController extends BaseApiController
} }
$data = $request->getBody()->getContents(); $data = $request->getBody()->getContents();
file_put_contents($this->FilesService->GetFilePath($args['group'], $fileName), $data); file_put_contents($this->getFilesService()->GetFilePath($args['group'], $fileName), $data);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
@@ -71,11 +66,11 @@ class FilesApiController extends BaseApiController
$bestFitWidth = $request->getQueryParams()['best_fit_width']; $bestFitWidth = $request->getQueryParams()['best_fit_width'];
} }
$filePath = $this->FilesService->DownscaleImage($args['group'], $fileName, $bestFitHeight, $bestFitWidth); $filePath = $this->getFilesService()->DownscaleImage($args['group'], $fileName, $bestFitHeight, $bestFitWidth);
} }
else else
{ {
$filePath = $this->FilesService->GetFilePath($args['group'], $fileName); $filePath = $this->getFilesService()->GetFilePath($args['group'], $fileName);
} }
if (file_exists($filePath)) if (file_exists($filePath))
@@ -109,7 +104,7 @@ class FilesApiController extends BaseApiController
throw new \Exception('Invalid filename'); throw new \Exception('Invalid filename');
} }
$filePath = $this->FilesService->GetFilePath($args['group'], $fileName); $filePath = $this->getFilesService()->GetFilePath($args['group'], $fileName);
if (file_exists($filePath)) if (file_exists($filePath))
{ {
unlink($filePath); unlink($filePath);

View File

@@ -2,23 +2,18 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\UserfieldsService;
class GenericEntityApiController extends BaseApiController class GenericEntityApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->UserfieldsService = new UserfieldsService();
} }
protected $UserfieldsService;
public function GetObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity']))
{ {
return $this->ApiResponse($response, $this->Database->{$args['entity']}()); return $this->ApiResponse($response, $this->getDatabase()->{$args['entity']}());
} }
else else
{ {
@@ -30,7 +25,7 @@ class GenericEntityApiController extends BaseApiController
{ {
if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity'])) if ($this->IsValidEntity($args['entity']) && !$this->IsEntityWithPreventedListing($args['entity']))
{ {
return $this->ApiResponse($response, $this->Database->{$args['entity']}($args['objectId'])); return $this->ApiResponse($response, $this->getDatabase()->{$args['entity']}($args['objectId']));
} }
else else
{ {
@@ -51,11 +46,11 @@ class GenericEntityApiController extends BaseApiController
throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)');
} }
$newRow = $this->Database->{$args['entity']}()->createRow($requestBody); $newRow = $this->getDatabase()->{$args['entity']}()->createRow($requestBody);
$newRow->save(); $newRow->save();
$success = $newRow->isClean(); $success = $newRow->isClean();
return $this->ApiResponse($response, array( return $this->ApiResponse($response, array(
'created_object_id' => $this->Database->lastInsertId() 'created_object_id' => $this->getDatabase()->lastInsertId()
)); ));
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -82,7 +77,7 @@ class GenericEntityApiController extends BaseApiController
throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)');
} }
$row = $this->Database->{$args['entity']}($args['objectId']); $row = $this->getDatabase()->{$args['entity']}($args['objectId']);
$row->update($requestBody); $row->update($requestBody);
$success = $row->isClean(); $success = $row->isClean();
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
@@ -102,7 +97,7 @@ class GenericEntityApiController extends BaseApiController
{ {
if ($this->IsValidEntity($args['entity'])) if ($this->IsValidEntity($args['entity']))
{ {
$row = $this->Database->{$args['entity']}($args['objectId']); $row = $this->getDatabase()->{$args['entity']}($args['objectId']);
$row->delete(); $row->delete();
$success = $row->isClean(); $success = $row->isClean();
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
@@ -119,7 +114,7 @@ class GenericEntityApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->Database->{$args['entity']}()->where('name LIKE ?', '%' . $args['searchString'] . '%')); return $this->ApiResponse($response, $this->getDatabase()->{$args['entity']}()->where('name LIKE ?', '%' . $args['searchString'] . '%'));
} }
catch (\PDOException $ex) catch (\PDOException $ex)
{ {
@@ -136,7 +131,7 @@ class GenericEntityApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->UserfieldsService->GetValues($args['entity'], $args['objectId'])); return $this->ApiResponse($response, $this->getUserfieldsService()->GetValues($args['entity'], $args['objectId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -155,7 +150,7 @@ class GenericEntityApiController extends BaseApiController
throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)');
} }
$this->UserfieldsService->SetValues($args['entity'], $args['objectId'], $requestBody); $this->getUserfieldsService()->SetValues($args['entity'], $args['objectId'], $requestBody);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -166,11 +161,11 @@ class GenericEntityApiController extends BaseApiController
private function IsValidEntity($entity) private function IsValidEntity($entity)
{ {
return in_array($entity, $this->OpenApiSpec->components->internalSchemas->ExposedEntity->enum); return in_array($entity, $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum);
} }
private function IsEntityWithPreventedListing($entity) private function IsEntityWithPreventedListing($entity)
{ {
return !in_array($entity, $this->OpenApiSpec->components->internalSchemas->ExposedEntityButNoListing->enum); return !in_array($entity, $this->getOpenApiSpec()->components->internalSchemas->ExposedEntityButNoListing->enum);
} }
} }

View File

@@ -2,42 +2,37 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\UserfieldsService;
class GenericEntityController extends BaseController class GenericEntityController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->UserfieldsService = new UserfieldsService();
} }
protected $UserfieldsService;
public function UserfieldsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserfieldsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'userfields', [ return $this->renderPage($response, 'userfields', [
'userfields' => $this->UserfieldsService->GetAllFields(), 'userfields' => $this->getUserfieldsService()->GetAllFields(),
'entities' => $this->UserfieldsService->GetEntities() 'entities' => $this->getUserfieldsService()->GetEntities()
]); ]);
} }
public function UserentitiesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserentitiesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'userentities', [ return $this->renderPage($response, 'userentities', [
'userentities' => $this->Database->userentities()->orderBy('name') 'userentities' => $this->getDatabase()->userentities()->orderBy('name')
]); ]);
} }
public function UserobjectsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserobjectsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$userentity = $this->Database->userentities()->where('name = :1', $args['userentityName'])->fetch(); $userentity = $this->getDatabase()->userentities()->where('name = :1', $args['userentityName'])->fetch();
return $this->View->render($response, 'userobjects', [ return $this->renderPage($response, 'userobjects', [
'userentity' => $userentity, 'userentity' => $userentity,
'userobjects' => $this->Database->userobjects()->where('userentity_id = :1', $userentity->id), 'userobjects' => $this->getDatabase()->userobjects()->where('userentity_id = :1', $userentity->id),
'userfields' => $this->UserfieldsService->GetFields('userentity-' . $args['userentityName']), 'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']),
'userfieldValues' => $this->UserfieldsService->GetAllValues('userentity-' . $args['userentityName']) 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('userentity-' . $args['userentityName'])
]); ]);
} }
@@ -45,19 +40,19 @@ class GenericEntityController extends BaseController
{ {
if ($args['userfieldId'] == 'new') if ($args['userfieldId'] == 'new')
{ {
return $this->View->render($response, 'userfieldform', [ return $this->renderPage($response, 'userfieldform', [
'mode' => 'create', 'mode' => 'create',
'userfieldTypes' => $this->UserfieldsService->GetFieldTypes(), 'userfieldTypes' => $this->getUserfieldsService()->GetFieldTypes(),
'entities' => $this->UserfieldsService->GetEntities() 'entities' => $this->getUserfieldsService()->GetEntities()
]); ]);
} }
else else
{ {
return $this->View->render($response, 'userfieldform', [ return $this->renderPage($response, 'userfieldform', [
'mode' => 'edit', 'mode' => 'edit',
'userfield' => $this->UserfieldsService->GetField($args['userfieldId']), 'userfield' => $this->getUserfieldsService()->GetField($args['userfieldId']),
'userfieldTypes' => $this->UserfieldsService->GetFieldTypes(), 'userfieldTypes' => $this->getUserfieldsService()->GetFieldTypes(),
'entities' => $this->UserfieldsService->GetEntities() 'entities' => $this->getUserfieldsService()->GetEntities()
]); ]);
} }
} }
@@ -66,38 +61,38 @@ class GenericEntityController extends BaseController
{ {
if ($args['userentityId'] == 'new') if ($args['userentityId'] == 'new')
{ {
return $this->View->render($response, 'userentityform', [ return $this->renderPage($response, 'userentityform', [
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
return $this->View->render($response, 'userentityform', [ return $this->renderPage($response, 'userentityform', [
'mode' => 'edit', 'mode' => 'edit',
'userentity' => $this->Database->userentities($args['userentityId']) 'userentity' => $this->getDatabase()->userentities($args['userentityId'])
]); ]);
} }
} }
public function UserobjectEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserobjectEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$userentity = $this->Database->userentities()->where('name = :1', $args['userentityName'])->fetch(); $userentity = $this->getDatabase()->userentities()->where('name = :1', $args['userentityName'])->fetch();
if ($args['userobjectId'] == 'new') if ($args['userobjectId'] == 'new')
{ {
return $this->View->render($response, 'userobjectform', [ return $this->renderPage($response, 'userobjectform', [
'userentity' => $userentity, 'userentity' => $userentity,
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('userentity-' . $args['userentityName']) 'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName'])
]); ]);
} }
else else
{ {
return $this->View->render($response, 'userobjectform', [ return $this->renderPage($response, 'userobjectform', [
'userentity' => $userentity, 'userentity' => $userentity,
'mode' => 'edit', 'mode' => 'edit',
'userobject' => $this->Database->userobjects($args['userobjectId']), 'userobject' => $this->getDatabase()->userobjects($args['userobjectId']),
'userfields' => $this->UserfieldsService->GetFields('userentity-' . $args['userentityName']) 'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName'])
]); ]);
} }
} }

View File

@@ -2,20 +2,13 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\SessionService;
use \Grocy\Services\DatabaseMigrationService;
use \Grocy\Services\DemoDataGeneratorService;
class LoginController extends BaseController class LoginController extends BaseController
{ {
public function __construct(\DI\Container $container, string $sessionCookieName) public function __construct(\DI\Container $container, string $sessionCookieName)
{ {
parent::__construct($container); parent::__construct($container);
$this->SessionService = new SessionService();
$this->SessionCookieName = $sessionCookieName; $this->SessionCookieName = $sessionCookieName;
} }
protected $SessionService;
protected $SessionCookieName; protected $SessionCookieName;
public function ProcessLogin(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProcessLogin(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@@ -23,13 +16,13 @@ class LoginController extends BaseController
$postParams = $request->getParsedBody(); $postParams = $request->getParsedBody();
if (isset($postParams['username']) && isset($postParams['password'])) if (isset($postParams['username']) && isset($postParams['password']))
{ {
$user = $this->Database->users()->where('username', $postParams['username'])->fetch(); $user = $this->getDatabase()->users()->where('username', $postParams['username'])->fetch();
$inputPassword = $postParams['password']; $inputPassword = $postParams['password'];
$stayLoggedInPermanently = $postParams['stay_logged_in'] == 'on'; $stayLoggedInPermanently = $postParams['stay_logged_in'] == 'on';
if ($user !== null && password_verify($inputPassword, $user->password)) if ($user !== null && password_verify($inputPassword, $user->password))
{ {
$sessionKey = $this->SessionService->CreateSession($user->id, $stayLoggedInPermanently); $sessionKey = $this->getSessionService()->CreateSession($user->id, $stayLoggedInPermanently);
setcookie($this->SessionCookieName, $sessionKey, PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX>>32); // Cookie expires never, but session validity is up to SessionService setcookie($this->SessionCookieName, $sessionKey, PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX>>32); // Cookie expires never, but session validity is up to SessionService
if (password_needs_rehash($user->password, PASSWORD_DEFAULT)) if (password_needs_rehash($user->password, PASSWORD_DEFAULT))
@@ -54,12 +47,12 @@ class LoginController extends BaseController
public function LoginPage(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function LoginPage(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'login'); return $this->renderPage($response, 'login');
} }
public function Logout(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Logout(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$this->SessionService->RemoveSession($_COOKIE[$this->SessionCookieName]); $this->getSessionService()->RemoveSession($_COOKIE[$this->SessionCookieName]);
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/')); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/'));
} }

View File

@@ -2,48 +2,42 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\ApplicationService;
use \Grocy\Services\ApiKeyService;
class OpenApiController extends BaseApiController class OpenApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->ApiKeyService = new ApiKeyService();
} }
protected $ApiKeyService;
public function DocumentationUi(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function DocumentationUi(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'openapiui'); return $this->render($response, 'openapiui');
} }
public function DocumentationSpec(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function DocumentationSpec(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$applicationService = new ApplicationService(); $applicationService = $this->getApplicationService();
$versionInfo = $applicationService->GetInstalledVersion(); $versionInfo = $applicationService->GetInstalledVersion();
$this->OpenApiSpec->info->version = $versionInfo->Version; $this->getOpenApiSpec()->info->version = $versionInfo->Version;
$this->OpenApiSpec->info->description = str_replace('PlaceHolderManageApiKeysUrl', $this->AppContainer->get('UrlManager')->ConstructUrl('/manageapikeys'), $this->OpenApiSpec->info->description); $this->getOpenApiSpec()->info->description = str_replace('PlaceHolderManageApiKeysUrl', $this->AppContainer->get('UrlManager')->ConstructUrl('/manageapikeys'), $this->getOpenApiSpec()->info->description);
$this->OpenApiSpec->servers[0]->url = $this->AppContainer->get('UrlManager')->ConstructUrl('/api'); $this->getOpenApiSpec()->servers[0]->url = $this->AppContainer->get('UrlManager')->ConstructUrl('/api');
return $this->ApiResponse($response, $this->OpenApiSpec); return $this->ApiResponse($response, $this->getOpenApiSpec());
} }
public function ApiKeysList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ApiKeysList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'manageapikeys', [ return $this->renderPage($response, 'manageapikeys', [
'apiKeys' => $this->Database->api_keys(), 'apiKeys' => $this->getDatabase()->api_keys(),
'users' => $this->Database->users() 'users' => $this->getDatabase()->users()
]); ]);
} }
public function CreateNewApiKey(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function CreateNewApiKey(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$newApiKey = $this->ApiKeyService->CreateApiKey(); $newApiKey = $this->getApiKeyService()->CreateApiKey();
$newApiKeyId = $this->ApiKeyService->GetApiKeyId($newApiKey); $newApiKeyId = $this->getApiKeyService()->GetApiKeyId($newApiKey);
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl("/manageapikeys?CreatedApiKeyId=$newApiKeyId")); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl("/manageapikeys?CreatedApiKeyId=$newApiKeyId"));
} }
} }

View File

@@ -2,18 +2,13 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\RecipesService;
class RecipesApiController extends BaseApiController class RecipesApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->RecipesService = new RecipesService();
} }
protected $RecipesService;
public function AddNotFulfilledProductsToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function AddNotFulfilledProductsToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
@@ -24,7 +19,7 @@ class RecipesApiController extends BaseApiController
$excludedProductIds = $requestBody['excludedProductIds']; $excludedProductIds = $requestBody['excludedProductIds'];
} }
$this->RecipesService->AddNotFulfilledProductsToShoppingList($args['recipeId'], $excludedProductIds); $this->getRecipesService()->AddNotFulfilledProductsToShoppingList($args['recipeId'], $excludedProductIds);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
@@ -32,7 +27,7 @@ class RecipesApiController extends BaseApiController
{ {
try try
{ {
$this->RecipesService->ConsumeRecipe($args['recipeId']); $this->getRecipesService()->ConsumeRecipe($args['recipeId']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -47,10 +42,10 @@ class RecipesApiController extends BaseApiController
{ {
if(!isset($args['recipeId'])) if(!isset($args['recipeId']))
{ {
return $this->ApiResponse($response, $this->RecipesService->GetRecipesResolved()); return $this->ApiResponse($response, $this->getRecipesService()->GetRecipesResolved());
} }
$recipeResolved = FindObjectInArrayByPropertyValue($this->RecipesService->GetRecipesResolved(), 'recipe_id', $args['recipeId']); $recipeResolved = FindObjectInArrayByPropertyValue($this->getRecipesService()->GetRecipesResolved(), 'recipe_id', $args['recipeId']);
if(!$recipeResolved) if(!$recipeResolved)
{ {
throw new \Exception('Recipe does not exist'); throw new \Exception('Recipe does not exist');

View File

@@ -3,47 +3,38 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\RecipesService; use \Grocy\Services\RecipesService;
use \Grocy\Services\StockService;
use \Grocy\Services\UserfieldsService;
class RecipesController extends BaseController class RecipesController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->RecipesService = new RecipesService();
$this->StockService = new StockService();
$this->UserfieldsService = new UserfieldsService();
} }
protected $RecipesService;
protected $StockService;
protected $UserfieldsService;
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$recipes = $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name'); $recipes = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name');
$recipesResolved = $this->RecipesService->GetRecipesResolved(); $recipesResolved = $this->getRecipesService()->GetRecipesResolved();
$selectedRecipe = null; $selectedRecipe = null;
$selectedRecipePositionsResolved = null; $selectedRecipePositionsResolved = null;
if (isset($request->getQueryParams()['recipe'])) if (isset($request->getQueryParams()['recipe']))
{ {
$selectedRecipe = $this->Database->recipes($request->getQueryParams()['recipe']); $selectedRecipe = $this->getDatabase()->recipes($request->getQueryParams()['recipe']);
$selectedRecipePositionsResolved = $this->Database->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $request->getQueryParams()['recipe'])->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); $selectedRecipePositionsResolved = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $request->getQueryParams()['recipe'])->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC');
} }
else else
{ {
foreach ($recipes as $recipe) foreach ($recipes as $recipe)
{ {
$selectedRecipe = $recipe; $selectedRecipe = $recipe;
$selectedRecipePositionsResolved = $this->Database->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $recipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); $selectedRecipePositionsResolved = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $recipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC');
break; break;
} }
} }
$selectedRecipeSubRecipes = $this->Database->recipes()->where('id IN (SELECT includes_recipe_id FROM recipes_nestings_resolved WHERE recipe_id = :1 AND includes_recipe_id != :1)', $selectedRecipe->id)->orderBy('name')->fetchAll(); $selectedRecipeSubRecipes = $this->getDatabase()->recipes()->where('id IN (SELECT includes_recipe_id FROM recipes_nestings_resolved WHERE recipe_id = :1 AND includes_recipe_id != :1)', $selectedRecipe->id)->orderBy('name')->fetchAll();
$selectedRecipeSubRecipesPositions = $this->Database->recipes_pos_resolved()->where('recipe_id = :1', $selectedRecipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC')->fetchAll(); $selectedRecipeSubRecipesPositions = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1', $selectedRecipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC')->fetchAll();
$includedRecipeIdsAbsolute = array(); $includedRecipeIdsAbsolute = array();
$includedRecipeIdsAbsolute[] = $selectedRecipe->id; $includedRecipeIdsAbsolute[] = $selectedRecipe->id;
@@ -52,22 +43,22 @@ class RecipesController extends BaseController
$includedRecipeIdsAbsolute[] = $subRecipe->id; $includedRecipeIdsAbsolute[] = $subRecipe->id;
} }
return $this->View->render($response, 'recipes', [ return $this->renderPage($response, 'recipes', [
'recipes' => $recipes, 'recipes' => $recipes,
'recipesResolved' => $recipesResolved, 'recipesResolved' => $recipesResolved,
'recipePositionsResolved' => $this->Database->recipes_pos_resolved()->where('recipe_type', RecipesService::RECIPE_TYPE_NORMAL), 'recipePositionsResolved' => $this->getDatabase()->recipes_pos_resolved()->where('recipe_type', RecipesService::RECIPE_TYPE_NORMAL),
'selectedRecipe' => $selectedRecipe, 'selectedRecipe' => $selectedRecipe,
'selectedRecipePositionsResolved' => $selectedRecipePositionsResolved, 'selectedRecipePositionsResolved' => $selectedRecipePositionsResolved,
'products' => $this->Database->products(), 'products' => $this->getDatabase()->products(),
'quantityUnits' => $this->Database->quantity_units(), 'quantityUnits' => $this->getDatabase()->quantity_units(),
'selectedRecipeSubRecipes' => $selectedRecipeSubRecipes, 'selectedRecipeSubRecipes' => $selectedRecipeSubRecipes,
'selectedRecipeSubRecipesPositions' => $selectedRecipeSubRecipesPositions, 'selectedRecipeSubRecipesPositions' => $selectedRecipeSubRecipesPositions,
'includedRecipeIdsAbsolute' => $includedRecipeIdsAbsolute, 'includedRecipeIdsAbsolute' => $includedRecipeIdsAbsolute,
'selectedRecipeTotalCosts' => FindObjectInArrayByPropertyValue($recipesResolved, 'recipe_id', $selectedRecipe->id)->costs, 'selectedRecipeTotalCosts' => FindObjectInArrayByPropertyValue($recipesResolved, 'recipe_id', $selectedRecipe->id)->costs,
'selectedRecipeTotalCalories' => FindObjectInArrayByPropertyValue($recipesResolved, 'recipe_id', $selectedRecipe->id)->calories, 'selectedRecipeTotalCalories' => FindObjectInArrayByPropertyValue($recipesResolved, 'recipe_id', $selectedRecipe->id)->calories,
'userfields' => $this->UserfieldsService->GetFields('recipes'), 'userfields' => $this->getUserfieldsService()->GetFields('recipes'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('recipes'), 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('recipes'),
'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved()
]); ]);
} }
@@ -76,26 +67,26 @@ class RecipesController extends BaseController
$recipeId = $args['recipeId']; $recipeId = $args['recipeId'];
if ($recipeId == 'new') if ($recipeId == 'new')
{ {
$newRecipe = $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->createRow(array( $newRecipe = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->createRow(array(
'name' => $this->LocalizationService->__t('New recipe') 'name' => $this->getLocalizationService()->__t('New recipe')
)); ));
$newRecipe->save(); $newRecipe->save();
$recipeId = $this->Database->lastInsertId(); $recipeId = $this->getDatabase()->lastInsertId();
} }
return $this->View->render($response, 'recipeform', [ return $this->renderPage($response, 'recipeform', [
'recipe' => $this->Database->recipes($recipeId), 'recipe' => $this->getDatabase()->recipes($recipeId),
'recipePositions' => $this->Database->recipes_pos()->where('recipe_id', $recipeId), 'recipePositions' => $this->getDatabase()->recipes_pos()->where('recipe_id', $recipeId),
'mode' => 'edit', 'mode' => 'edit',
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units(), 'quantityunits' => $this->getDatabase()->quantity_units(),
'recipePositionsResolved' => $this->RecipesService->GetRecipesPosResolved(), 'recipePositionsResolved' => $this->getRecipesService()->GetRecipesPosResolved(),
'recipesResolved' => $this->RecipesService->GetRecipesResolved(), 'recipesResolved' => $this->getRecipesService()->GetRecipesResolved(),
'recipes' => $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name'), 'recipes' => $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name'),
'recipeNestings' => $this->Database->recipes_nestings()->where('recipe_id', $recipeId), 'recipeNestings' => $this->getDatabase()->recipes_nestings()->where('recipe_id', $recipeId),
'userfields' => $this->UserfieldsService->GetFields('recipes'), 'userfields' => $this->getUserfieldsService()->GetFields('recipes'),
'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved()
]); ]);
} }
@@ -103,39 +94,39 @@ class RecipesController extends BaseController
{ {
if ($args['recipePosId'] == 'new') if ($args['recipePosId'] == 'new')
{ {
return $this->View->render($response, 'recipeposform', [ return $this->renderPage($response, 'recipeposform', [
'mode' => 'create', 'mode' => 'create',
'recipe' => $this->Database->recipes($args['recipeId']), 'recipe' => $this->getDatabase()->recipes($args['recipeId']),
'recipePos' => new \stdClass(), 'recipePos' => new \stdClass(),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityUnits' => $this->Database->quantity_units()->orderBy('name'), 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved()
]); ]);
} }
else else
{ {
return $this->View->render($response, 'recipeposform', [ return $this->renderPage($response, 'recipeposform', [
'mode' => 'edit', 'mode' => 'edit',
'recipe' => $this->Database->recipes($args['recipeId']), 'recipe' => $this->getDatabase()->recipes($args['recipeId']),
'recipePos' => $this->Database->recipes_pos($args['recipePosId']), 'recipePos' => $this->getDatabase()->recipes_pos($args['recipePosId']),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityUnits' => $this->Database->quantity_units()->orderBy('name'), 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved()
]); ]);
} }
} }
public function RecipesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function RecipesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'recipessettings'); return $this->renderPage($response, 'recipessettings');
} }
public function MealPlan(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function MealPlan(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$recipes = $this->Database->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(); $recipes = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll();
$events = array(); $events = array();
foreach($this->Database->meal_plan() as $mealPlanEntry) foreach($this->getDatabase()->meal_plan() as $mealPlanEntry)
{ {
$recipe = FindObjectInArrayByPropertyValue($recipes, 'id', $mealPlanEntry['recipe_id']); $recipe = FindObjectInArrayByPropertyValue($recipes, 'id', $mealPlanEntry['recipe_id']);
$title = ''; $title = '';
@@ -147,7 +138,7 @@ class RecipesController extends BaseController
$productDetails = null; $productDetails = null;
if ($mealPlanEntry['product_id'] !== null) if ($mealPlanEntry['product_id'] !== null)
{ {
$productDetails = $this->StockService->GetProductDetails($mealPlanEntry['product_id']); $productDetails = $this->getStockService()->GetProductDetails($mealPlanEntry['product_id']);
} }
$events[] = array( $events[] = array(
@@ -162,14 +153,14 @@ class RecipesController extends BaseController
); );
} }
return $this->View->render($response, 'mealplan', [ return $this->renderPage($response, 'mealplan', [
'fullcalendarEventSources' => $events, 'fullcalendarEventSources' => $events,
'recipes' => $recipes, 'recipes' => $recipes,
'internalRecipes' => $this->Database->recipes()->whereNot('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(), 'internalRecipes' => $this->getDatabase()->recipes()->whereNot('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(),
'recipesResolved' => $this->RecipesService->GetRecipesResolved(), 'recipesResolved' => $this->getRecipesService()->GetRecipesResolved(),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityUnits' => $this->Database->quantity_units()->orderBy('name'), 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'quantityUnitConversionsResolved' => $this->Database->quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved()
]); ]);
} }
} }

View File

@@ -9,16 +9,13 @@ class StockApiController extends BaseApiController
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->StockService = new StockService();
} }
protected $StockService;
public function ProductDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
{ {
return $this->ApiResponse($response, $this->StockService->GetProductDetails($args['productId'])); return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($args['productId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -30,8 +27,8 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$productId = $this->StockService->GetProductIdFromBarcode($args['barcode']); $productId = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
return $this->ApiResponse($response, $this->StockService->GetProductDetails($productId)); return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($productId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -43,7 +40,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->StockService->GetProductPriceHistory($args['productId'])); return $this->ApiResponse($response, $this->getStockService()->GetProductPriceHistory($args['productId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -91,8 +88,8 @@ class StockApiController extends BaseApiController
$transactionType = $requestBody['transactiontype']; $transactionType = $requestBody['transactiontype'];
} }
$bookingId = $this->StockService->AddProduct($args['productId'], $requestBody['amount'], $bestBeforeDate, $transactionType, date('Y-m-d'), $price, $locationId); $bookingId = $this->getStockService()->AddProduct($args['productId'], $requestBody['amount'], $bestBeforeDate, $transactionType, date('Y-m-d'), $price, $locationId);
return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -104,7 +101,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
return $this->AddProduct($request, $response, $args); return $this->AddProduct($request, $response, $args);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -147,8 +144,8 @@ class StockApiController extends BaseApiController
$locationId = $requestBody['location_id']; $locationId = $requestBody['location_id'];
} }
$bookingId = $this->StockService->EditStockEntry($args['entryId'], $requestBody['amount'], $bestBeforeDate, $locationId, $price, $requestBody['open'], $requestBody['purchased_date']); $bookingId = $this->getStockService()->EditStockEntry($args['entryId'], $requestBody['amount'], $bestBeforeDate, $locationId, $price, $requestBody['open'], $requestBody['purchased_date']);
return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -188,8 +185,8 @@ class StockApiController extends BaseApiController
$specificStockEntryId = $requestBody['stock_entry_id']; $specificStockEntryId = $requestBody['stock_entry_id'];
} }
$bookingId = $this->StockService->TransferProduct($args['productId'], $requestBody['amount'], $requestBody['location_id_from'], $requestBody['location_id_to'], $specificStockEntryId); $bookingId = $this->getStockService()->TransferProduct($args['productId'], $requestBody['amount'], $requestBody['location_id_from'], $requestBody['location_id_to'], $specificStockEntryId);
return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -201,7 +198,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
return $this->TransferProduct($request, $response, $args); return $this->TransferProduct($request, $response, $args);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -214,6 +211,8 @@ class StockApiController extends BaseApiController
{ {
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
$result = null;
try try
{ {
if ($requestBody === null) if ($requestBody === null)
@@ -256,20 +255,21 @@ class StockApiController extends BaseApiController
$recipeId = $requestBody['recipe_id']; $recipeId = $requestBody['recipe_id'];
} }
$bookingId = $this->StockService->ConsumeProduct($args['productId'], $requestBody['amount'], $spoiled, $transactionType, $specificStockEntryId, $recipeId, $locationId); $bookingId = $this->getStockService()->ConsumeProduct($args['productId'], $requestBody['amount'], $spoiled, $transactionType, $specificStockEntryId, $recipeId, $locationId);
return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); $result = $this->GenericErrorResponse($response, $ex->getMessage());
} }
return $result;
} }
public function ConsumeProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ConsumeProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
{ {
$args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
return $this->ConsumeProduct($request, $response, $args); return $this->ConsumeProduct($request, $response, $args);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -312,8 +312,8 @@ class StockApiController extends BaseApiController
$price = $requestBody['price']; $price = $requestBody['price'];
} }
$bookingId = $this->StockService->InventoryProduct($args['productId'], $requestBody['new_amount'], $bestBeforeDate, $locationId, $price); $bookingId = $this->getStockService()->InventoryProduct($args['productId'], $requestBody['new_amount'], $bestBeforeDate, $locationId, $price);
return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -325,7 +325,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
return $this->InventoryProduct($request, $response, $args); return $this->InventoryProduct($request, $response, $args);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -356,8 +356,8 @@ class StockApiController extends BaseApiController
$specificStockEntryId = $requestBody['stock_entry_id']; $specificStockEntryId = $requestBody['stock_entry_id'];
} }
$bookingId = $this->StockService->OpenProduct($args['productId'], $requestBody['amount'], $specificStockEntryId); $bookingId = $this->getStockService()->OpenProduct($args['productId'], $requestBody['amount'], $specificStockEntryId);
return $this->ApiResponse($response, $this->Database->stock_log($bookingId)); return $this->ApiResponse($response, $this->getDatabase()->stock_log($bookingId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -369,7 +369,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->StockService->GetProductIdFromBarcode($args['barcode']); $args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
return $this->OpenProduct($request, $response, $args); return $this->OpenProduct($request, $response, $args);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -380,7 +380,7 @@ class StockApiController extends BaseApiController
public function CurrentStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function CurrentStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, $this->StockService->GetCurrentStock()); return $this->ApiResponse($response, $this->getStockService()->GetCurrentStock());
} }
public function CurrentVolatileStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function CurrentVolatileStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@@ -391,9 +391,9 @@ class StockApiController extends BaseApiController
$nextXDays = $request->getQueryParams()['expiring_days']; $nextXDays = $request->getQueryParams()['expiring_days'];
} }
$expiringProducts = $this->StockService->GetExpiringProducts($nextXDays, true); $expiringProducts = $this->getStockService()->GetExpiringProducts($nextXDays, true);
$expiredProducts = $this->StockService->GetExpiringProducts(-1); $expiredProducts = $this->getStockService()->GetExpiringProducts(-1);
$missingProducts = $this->StockService->GetMissingProducts(); $missingProducts = $this->getStockService()->GetMissingProducts();
return $this->ApiResponse($response, array( return $this->ApiResponse($response, array(
'expiring_products' => $expiringProducts, 'expiring_products' => $expiringProducts,
'expired_products' => $expiredProducts, 'expired_products' => $expiredProducts,
@@ -413,7 +413,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']); $listId = intval($requestBody['list_id']);
} }
$this->StockService->AddMissingProductsToShoppingList($listId); $this->getStockService()->AddMissingProductsToShoppingList($listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -434,7 +434,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']); $listId = intval($requestBody['list_id']);
} }
$this->StockService->ClearShoppingList($listId); $this->getStockService()->ClearShoppingList($listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -476,7 +476,7 @@ class StockApiController extends BaseApiController
throw new \Exception("No product id was supplied"); throw new \Exception("No product id was supplied");
} }
$this->StockService->AddProductToShoppingList($productId, $amount, $note, $listId); $this->getStockService()->AddProductToShoppingList($productId, $amount, $note, $listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -512,7 +512,7 @@ class StockApiController extends BaseApiController
throw new \Exception("No product id was supplied"); throw new \Exception("No product id was supplied");
} }
$this->StockService->RemoveProductFromShoppingList($productId, $amount, $listId); $this->getStockService()->RemoveProductFromShoppingList($productId, $amount, $listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -531,7 +531,7 @@ class StockApiController extends BaseApiController
$addFoundProduct = true; $addFoundProduct = true;
} }
return $this->ApiResponse($response, $this->StockService->ExternalBarcodeLookup($args['barcode'], $addFoundProduct)); return $this->ApiResponse($response, $this->getStockService()->ExternalBarcodeLookup($args['barcode'], $addFoundProduct));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -543,7 +543,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$this->ApiResponse($response, $this->StockService->UndoBooking($args['bookingId'])); $this->ApiResponse($response, $this->getStockService()->UndoBooking($args['bookingId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -556,7 +556,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$this->ApiResponse($response, $this->StockService->UndoTransaction($args['transactionId'])); $this->ApiResponse($response, $this->getStockService()->UndoTransaction($args['transactionId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -573,24 +573,24 @@ class StockApiController extends BaseApiController
$allowSubproductSubstitution = true; $allowSubproductSubstitution = true;
} }
return $this->ApiResponse($response, $this->StockService->GetProductStockEntries($args['productId'], false, $allowSubproductSubstitution)); return $this->ApiResponse($response, $this->getStockService()->GetProductStockEntries($args['productId'], false, $allowSubproductSubstitution));
} }
public function ProductStockLocations(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductStockLocations(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, $this->StockService->GetProductStockLocations($args['productId'])); return $this->ApiResponse($response, $this->getStockService()->GetProductStockLocations($args['productId']));
} }
public function StockEntry(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function StockEntry(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, $this->StockService->GetStockEntry($args['entryId'])); return $this->ApiResponse($response, $this->getStockService()->GetStockEntry($args['entryId']));
} }
public function StockBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function StockBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
{ {
$stockLogRow = $this->Database->stock_log($args['bookingId']); $stockLogRow = $this->getDatabase()->stock_log($args['bookingId']);
if ($stockLogRow === null) if ($stockLogRow === null)
{ {
@@ -609,7 +609,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$transactionRows = $this->Database->stock_log()->where('transaction_id = :1', $args['transactionId'])->fetchAll(); $transactionRows = $this->getDatabase()->stock_log()->where('transaction_id = :1', $args['transactionId'])->fetchAll();
if (count($transactionRows) === 0) if (count($transactionRows) === 0)
{ {

View File

@@ -2,99 +2,90 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\StockService;
use \Grocy\Services\UsersService;
use \Grocy\Services\UserfieldsService;
class StockController extends BaseController class StockController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->StockService = new StockService();
$this->UserfieldsService = new UserfieldsService();
} }
protected $StockService;
protected $UserfieldsService;
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$usersService = new UsersService(); $usersService = $this->getUsersService();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_expring_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_expring_soon_days'];
return $this->View->render($response, 'stockoverview', [ return $this->renderPage($response, 'stockoverview', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'currentStock' => $this->StockService->GetCurrentStock(true), 'currentStock' => $this->getStockService()->GetCurrentStock(true),
'currentStockLocations' => $this->StockService->GetCurrentStockLocations(), 'currentStockLocations' => $this->getStockService()->GetCurrentStockLocations(),
'missingProducts' => $this->StockService->GetMissingProducts(), 'missingProducts' => $this->getStockService()->GetMissingProducts(),
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'productGroups' => $this->Database->product_groups()->orderBy('name'), 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('products'), 'userfields' => $this->getUserfieldsService()->GetFields('products'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('products') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products')
]); ]);
} }
public function Stockentries(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Stockentries(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
$usersService = new UsersService(); $usersService = $this->getUsersService();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_expring_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_expring_soon_days'];
return $this->View->render($response, 'stockentries', [ return $this->renderPage($response, 'stockentries', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'stockEntries' => $this->Database->stock()->orderBy('product_id'), 'stockEntries' => $this->getDatabase()->stock()->orderBy('product_id'),
'currentStockLocations' => $this->StockService->GetCurrentStockLocations(), 'currentStockLocations' => $this->getStockService()->GetCurrentStockLocations(),
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'userfields' => $this->UserfieldsService->GetFields('products'), 'userfields' => $this->getUserfieldsService()->GetFields('products'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('products') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products')
]); ]);
} }
public function Purchase(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Purchase(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'purchase', [ return $this->renderPage($response, 'purchase', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name') 'locations' => $this->getDatabase()->locations()->orderBy('name')
]); ]);
} }
public function Consume(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Consume(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'consume', [ return $this->renderPage($response, 'consume', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'recipes' => $this->Database->recipes()->orderBy('name'), 'recipes' => $this->getDatabase()->recipes()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name') 'locations' => $this->getDatabase()->locations()->orderBy('name')
]); ]);
} }
public function Transfer(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Transfer(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'transfer', [ return $this->renderPage($response, 'transfer', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'recipes' => $this->Database->recipes()->orderBy('name'), 'recipes' => $this->getDatabase()->recipes()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name') 'locations' => $this->getDatabase()->locations()->orderBy('name')
]); ]);
} }
public function Inventory(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Inventory(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'inventory', [ return $this->renderPage($response, 'inventory', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name') 'locations' => $this->getDatabase()->locations()->orderBy('name')
]); ]);
} }
public function StockEntryEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function StockEntryEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'stockentryform', [ return $this->renderPage($response, 'stockentryform', [
'stockEntry' => $this->Database->stock()->where('id', $args['entryId'])->fetch(), 'stockEntry' => $this->getDatabase()->stock()->where('id', $args['entryId'])->fetch(),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name') 'locations' => $this->getDatabase()->locations()->orderBy('name')
]); ]);
} }
@@ -106,65 +97,65 @@ class StockController extends BaseController
$listId = $request->getQueryParams()['list']; $listId = $request->getQueryParams()['list'];
} }
return $this->View->render($response, 'shoppinglist', [ return $this->renderPage($response, 'shoppinglist', [
'listItems' => $this->Database->shopping_list()->where('shopping_list_id = :1', $listId), 'listItems' => $this->getDatabase()->shopping_list()->where('shopping_list_id = :1', $listId),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'missingProducts' => $this->StockService->GetMissingProducts(), 'missingProducts' => $this->getStockService()->GetMissingProducts(),
'productGroups' => $this->Database->product_groups()->orderBy('name'), 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'),
'shoppingLists' => $this->Database->shopping_lists()->orderBy('name'), 'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name'),
'selectedShoppingListId' => $listId, 'selectedShoppingListId' => $listId,
'userfields' => $this->UserfieldsService->GetFields('products'), 'userfields' => $this->getUserfieldsService()->GetFields('products'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('products') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products')
]); ]);
} }
public function ProductsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'products', [ return $this->renderPage($response, 'products', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'productGroups' => $this->Database->product_groups()->orderBy('name'), 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('products'), 'userfields' => $this->getUserfieldsService()->GetFields('products'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('products') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products')
]); ]);
} }
public function StockSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function StockSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'stocksettings', [ return $this->renderPage($response, 'stocksettings', [
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'productGroups' => $this->Database->product_groups()->orderBy('name') 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name')
]); ]);
} }
public function LocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function LocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'locations', [ return $this->renderPage($response, 'locations', [
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('locations'), 'userfields' => $this->getUserfieldsService()->GetFields('locations'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('locations') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('locations')
]); ]);
} }
public function ProductGroupsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductGroupsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'productgroups', [ return $this->renderPage($response, 'productgroups', [
'productGroups' => $this->Database->product_groups()->orderBy('name'), 'productGroups' => $this->getDatabase()->product_groups()->orderBy('name'),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('product_groups'), 'userfields' => $this->getUserfieldsService()->GetFields('product_groups'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('product_groups') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('product_groups')
]); ]);
} }
public function QuantityUnitsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function QuantityUnitsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'quantityunits', [ return $this->renderPage($response, 'quantityunits', [
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('quantity_units'), 'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('quantity_units') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('quantity_units')
]); ]);
} }
@@ -172,30 +163,30 @@ class StockController extends BaseController
{ {
if ($args['productId'] == 'new') if ($args['productId'] == 'new')
{ {
return $this->View->render($response, 'productform', [ return $this->renderPage($response, 'productform', [
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'productgroups' => $this->Database->product_groups()->orderBy('name'), 'productgroups' => $this->getDatabase()->product_groups()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('products'), 'userfields' => $this->getUserfieldsService()->GetFields('products'),
'products' => $this->Database->products()->where('parent_product_id IS NULL')->orderBy('name'), 'products' => $this->getDatabase()->products()->where('parent_product_id IS NULL')->orderBy('name'),
'isSubProductOfOthers' => false, 'isSubProductOfOthers' => false,
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
$product = $this->Database->products($args['productId']); $product = $this->getDatabase()->products($args['productId']);
return $this->View->render($response, 'productform', [ return $this->renderPage($response, 'productform', [
'product' => $product, 'product' => $product,
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'productgroups' => $this->Database->product_groups()->orderBy('name'), 'productgroups' => $this->getDatabase()->product_groups()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('products'), 'userfields' => $this->getUserfieldsService()->GetFields('products'),
'products' => $this->Database->products()->where('id != :1 AND parent_product_id IS NULL', $product->id)->orderBy('name'), 'products' => $this->getDatabase()->products()->where('id != :1 AND parent_product_id IS NULL', $product->id)->orderBy('name'),
'isSubProductOfOthers' => $this->Database->products()->where('parent_product_id = :1', $product->id)->count() !== 0, 'isSubProductOfOthers' => $this->getDatabase()->products()->where('parent_product_id = :1', $product->id)->count() !== 0,
'mode' => 'edit', 'mode' => 'edit',
'quConversions' => $this->Database->quantity_unit_conversions() 'quConversions' => $this->getDatabase()->quantity_unit_conversions()
]); ]);
} }
} }
@@ -204,17 +195,17 @@ class StockController extends BaseController
{ {
if ($args['locationId'] == 'new') if ($args['locationId'] == 'new')
{ {
return $this->View->render($response, 'locationform', [ return $this->renderPage($response, 'locationform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('locations') 'userfields' => $this->getUserfieldsService()->GetFields('locations')
]); ]);
} }
else else
{ {
return $this->View->render($response, 'locationform', [ return $this->renderPage($response, 'locationform', [
'location' => $this->Database->locations($args['locationId']), 'location' => $this->getDatabase()->locations($args['locationId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('locations') 'userfields' => $this->getUserfieldsService()->GetFields('locations')
]); ]);
} }
} }
@@ -223,17 +214,17 @@ class StockController extends BaseController
{ {
if ($args['productGroupId'] == 'new') if ($args['productGroupId'] == 'new')
{ {
return $this->View->render($response, 'productgroupform', [ return $this->renderPage($response, 'productgroupform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('product_groups') 'userfields' => $this->getUserfieldsService()->GetFields('product_groups')
]); ]);
} }
else else
{ {
return $this->View->render($response, 'productgroupform', [ return $this->renderPage($response, 'productgroupform', [
'group' => $this->Database->product_groups($args['productGroupId']), 'group' => $this->getDatabase()->product_groups($args['productGroupId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('product_groups') 'userfields' => $this->getUserfieldsService()->GetFields('product_groups')
]); ]);
} }
} }
@@ -242,25 +233,25 @@ class StockController extends BaseController
{ {
if ($args['quantityunitId'] == 'new') if ($args['quantityunitId'] == 'new')
{ {
return $this->View->render($response, 'quantityunitform', [ return $this->renderPage($response, 'quantityunitform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('quantity_units'), 'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'),
'pluralCount' => $this->LocalizationService->GetPluralCount(), 'pluralCount' => $this->getLocalizationService()->GetPluralCount(),
'pluralRule' => $this->LocalizationService->GetPluralDefinition() 'pluralRule' => $this->getLocalizationService()->GetPluralDefinition()
]); ]);
} }
else else
{ {
$quantityUnit = $this->Database->quantity_units($args['quantityunitId']); $quantityUnit = $this->getDatabase()->quantity_units($args['quantityunitId']);
return $this->View->render($response, 'quantityunitform', [ return $this->renderPage($response, 'quantityunitform', [
'quantityUnit' => $quantityUnit, 'quantityUnit' => $quantityUnit,
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('quantity_units'), 'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'),
'pluralCount' => $this->LocalizationService->GetPluralCount(), 'pluralCount' => $this->getLocalizationService()->GetPluralCount(),
'pluralRule' => $this->LocalizationService->GetPluralDefinition(), 'pluralRule' => $this->getLocalizationService()->GetPluralDefinition(),
'defaultQuConversions' => $this->Database->quantity_unit_conversions()->where('from_qu_id = :1 AND product_id IS NULL', $quantityUnit->id), 'defaultQuConversions' => $this->getDatabase()->quantity_unit_conversions()->where('from_qu_id = :1 AND product_id IS NULL', $quantityUnit->id),
'quantityUnits' => $this->Database->quantity_units() 'quantityUnits' => $this->getDatabase()->quantity_units()
]); ]);
} }
} }
@@ -269,18 +260,18 @@ class StockController extends BaseController
{ {
if ($args['itemId'] == 'new') if ($args['itemId'] == 'new')
{ {
return $this->View->render($response, 'shoppinglistitemform', [ return $this->renderPage($response, 'shoppinglistitemform', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'shoppingLists' => $this->Database->shopping_lists()->orderBy('name'), 'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name'),
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
return $this->View->render($response, 'shoppinglistitemform', [ return $this->renderPage($response, 'shoppinglistitemform', [
'listItem' => $this->Database->shopping_list($args['itemId']), 'listItem' => $this->getDatabase()->shopping_list($args['itemId']),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'shoppingLists' => $this->Database->shopping_lists()->orderBy('name'), 'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name'),
'mode' => 'edit' 'mode' => 'edit'
]); ]);
} }
@@ -290,14 +281,14 @@ class StockController extends BaseController
{ {
if ($args['listId'] == 'new') if ($args['listId'] == 'new')
{ {
return $this->View->render($response, 'shoppinglistform', [ return $this->renderPage($response, 'shoppinglistform', [
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
return $this->View->render($response, 'shoppinglistform', [ return $this->renderPage($response, 'shoppinglistform', [
'shoppingList' => $this->Database->shopping_lists($args['listId']), 'shoppingList' => $this->getDatabase()->shopping_lists($args['listId']),
'mode' => 'edit' 'mode' => 'edit'
]); ]);
} }
@@ -305,26 +296,26 @@ class StockController extends BaseController
public function ShoppingListSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ShoppingListSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'shoppinglistsettings'); return $this->renderPage($response, 'shoppinglistsettings');
} }
public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'stockjournal', [ return $this->renderPage($response, 'stockjournal', [
'stockLog' => $this->Database->stock_log()->orderBy('row_created_timestamp', 'DESC'), 'stockLog' => $this->getDatabase()->stock_log()->orderBy('row_created_timestamp', 'DESC'),
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name') 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name')
]); ]);
} }
public function LocationContentSheet(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function LocationContentSheet(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'locationcontentsheet', [ return $this->renderPage($response, 'locationcontentsheet', [
'products' => $this->Database->products()->orderBy('name'), 'products' => $this->getDatabase()->products()->orderBy('name'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'locations' => $this->Database->locations()->orderBy('name'), 'locations' => $this->getDatabase()->locations()->orderBy('name'),
'currentStockLocationContent' => $this->StockService->GetCurrentStockLocationContent() 'currentStockLocationContent' => $this->getStockService()->GetCurrentStockLocationContent()
]); ]);
} }
@@ -333,32 +324,32 @@ class StockController extends BaseController
$product = null; $product = null;
if (isset($request->getQueryParams()['product'])) if (isset($request->getQueryParams()['product']))
{ {
$product = $this->Database->products($request->getQueryParams()['product']); $product = $this->getDatabase()->products($request->getQueryParams()['product']);
} }
$defaultQuUnit = null; $defaultQuUnit = null;
if (isset($request->getQueryParams()['qu-unit'])) if (isset($request->getQueryParams()['qu-unit']))
{ {
$defaultQuUnit = $this->Database->quantity_units($request->getQueryParams()['qu-unit']); $defaultQuUnit = $this->getDatabase()->quantity_units($request->getQueryParams()['qu-unit']);
} }
if ($args['quConversionId'] == 'new') if ($args['quConversionId'] == 'new')
{ {
return $this->View->render($response, 'quantityunitconversionform', [ return $this->renderPage($response, 'quantityunitconversionform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('quantity_unit_conversions'), 'userfields' => $this->getUserfieldsService()->GetFields('quantity_unit_conversions'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'product' => $product, 'product' => $product,
'defaultQuUnit' => $defaultQuUnit 'defaultQuUnit' => $defaultQuUnit
]); ]);
} }
else else
{ {
return $this->View->render($response, 'quantityunitconversionform', [ return $this->renderPage($response, 'quantityunitconversionform', [
'quConversion' => $this->Database->quantity_unit_conversions($args['quConversionId']), 'quConversion' => $this->getDatabase()->quantity_unit_conversions($args['quConversionId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('quantity_unit_conversions'), 'userfields' => $this->getUserfieldsService()->GetFields('quantity_unit_conversions'),
'quantityunits' => $this->Database->quantity_units()->orderBy('name'), 'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name'),
'product' => $product, 'product' => $product,
'defaultQuUnit' => $defaultQuUnit 'defaultQuUnit' => $defaultQuUnit
]); ]);
@@ -367,8 +358,8 @@ class StockController extends BaseController
public function QuantityUnitPluralFormTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function QuantityUnitPluralFormTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'quantityunitpluraltesting', [ return $this->renderPage($response, 'quantityunitpluraltesting', [
'quantityUnits' => $this->Database->quantity_units()->orderBy('name') 'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name')
]); ]);
} }
} }

View File

@@ -2,25 +2,17 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\DatabaseService;
use \Grocy\Services\ApplicationService;
class SystemApiController extends BaseApiController class SystemApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->DatabaseService = new DatabaseService();
$this->ApplicationService = new ApplicationService();
} }
protected $DatabaseService;
protected $ApplicationService;
public function GetDbChangedTime(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetDbChangedTime(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, array( return $this->ApiResponse($response, array(
'changed_time' => $this->DatabaseService->GetDbChangedTime() 'changed_time' => $this->getDatabaseService()->GetDbChangedTime()
)); ));
} }
@@ -32,7 +24,7 @@ class SystemApiController extends BaseApiController
{ {
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
$this->LocalizationService->CheckAndAddMissingTranslationToPot($requestBody['text']); $this->getLocalizationService()->CheckAndAddMissingTranslationToPot($requestBody['text']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -44,6 +36,6 @@ class SystemApiController extends BaseApiController
public function GetSystemInfo(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetSystemInfo(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, $this->ApplicationService->GetSystemInfo()); return $this->ApiResponse($response, $this->getApplicationService()->GetSystemInfo());
} }
} }

View File

@@ -2,29 +2,26 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\ApplicationService;
use \Grocy\Services\DatabaseMigrationService; use \Grocy\Services\DatabaseMigrationService;
use \Grocy\Services\DemoDataGeneratorService; use \Grocy\Services\DemoDataGeneratorService;
class SystemController extends BaseController class SystemController extends BaseController
{ {
protected $ApplicationService;
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->ApplicationService = new ApplicationService();
} }
public function Root(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Root(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
// Schema migration is done here // Schema migration is done here
$databaseMigrationService = new DatabaseMigrationService(); $databaseMigrationService = DatabaseMigrationService::getInstance();
$databaseMigrationService->MigrateDatabase(); $databaseMigrationService->MigrateDatabase();
if (GROCY_MODE === 'dev' || GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease') if (GROCY_MODE === 'dev' || GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease')
{ {
$demoDataGeneratorService = new DemoDataGeneratorService(); $demoDataGeneratorService = DemoDataGeneratorService::getInstance();
$demoDataGeneratorService->PopulateDemoData(); $demoDataGeneratorService->PopulateDemoData();
} }
@@ -96,14 +93,14 @@ class SystemController extends BaseController
public function About(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function About(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'about', [ return $this->renderPage($response, 'about', [
'system_info' => $this->ApplicationService->GetSystemInfo(), 'system_info' => $this->getApplicationService()->GetSystemInfo(),
'changelog' => $this->ApplicationService->GetChangelog() 'changelog' => $this->getApplicationService()->GetChangelog()
]); ]);
} }
public function BarcodeScannerTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function BarcodeScannerTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'barcodescannertesting'); return $this->renderPage($response, 'barcodescannertesting');
} }
} }

View File

@@ -2,21 +2,16 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\TasksService;
class TasksApiController extends BaseApiController class TasksApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->TasksService = new TasksService();
} }
protected $TasksService;
public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->ApiResponse($response, $this->TasksService->GetCurrent()); return $this->ApiResponse($response, $this->getTasksService()->GetCurrent());
} }
public function MarkTaskAsCompleted(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function MarkTaskAsCompleted(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@@ -31,7 +26,7 @@ class TasksApiController extends BaseApiController
$doneTime = $requestBody['done_time']; $doneTime = $requestBody['done_time'];
} }
$this->TasksService->MarkTaskAsCompleted($args['taskId'], $doneTime); $this->getTasksService()->MarkTaskAsCompleted($args['taskId'], $doneTime);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -44,7 +39,7 @@ class TasksApiController extends BaseApiController
{ {
try try
{ {
$this->TasksService->UndoTask($args['taskId']); $this->getTasksService()->UndoTask($args['taskId']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@@ -2,43 +2,34 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\TasksService;
use \Grocy\Services\UsersService;
use \Grocy\Services\UserfieldsService;
class TasksController extends BaseController class TasksController extends BaseController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->TasksService = new TasksService();
$this->UserfieldsService = new UserfieldsService();
} }
protected $TasksService;
protected $UserfieldsService;
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
if (isset($request->getQueryParams()['include_done'])) if (isset($request->getQueryParams()['include_done']))
{ {
$tasks = $this->Database->tasks()->orderBy('name'); $tasks = $this->getDatabase()->tasks()->orderBy('name');
} }
else else
{ {
$tasks = $this->TasksService->GetCurrent(); $tasks = $this->getTasksService()->GetCurrent();
} }
$usersService = new UsersService(); $usersService = $this->getUsersService();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['tasks_due_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['tasks_due_soon_days'];
return $this->View->render($response, 'tasks', [ return $this->renderPage($response, 'tasks', [
'tasks' => $tasks, 'tasks' => $tasks,
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'taskCategories' => $this->Database->task_categories()->orderBy('name'), 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'),
'users' => $this->Database->users(), 'users' => $this->getDatabase()->users(),
'userfields' => $this->UserfieldsService->GetFields('tasks'), 'userfields' => $this->getUserfieldsService()->GetFields('tasks'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('tasks') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('tasks')
]); ]);
} }
@@ -46,31 +37,31 @@ class TasksController extends BaseController
{ {
if ($args['taskId'] == 'new') if ($args['taskId'] == 'new')
{ {
return $this->View->render($response, 'taskform', [ return $this->renderPage($response, 'taskform', [
'mode' => 'create', 'mode' => 'create',
'taskCategories' => $this->Database->task_categories()->orderBy('name'), 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'),
'users' => $this->Database->users()->orderBy('username'), 'users' => $this->getDatabase()->users()->orderBy('username'),
'userfields' => $this->UserfieldsService->GetFields('tasks') 'userfields' => $this->getUserfieldsService()->GetFields('tasks')
]); ]);
} }
else else
{ {
return $this->View->render($response, 'taskform', [ return $this->renderPage($response, 'taskform', [
'task' => $this->Database->tasks($args['taskId']), 'task' => $this->getDatabase()->tasks($args['taskId']),
'mode' => 'edit', 'mode' => 'edit',
'taskCategories' => $this->Database->task_categories()->orderBy('name'), 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'),
'users' => $this->Database->users()->orderBy('username'), 'users' => $this->getDatabase()->users()->orderBy('username'),
'userfields' => $this->UserfieldsService->GetFields('tasks') 'userfields' => $this->getUserfieldsService()->GetFields('tasks')
]); ]);
} }
} }
public function TaskCategoriesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TaskCategoriesList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'taskcategories', [ return $this->renderPage($response, 'taskcategories', [
'taskCategories' => $this->Database->task_categories()->orderBy('name'), 'taskCategories' => $this->getDatabase()->task_categories()->orderBy('name'),
'userfields' => $this->UserfieldsService->GetFields('task_categories'), 'userfields' => $this->getUserfieldsService()->GetFields('task_categories'),
'userfieldValues' => $this->UserfieldsService->GetAllValues('task_categories') 'userfieldValues' => $this->getUserfieldsService()->GetAllValues('task_categories')
]); ]);
} }
@@ -78,23 +69,23 @@ class TasksController extends BaseController
{ {
if ($args['categoryId'] == 'new') if ($args['categoryId'] == 'new')
{ {
return $this->View->render($response, 'taskcategoryform', [ return $this->renderPage($response, 'taskcategoryform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->UserfieldsService->GetFields('task_categories') 'userfields' => $this->getUserfieldsService()->GetFields('task_categories')
]); ]);
} }
else else
{ {
return $this->View->render($response, 'taskcategoryform', [ return $this->renderPage($response, 'taskcategoryform', [
'category' => $this->Database->task_categories($args['categoryId']), 'category' => $this->getDatabase()->task_categories($args['categoryId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->UserfieldsService->GetFields('task_categories') 'userfields' => $this->getUserfieldsService()->GetFields('task_categories')
]); ]);
} }
} }
public function TasksSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TasksSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'taskssettings'); return $this->renderPage($response, 'taskssettings');
} }
} }

View File

@@ -2,23 +2,18 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use \Grocy\Services\UsersService;
class UsersApiController extends BaseApiController class UsersApiController extends BaseApiController
{ {
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
$this->UsersService = new UsersService();
} }
protected $UsersService;
public function GetUsers(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetUsers(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try try
{ {
return $this->ApiResponse($response, $this->UsersService->GetUsersAsDto()); return $this->ApiResponse($response, $this->getUsersService()->GetUsersAsDto());
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@@ -37,7 +32,7 @@ class UsersApiController extends BaseApiController
throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)'); throw new \Exception('Request body could not be parsed (probably invalid JSON format or missing/wrong Content-Type header)');
} }
$this->UsersService->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']); $this->getUsersService()->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -50,7 +45,7 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
$this->UsersService->DeleteUser($args['userId']); $this->getUsersService()->DeleteUser($args['userId']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -65,7 +60,7 @@ class UsersApiController extends BaseApiController
try try
{ {
$this->UsersService->EditUser($args['userId'], $requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']); $this->getUsersService()->EditUser($args['userId'], $requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -78,7 +73,7 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
$value = $this->UsersService->GetUserSetting(GROCY_USER_ID, $args['settingKey']); $value = $this->getUsersService()->GetUserSetting(GROCY_USER_ID, $args['settingKey']);
return $this->ApiResponse($response, array('value' => $value)); return $this->ApiResponse($response, array('value' => $value));
} }
catch (\Exception $ex) catch (\Exception $ex)
@@ -93,7 +88,7 @@ class UsersApiController extends BaseApiController
{ {
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
$value = $this->UsersService->SetUserSetting(GROCY_USER_ID, $args['settingKey'], $requestBody['value']); $value = $this->getUsersService()->SetUserSetting(GROCY_USER_ID, $args['settingKey'], $requestBody['value']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@@ -6,8 +6,8 @@ class UsersController extends BaseController
{ {
public function UsersList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UsersList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->View->render($response, 'users', [ return $this->renderPage($response, 'users', [
'users' => $this->Database->users()->orderBy('username') 'users' => $this->getDatabase()->users()->orderBy('username')
]); ]);
} }
@@ -15,14 +15,14 @@ class UsersController extends BaseController
{ {
if ($args['userId'] == 'new') if ($args['userId'] == 'new')
{ {
return $this->View->render($response, 'userform', [ return $this->renderPage($response, 'userform', [
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
return $this->View->render($response, 'userform', [ return $this->renderPage($response, 'userform', [
'user' => $this->Database->users($args['userId']), 'user' => $this->getDatabase()->users($args['userId']),
'mode' => 'edit' 'mode' => 'edit'
]); ]);
} }

View File

@@ -39,7 +39,7 @@ class ApiKeyAuthMiddleware extends BaseMiddleware
$validApiKey = true; $validApiKey = true;
$usedApiKey = null; $usedApiKey = null;
$sessionService = new SessionService(); $sessionService = SessionService::getInstance();
if (!isset($_COOKIE[$this->SessionCookieName]) || !$sessionService->IsValidSession($_COOKIE[$this->SessionCookieName])) if (!isset($_COOKIE[$this->SessionCookieName]) || !$sessionService->IsValidSession($_COOKIE[$this->SessionCookieName]))
{ {
$validSession = false; $validSession = false;

View File

@@ -9,7 +9,7 @@ class BaseMiddleware
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
$this->AppContainer = $container; $this->AppContainer = $container;
$this->ApplicationService = new ApplicationService(); $this->ApplicationService = ApplicationService::getInstance();
} }
protected $AppContainer; protected $AppContainer;

View File

@@ -25,7 +25,7 @@ class SessionAuthMiddleware extends BaseMiddleware
$routeContext = RouteContext::fromRequest($request); $routeContext = RouteContext::fromRequest($request);
$route = $routeContext->getRoute(); $route = $routeContext->getRoute();
$routeName = $route->getName(); $routeName = $route->getName();
$sessionService = new SessionService(); $sessionService = SessionService::getInstance();
if ($routeName === 'root') if ($routeName === 'root')
{ {

View File

@@ -2,7 +2,7 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
$db = $this->DatabaseService->GetDbConnection(); $db = $this->getDatabaseService()->GetDbConnection();
if (defined('GROCY_HTTP_USER')) if (defined('GROCY_HTTP_USER'))
{ {

View File

@@ -3,9 +3,9 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
use \Grocy\Services\LocalizationService; use \Grocy\Services\LocalizationService;
$localizationService = new LocalizationService(GROCY_CULTURE); $localizationService = $this->getLocalizationService();
$db = $this->DatabaseService->GetDbConnection(); $db = $this->getDatabaseService()->GetDbConnection();
if ($db->quantity_units()->count() === 0) if ($db->quantity_units()->count() === 0)
{ {

View File

@@ -3,11 +3,11 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
use \Grocy\Services\LocalizationService; use \Grocy\Services\LocalizationService;
$localizationService = new LocalizationService(GROCY_CULTURE); $localizationService = $this->getLocalizationService();
$db = $this->DatabaseService->GetDbConnection(); $db = $this->getDatabaseService()->GetDbConnection();
$defaultShoppingList = $this->Database->shopping_lists()->where('id = 1')->fetch(); $defaultShoppingList = $db->shopping_lists()->where('id = 1')->fetch();
$defaultShoppingList->update(array( $defaultShoppingList->update(array(
'name' => $localizationService->__t('Shopping list') 'name' => $localizationService->__t('Shopping list')
)); ));

View File

@@ -9,6 +9,7 @@ use Grocy\Middleware\ApiKeyAuthMiddleware;
$app->group('', function(RouteCollectorProxy $group) $app->group('', function(RouteCollectorProxy $group)
{ {
// System routes // System routes
$group->get('/', '\Grocy\Controllers\SystemController:Root')->setName('root'); $group->get('/', '\Grocy\Controllers\SystemController:Root')->setName('root');
$group->get('/about', '\Grocy\Controllers\SystemController:About'); $group->get('/about', '\Grocy\Controllers\SystemController:About');

View File

@@ -18,16 +18,16 @@ class ApiKeyService extends BaseService
} }
else else
{ {
$apiKeyRow = $this->Database->api_keys()->where('api_key = :1 AND expires > :2 AND key_type = :3', $apiKey, date('Y-m-d H:i:s', time()), $keyType)->fetch(); $apiKeyRow = $this->getDatabase()->api_keys()->where('api_key = :1 AND expires > :2 AND key_type = :3', $apiKey, date('Y-m-d H:i:s', time()), $keyType)->fetch();
if ($apiKeyRow !== null) if ($apiKeyRow !== null)
{ {
// This should not change the database file modification time as this is used // This should not change the database file modification time as this is used
// to determine if REALLY something has changed // to determine if REALLY something has changed
$dbModTime = $this->DatabaseService->GetDbChangedTime(); $dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$apiKeyRow->update(array( $apiKeyRow->update(array(
'last_used' => date('Y-m-d H:i:s', time()) 'last_used' => date('Y-m-d H:i:s', time())
)); ));
$this->DatabaseService->SetDbChangedTime($dbModTime); $this->getDatabaseService()->SetDbChangedTime($dbModTime);
return true; return true;
} }
@@ -45,7 +45,7 @@ class ApiKeyService extends BaseService
{ {
$newApiKey = $this->GenerateApiKey(); $newApiKey = $this->GenerateApiKey();
$apiKeyRow = $this->Database->api_keys()->createRow(array( $apiKeyRow = $this->getDatabase()->api_keys()->createRow(array(
'api_key' => $newApiKey, 'api_key' => $newApiKey,
'user_id' => GROCY_USER_ID, 'user_id' => GROCY_USER_ID,
'expires' => '2999-12-31 23:59:59', // Default is that API keys expire never 'expires' => '2999-12-31 23:59:59', // Default is that API keys expire never
@@ -58,21 +58,21 @@ class ApiKeyService extends BaseService
public function RemoveApiKey($apiKey) public function RemoveApiKey($apiKey)
{ {
$this->Database->api_keys()->where('api_key', $apiKey)->delete(); $this->getDatabase()->api_keys()->where('api_key', $apiKey)->delete();
} }
public function GetApiKeyId($apiKey) public function GetApiKeyId($apiKey)
{ {
$apiKey = $this->Database->api_keys()->where('api_key', $apiKey)->fetch(); $apiKey = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch();
return $apiKey->id; return $apiKey->id;
} }
public function GetUserByApiKey($apiKey) public function GetUserByApiKey($apiKey)
{ {
$apiKeyRow = $this->Database->api_keys()->where('api_key', $apiKey)->fetch(); $apiKeyRow = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch();
if ($apiKeyRow !== null) if ($apiKeyRow !== null)
{ {
return $this->Database->users($apiKeyRow->user_id); return $this->getDatabase()->users($apiKeyRow->user_id);
} }
return null; return null;
} }
@@ -87,7 +87,7 @@ class ApiKeyService extends BaseService
} }
else else
{ {
$apiKeyRow = $this->Database->api_keys()->where('key_type = :1 AND expires > :2', $keyType, date('Y-m-d H:i:s', time()))->fetch(); $apiKeyRow = $this->getDatabase()->api_keys()->where('key_type = :1 AND expires > :2', $keyType, date('Y-m-d H:i:s', time()))->fetch();
if ($apiKeyRow !== null) if ($apiKeyRow !== null)
{ {
return $apiKeyRow->api_key; return $apiKeyRow->api_key;

View File

@@ -5,6 +5,7 @@ namespace Grocy\Services;
class ApplicationService extends BaseService class ApplicationService extends BaseService
{ {
private $InstalledVersion; private $InstalledVersion;
public function GetInstalledVersion() public function GetInstalledVersion()
{ {
if ($this->InstalledVersion == null) if ($this->InstalledVersion == null)

View File

@@ -2,20 +2,64 @@
namespace Grocy\Services; namespace Grocy\Services;
use \Grocy\Services\DatabaseService; #use \Grocy\Services\DatabaseService;
use \Grocy\Services\LocalizationService; #use \Grocy\Services\LocalizationService;
class BaseService class BaseService
{ {
public function __construct() { public function __construct() {
$this->DatabaseService = new DatabaseService();
$this->Database = $this->DatabaseService->GetDbConnection();
$localizationService = new LocalizationService(GROCY_CULTURE);
$this->LocalizationService = $localizationService;
} }
protected $DatabaseService; private static $instances = array();
protected $Database;
protected $LocalizationService; public static function getInstance()
{
$className = get_called_class();
if(!isset(self::$instances[$className]))
{
self::$instances[$className] = new $className();
}
return self::$instances[$className];
}
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getDatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
protected function getLocalizationService()
{
return LocalizationService::getInstance(GROCY_CULTURE);
}
protected function getStockservice()
{
return StockService::getInstance();
}
protected function getTasksService()
{
return TasksService::getInstance();
}
protected function getChoresService()
{
return ChoresService::getInstance();
}
protected function getBatteriesService()
{
return BatteriesService::getInstance();
}
protected function getUsersService()
{
return UsersService::getInstance();
}
} }

View File

@@ -7,7 +7,7 @@ class BatteriesService extends BaseService
public function GetCurrent() public function GetCurrent()
{ {
$sql = 'SELECT * from batteries_current'; $sql = 'SELECT * from batteries_current';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetBatteryDetails(int $batteryId) public function GetBatteryDetails(int $batteryId)
@@ -17,10 +17,10 @@ class BatteriesService extends BaseService
throw new \Exception('Battery does not exist'); throw new \Exception('Battery does not exist');
} }
$battery = $this->Database->batteries($batteryId); $battery = $this->getDatabase()->batteries($batteryId);
$batteryChargeCyclesCount = $this->Database->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count(); $batteryChargeCyclesCount = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count();
$batteryLastChargedTime = $this->Database->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time'); $batteryLastChargedTime = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time');
$nextChargeTime = $this->Database->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time'); $nextChargeTime = $this->getDatabase()->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time');
return array( return array(
'battery' => $battery, 'battery' => $battery,
@@ -37,24 +37,24 @@ class BatteriesService extends BaseService
throw new \Exception('Battery does not exist'); throw new \Exception('Battery does not exist');
} }
$logRow = $this->Database->battery_charge_cycles()->createRow(array( $logRow = $this->getDatabase()->battery_charge_cycles()->createRow(array(
'battery_id' => $batteryId, 'battery_id' => $batteryId,
'tracked_time' => $trackedTime 'tracked_time' => $trackedTime
)); ));
$logRow->save(); $logRow->save();
return $this->Database->lastInsertId(); return $this->getDatabase()->lastInsertId();
} }
private function BatteryExists($batteryId) private function BatteryExists($batteryId)
{ {
$batteryRow = $this->Database->batteries()->where('id = :1', $batteryId)->fetch(); $batteryRow = $this->getDatabase()->batteries()->where('id = :1', $batteryId)->fetch();
return $batteryRow !== null; return $batteryRow !== null;
} }
public function UndoChargeCycle($chargeCycleId) public function UndoChargeCycle($chargeCycleId)
{ {
$logRow = $this->Database->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch(); $logRow = $this->getDatabase()->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch();
if ($logRow == null) if ($logRow == null)
{ {
throw new \Exception('Charge cycle does not exist or was already undone'); throw new \Exception('Charge cycle does not exist or was already undone');

View File

@@ -2,11 +2,11 @@
namespace Grocy\Services; namespace Grocy\Services;
use \Grocy\Services\StockService; #use \Grocy\Services\StockService;
use \Grocy\Services\TasksService; #use \Grocy\Services\TasksService;
use \Grocy\Services\ChoresService; #use \Grocy\Services\ChoresService;
use \Grocy\Services\BatteriesService; #use \Grocy\Services\BatteriesService;
use \Grocy\Services\UsersService; #use \Grocy\Services\UsersService;
use \Grocy\Helpers\UrlManager; use \Grocy\Helpers\UrlManager;
class CalendarService extends BaseService class CalendarService extends BaseService
@@ -14,27 +14,17 @@ class CalendarService extends BaseService
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
$this->StockService = new StockService();
$this->TasksService = new TasksService();
$this->ChoresService = new ChoresService();
$this->BatteriesService = new BatteriesService();
$this->UrlManager = new UrlManager(GROCY_BASE_URL); $this->UrlManager = new UrlManager(GROCY_BASE_URL);
} }
protected $StockService;
protected $TasksService;
protected $ChoresService;
protected $BatteriesService;
protected $UrlManager;
public function GetEvents() public function GetEvents()
{ {
$stockEvents = array(); $stockEvents = array();
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
$products = $this->Database->products(); $products = $this->getDatabase()->products();
$titlePrefix = $this->LocalizationService->__t('Product expires') . ': '; $titlePrefix = $this->getLocalizationService()->__t('Product expires') . ': ';
foreach($this->StockService->GetCurrentStock() as $currentStockEntry) foreach($this->getStockService()->GetCurrentStock() as $currentStockEntry)
{ {
if ($currentStockEntry->amount > 0) if ($currentStockEntry->amount > 0)
{ {
@@ -50,8 +40,8 @@ class CalendarService extends BaseService
$taskEvents = array(); $taskEvents = array();
if (GROCY_FEATURE_FLAG_TASKS) if (GROCY_FEATURE_FLAG_TASKS)
{ {
$titlePrefix = $this->LocalizationService->__t('Task due') . ': '; $titlePrefix = $this->getLocalizationService()->__t('Task due') . ': ';
foreach($this->TasksService->GetCurrent() as $currentTaskEntry) foreach($this->getTasksService()->GetCurrent() as $currentTaskEntry)
{ {
$taskEvents[] = array( $taskEvents[] = array(
'title' => $titlePrefix . $currentTaskEntry->name, 'title' => $titlePrefix . $currentTaskEntry->name,
@@ -64,19 +54,18 @@ class CalendarService extends BaseService
$choreEvents = array(); $choreEvents = array();
if (GROCY_FEATURE_FLAG_CHORES) if (GROCY_FEATURE_FLAG_CHORES)
{ {
$usersService = new UsersService(); $users = $this->getUsersService()->GetUsersAsDto();
$users = $usersService->GetUsersAsDto();
$chores = $this->Database->chores(); $chores = $this->getDatabase()->chores();
$titlePrefix = $this->LocalizationService->__t('Chore due') . ': '; $titlePrefix = $this->getLocalizationService()->__t('Chore due') . ': ';
foreach($this->ChoresService->GetCurrent() as $currentChoreEntry) foreach($this->getChoresService()->GetCurrent() as $currentChoreEntry)
{ {
$chore = FindObjectInArrayByPropertyValue($chores, 'id', $currentChoreEntry->chore_id); $chore = FindObjectInArrayByPropertyValue($chores, 'id', $currentChoreEntry->chore_id);
$assignedToText = ''; $assignedToText = '';
if (!empty($currentChoreEntry->next_execution_assigned_to_user_id)) if (!empty($currentChoreEntry->next_execution_assigned_to_user_id))
{ {
$assignedToText = ' (' . $this->LocalizationService->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')'; $assignedToText = ' (' . $this->getLocalizationService()->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')';
} }
$choreEvents[] = array( $choreEvents[] = array(
@@ -90,9 +79,9 @@ class CalendarService extends BaseService
$batteryEvents = array(); $batteryEvents = array();
if (GROCY_FEATURE_FLAG_BATTERIES) if (GROCY_FEATURE_FLAG_BATTERIES)
{ {
$batteries = $this->Database->batteries(); $batteries = $this->getDatabase()->batteries();
$titlePrefix = $this->LocalizationService->__t('Battery charge cycle due') . ': '; $titlePrefix = $this->getLocalizationService()->__t('Battery charge cycle due') . ': ';
foreach($this->BatteriesService->GetCurrent() as $currentBatteryEntry) foreach($this->getBatteriesService()->GetCurrent() as $currentBatteryEntry)
{ {
$batteryEvents[] = array( $batteryEvents[] = array(
'title' => $titlePrefix . FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name, 'title' => $titlePrefix . FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name,
@@ -105,13 +94,13 @@ class CalendarService extends BaseService
$mealPlanRecipeEvents = array(); $mealPlanRecipeEvents = array();
if (GROCY_FEATURE_FLAG_RECIPES) if (GROCY_FEATURE_FLAG_RECIPES)
{ {
$recipes = $this->Database->recipes(); $recipes = $this->getDatabase()->recipes();
$mealPlanDayRecipes = $this->Database->recipes()->where('type', 'mealplan-day'); $mealPlanDayRecipes = $this->getDatabase()->recipes()->where('type', 'mealplan-day');
$titlePrefix = $this->LocalizationService->__t('Meal plan recipe') . ': '; $titlePrefix = $this->getLocalizationService()->__t('Meal plan recipe') . ': ';
foreach($mealPlanDayRecipes as $mealPlanDayRecipe) foreach($mealPlanDayRecipes as $mealPlanDayRecipe)
{ {
$recipesOfCurrentDay = $this->Database->recipes_nestings_resolved()->where('recipe_id = :1 AND includes_recipe_id != :1', $mealPlanDayRecipe->id); $recipesOfCurrentDay = $this->getDatabase()->recipes_nestings_resolved()->where('recipe_id = :1 AND includes_recipe_id != :1', $mealPlanDayRecipe->id);
foreach ($recipesOfCurrentDay as $recipeOfCurrentDay) foreach ($recipesOfCurrentDay as $recipeOfCurrentDay)
{ {
$mealPlanRecipeEvents[] = array( $mealPlanRecipeEvents[] = array(
@@ -123,8 +112,8 @@ class CalendarService extends BaseService
} }
} }
$mealPlanDayNotes = $this->Database->meal_plan()->where('type', 'note'); $mealPlanDayNotes = $this->getDatabase()->meal_plan()->where('type', 'note');
$titlePrefix = $this->LocalizationService->__t('Meal plan note') . ': '; $titlePrefix = $this->getLocalizationService()->__t('Meal plan note') . ': ';
$mealPlanNotesEvents = array(); $mealPlanNotesEvents = array();
foreach($mealPlanDayNotes as $mealPlanDayNote) foreach($mealPlanDayNotes as $mealPlanDayNote)
{ {
@@ -135,9 +124,9 @@ class CalendarService extends BaseService
); );
} }
$products = $this->Database->products(); $products = $this->getDatabase()->products();
$mealPlanDayProducts = $this->Database->meal_plan()->where('type', 'product'); $mealPlanDayProducts = $this->getDatabase()->meal_plan()->where('type', 'product');
$titlePrefix = $this->LocalizationService->__t('Meal plan product') . ': '; $titlePrefix = $this->getLocalizationService()->__t('Meal plan product') . ': ';
$mealPlanProductEvents = array(); $mealPlanProductEvents = array();
foreach($mealPlanDayProducts as $mealPlanDayProduct) foreach($mealPlanDayProducts as $mealPlanDayProduct)
{ {

View File

@@ -2,7 +2,7 @@
namespace Grocy\Services; namespace Grocy\Services;
use \Grocy\Services\StockService; #use \Grocy\Services\StockService;
class ChoresService extends BaseService class ChoresService extends BaseService
{ {
@@ -21,15 +21,12 @@ class ChoresService extends BaseService
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
$this->StockService = new StockService();
} }
protected $StockService;
public function GetCurrent() public function GetCurrent()
{ {
$sql = 'SELECT * from chores_current'; $sql = 'SELECT * from chores_current';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetChoreDetails(int $choreId) public function GetChoreDetails(int $choreId)
@@ -39,15 +36,14 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist'); throw new \Exception('Chore does not exist');
} }
$usersService = new UsersService(); $users = $this->getUsersService()->GetUsersAsDto();
$users = $usersService->GetUsersAsDto();
$chore = $this->Database->chores($choreId); $chore = $this->getDatabase()->chores($choreId);
$choreTrackedCount = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->count(); $choreTrackedCount = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->count();
$choreLastTrackedTime = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time'); $choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$nextExecutionTime = $this->Database->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time'); $nextExecutionTime = $this->getDatabase()->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time');
$lastChoreLogRow = $this->Database->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch(); $lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch();
$lastDoneByUser = null; $lastDoneByUser = null;
if ($lastChoreLogRow !== null && !empty($lastChoreLogRow)) if ($lastChoreLogRow !== null && !empty($lastChoreLogRow))
{ {
@@ -77,31 +73,31 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist'); throw new \Exception('Chore does not exist');
} }
$userRow = $this->Database->users()->where('id = :1', $doneBy)->fetch(); $userRow = $this->getDatabase()->users()->where('id = :1', $doneBy)->fetch();
if ($userRow === null) if ($userRow === null)
{ {
throw new \Exception('User does not exist'); throw new \Exception('User does not exist');
} }
$chore = $this->Database->chores($choreId); $chore = $this->getDatabase()->chores($choreId);
if ($chore->track_date_only == 1) if ($chore->track_date_only == 1)
{ {
$trackedTime = substr($trackedTime, 0, 10) . ' 00:00:00'; $trackedTime = substr($trackedTime, 0, 10) . ' 00:00:00';
} }
$logRow = $this->Database->chores_log()->createRow(array( $logRow = $this->getDatabase()->chores_log()->createRow(array(
'chore_id' => $choreId, 'chore_id' => $choreId,
'tracked_time' => $trackedTime, 'tracked_time' => $trackedTime,
'done_by_user_id' => $doneBy 'done_by_user_id' => $doneBy
)); ));
$logRow->save(); $logRow->save();
$lastInsertId = $this->Database->lastInsertId(); $lastInsertId = $this->getDatabase()->lastInsertId();
$this->CalculateNextExecutionAssignment($choreId); $this->CalculateNextExecutionAssignment($choreId);
if ($chore->consume_product_on_execution == 1 && !empty($chore->product_id)) if ($chore->consume_product_on_execution == 1 && !empty($chore->product_id))
{ {
$this->StockService->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME); $this->getStockService()->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME);
} }
return $lastInsertId; return $lastInsertId;
@@ -109,13 +105,13 @@ class ChoresService extends BaseService
private function ChoreExists($choreId) private function ChoreExists($choreId)
{ {
$choreRow = $this->Database->chores()->where('id = :1', $choreId)->fetch(); $choreRow = $this->getDatabase()->chores()->where('id = :1', $choreId)->fetch();
return $choreRow !== null; return $choreRow !== null;
} }
public function UndoChoreExecution($executionId) public function UndoChoreExecution($executionId)
{ {
$logRow = $this->Database->chores_log()->where('id = :1 AND undone = 0', $executionId)->fetch(); $logRow = $this->getDatabase()->chores_log()->where('id = :1 AND undone = 0', $executionId)->fetch();
if ($logRow == null) if ($logRow == null)
{ {
throw new \Exception('Execution does not exist or was already undone'); throw new \Exception('Execution does not exist or was already undone');
@@ -135,13 +131,12 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist'); throw new \Exception('Chore does not exist');
} }
$chore = $this->Database->chores($choreId); $chore = $this->getDatabase()->chores($choreId);
$choreLastTrackedTime = $this->Database->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time'); $choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$lastChoreLogRow = $this->Database->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch(); $lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch();
$lastDoneByUserId = $lastChoreLogRow->done_by_user_id; $lastDoneByUserId = $lastChoreLogRow->done_by_user_id;
$usersService = new UsersService(); $users = $this->getUsersService()->GetUsersAsDto();
$users = $usersService->GetUsersAsDto();
$assignedUsers = array(); $assignedUsers = array();
foreach ($users as $user) foreach ($users as $user)
{ {
@@ -198,7 +193,7 @@ class ChoresService extends BaseService
} }
else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST) else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST)
{ {
$row = $this->Database->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch(); $row = $this->getDatabase()->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch();
if ($row != null) if ($row != null)
{ {
$nextExecutionUserId = $row->user_id; $nextExecutionUserId = $row->user_id;

View File

@@ -6,7 +6,7 @@ class DatabaseMigrationService extends BaseService
{ {
public function MigrateDatabase() public function MigrateDatabase()
{ {
$this->DatabaseService->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))"); $this->getDatabaseService()->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))");
$sqlMigrationFiles = array(); $sqlMigrationFiles = array();
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file) foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
@@ -41,21 +41,21 @@ class DatabaseMigrationService extends BaseService
private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql) private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql)
{ {
$rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); $rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if (intval($rowCount) === 0) if (intval($rowCount) === 0)
{ {
$this->DatabaseService->ExecuteDbStatement($sql); $this->getDatabaseService()->ExecuteDbStatement($sql);
$this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); $this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
} }
} }
private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile) private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile)
{ {
$rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); $rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if (intval($rowCount) === 0) if (intval($rowCount) === 0)
{ {
include $phpFile; include $phpFile;
$this->DatabaseService->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); $this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
} }
} }
} }

View File

@@ -2,10 +2,22 @@
namespace Grocy\Services; namespace Grocy\Services;
use \Grocy\Services\ApplicationService; #use \Grocy\Services\ApplicationService;
class DatabaseService class DatabaseService
{ {
private static $instance = null;
public static function getInstance()
{
if (self::$instance == null)
{
self::$instance = new self();
}
return self::$instance;
}
private function GetDbFilePath() private function GetDbFilePath()
{ {
if (GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease') if (GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease')
@@ -16,34 +28,34 @@ class DatabaseService
return GROCY_DATAPATH . '/grocy.db'; return GROCY_DATAPATH . '/grocy.db';
} }
private $DbConnectionRaw; private static $DbConnectionRaw = null;
/** /**
* @return \PDO * @return \PDO
*/ */
public function GetDbConnectionRaw() public function GetDbConnectionRaw()
{ {
if ($this->DbConnectionRaw == null) if (self::$DbConnectionRaw == null)
{ {
$pdo = new \PDO('sqlite:' . $this->GetDbFilePath()); $pdo = new \PDO('sqlite:' . $this->GetDbFilePath());
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->DbConnectionRaw = $pdo; self::$DbConnectionRaw = $pdo;
} }
return $this->DbConnectionRaw; return self::$DbConnectionRaw;
} }
private $DbConnection; private static $DbConnection = null;
/** /**
* @return \LessQL\Database * @return \LessQL\Database
*/ */
public function GetDbConnection() public function GetDbConnection()
{ {
if ($this->DbConnection == null) if (self::$DbConnection == null)
{ {
$this->DbConnection = new \LessQL\Database($this->GetDbConnectionRaw()); self::$DbConnection = new \LessQL\Database($this->GetDbConnectionRaw());
} }
return $this->DbConnection; return self::$DbConnection;
} }
/** /**

View File

@@ -2,7 +2,7 @@
namespace Grocy\Services; namespace Grocy\Services;
use \Grocy\Services\LocalizationService; #use \Grocy\Services\LocalizationService;
class DemoDataGeneratorService extends BaseService class DemoDataGeneratorService extends BaseService
{ {
@@ -16,7 +16,7 @@ class DemoDataGeneratorService extends BaseService
public function PopulateDemoData() public function PopulateDemoData()
{ {
$rowCount = $this->DatabaseService->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn(); $rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn();
if (intval($rowCount) === 0) if (intval($rowCount) === 0)
{ {
$loremIpsum = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.'; $loremIpsum = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.';
@@ -183,7 +183,7 @@ class DemoDataGeneratorService extends BaseService
INSERT INTO migrations (migration) VALUES (-1); INSERT INTO migrations (migration) VALUES (-1);
"; ";
$this->DatabaseService->ExecuteDbStatement($sql); $this->getDatabaseService()->ExecuteDbStatement($sql);
$stockService = new StockService(); $stockService = new StockService();
$stockService->AddProduct(3, 1, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE, date('Y-m-d', strtotime('-10 days')), $this->RandomPrice()); $stockService->AddProduct(3, 1, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE, date('Y-m-d', strtotime('-10 days')), $this->RandomPrice());
@@ -319,13 +319,13 @@ class DemoDataGeneratorService extends BaseService
private function __t_sql(string $text) private function __t_sql(string $text)
{ {
$localizedText = $this->LocalizationService->__t($text, null); $localizedText = $this->getLocalizationService()->__t($text, null);
return str_replace("'", "''", $localizedText); return str_replace("'", "''", $localizedText);
} }
private function __n_sql($number, string $singularForm, string $pluralForm) private function __n_sql($number, string $singularForm, string $pluralForm)
{ {
$localizedText = $this->LocalizationService->__n($number, $singularForm, $pluralForm); $localizedText = $this->getLocalizationService()->__n($number, $singularForm, $pluralForm);
return str_replace("'", "''", $localizedText); return str_replace("'", "''", $localizedText);
} }

View File

@@ -2,24 +2,44 @@
namespace Grocy\Services; namespace Grocy\Services;
use \Grocy\Services\DatabaseService; #use \Grocy\Services\DatabaseService;
use \Gettext\Translation; use \Gettext\Translation;
use \Gettext\Translations; use \Gettext\Translations;
use \Gettext\Translator; use \Gettext\Translator;
class LocalizationService class LocalizationService
{ {
private static $instanceMap = array();
public function __construct(string $culture) public function __construct(string $culture)
{ {
$this->Culture = $culture; $this->Culture = $culture;
$this->DatabaseService = new DatabaseService();
$this->Database = $this->DatabaseService->GetDbConnection();
$this->LoadLocalizations($culture); $this->LoadLocalizations($culture);
} }
protected $DatabaseService;
protected $Database; protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getdatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
public static function getInstance(string $culture)
{
if (!in_array($culture, self::$instanceMap))
{
self::$instanceMap[$culture] = new self($culture);
}
return self::$instanceMap[$culture];
}
protected $Pot; protected $Pot;
protected $PotMain; protected $PotMain;
protected $Po; protected $Po;
@@ -57,7 +77,7 @@ class LocalizationService
$quantityUnits = null; $quantityUnits = null;
try try
{ {
$quantityUnits = $this->Database->quantity_units()->fetchAll(); $quantityUnits = $this->getDatabase()->quantity_units()->fetchAll();
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {

View File

@@ -2,7 +2,7 @@
namespace Grocy\Services; namespace Grocy\Services;
use \Grocy\Services\StockService; #use \Grocy\Services\StockService;
class RecipesService extends BaseService class RecipesService extends BaseService
{ {
@@ -13,33 +13,30 @@ class RecipesService extends BaseService
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
$this->StockService = new StockService();
} }
protected $StockService;
public function GetRecipesPosResolved() public function GetRecipesPosResolved()
{ {
$sql = 'SELECT * FROM recipes_pos_resolved'; $sql = 'SELECT * FROM recipes_pos_resolved';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDataBaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetRecipesResolved() public function GetRecipesResolved()
{ {
$sql = 'SELECT * FROM recipes_resolved'; $sql = 'SELECT * FROM recipes_resolved';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDataBaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function AddNotFulfilledProductsToShoppingList($recipeId, $excludedProductIds = null) public function AddNotFulfilledProductsToShoppingList($recipeId, $excludedProductIds = null)
{ {
$recipe = $this->Database->recipes($recipeId); $recipe = $this->getDataBase()->recipes($recipeId);
$recipePositions = $this->GetRecipesPosResolved(); $recipePositions = $this->GetRecipesPosResolved();
foreach ($recipePositions as $recipePosition) foreach ($recipePositions as $recipePosition)
{ {
if($recipePosition->recipe_id == $recipeId && !in_array($recipePosition->product_id, $excludedProductIds)) if($recipePosition->recipe_id == $recipeId && !in_array($recipePosition->product_id, $excludedProductIds))
{ {
$product = $this->Database->products($recipePosition->product_id); $product = $this->getDataBase()->products($recipePosition->product_id);
$toOrderAmount = ceil(($recipePosition->missing_amount - $recipePosition->amount_on_shopping_list) / $product->qu_factor_purchase_to_stock); $toOrderAmount = ceil(($recipePosition->missing_amount - $recipePosition->amount_on_shopping_list) / $product->qu_factor_purchase_to_stock);
if ($recipe->not_check_shoppinglist == 1) if ($recipe->not_check_shoppinglist == 1)
@@ -49,10 +46,10 @@ class RecipesService extends BaseService
if($toOrderAmount > 0) if($toOrderAmount > 0)
{ {
$shoppinglistRow = $this->Database->shopping_list()->createRow(array( $shoppinglistRow = $this->getDataBase()->shopping_list()->createRow(array(
'product_id' => $recipePosition->product_id, 'product_id' => $recipePosition->product_id,
'amount' => $toOrderAmount, 'amount' => $toOrderAmount,
'note' => $this->LocalizationService->__t('Added for recipe %s', $recipe->name) 'note' => $this->getLocalizationService()->__t('Added for recipe %s', $recipe->name)
)); ));
$shoppinglistRow->save(); $shoppinglistRow->save();
} }
@@ -68,26 +65,26 @@ class RecipesService extends BaseService
} }
$transactionId = uniqid(); $transactionId = uniqid();
$recipePositions = $this->Database->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll(); $recipePositions = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll();
foreach ($recipePositions as $recipePosition) foreach ($recipePositions as $recipePosition)
{ {
if ($recipePosition->only_check_single_unit_in_stock == 0) if ($recipePosition->only_check_single_unit_in_stock == 0)
{ {
$this->StockService->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true); $this->getStockService()->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true);
} }
} }
$recipeRow = $this->Database->recipes()->where('id = :1', $recipeId)->fetch(); $recipeRow = $this->getDatabase()->recipes()->where('id = :1', $recipeId)->fetch();
if (!empty($recipeRow->product_id)) if (!empty($recipeRow->product_id))
{ {
$recipeResolvedRow = $this->Database->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch(); $recipeResolvedRow = $this->getDatabase()->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch();
$this->StockService->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs)); $this->getStockService()->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs));
} }
} }
private function RecipeExists($recipeId) private function RecipeExists($recipeId)
{ {
$recipeRow = $this->Database->recipes()->where('id = :1', $recipeId)->fetch(); $recipeRow = $this->getDataBase()->recipes()->where('id = :1', $recipeId)->fetch();
return $recipeRow !== null; return $recipeRow !== null;
} }
} }

View File

@@ -4,6 +4,7 @@ namespace Grocy\Services;
class SessionService extends BaseService class SessionService extends BaseService
{ {
/** /**
* @return boolean * @return boolean
*/ */
@@ -15,16 +16,16 @@ class SessionService extends BaseService
} }
else else
{ {
$sessionRow = $this->Database->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch(); $sessionRow = $this->getDatabase()->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch();
if ($sessionRow !== null) if ($sessionRow !== null)
{ {
// This should not change the database file modification time as this is used // This should not change the database file modification time as this is used
// to determine if REALLY something has changed // to determine if REALLY something has changed
$dbModTime = $this->DatabaseService->GetDbChangedTime(); $dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$sessionRow->update(array( $sessionRow->update(array(
'last_used' => date('Y-m-d H:i:s', time()) 'last_used' => date('Y-m-d H:i:s', time())
)); ));
$this->DatabaseService->SetDbChangedTime($dbModTime); $this->getDatabaseService()->SetDbChangedTime($dbModTime);
return true; return true;
} }
@@ -48,7 +49,7 @@ class SessionService extends BaseService
$expires = date('Y-m-d H:i:s', PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX>>32); // Never $expires = date('Y-m-d H:i:s', PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX>>32); // Never
} }
$sessionRow = $this->Database->sessions()->createRow(array( $sessionRow = $this->getDatabase()->sessions()->createRow(array(
'user_id' => $userId, 'user_id' => $userId,
'session_key' => $newSessionKey, 'session_key' => $newSessionKey,
'expires' => $expires 'expires' => $expires
@@ -60,22 +61,22 @@ class SessionService extends BaseService
public function RemoveSession($sessionKey) public function RemoveSession($sessionKey)
{ {
$this->Database->sessions()->where('session_key', $sessionKey)->delete(); $this->getDatabase()->sessions()->where('session_key', $sessionKey)->delete();
} }
public function GetUserBySessionKey($sessionKey) public function GetUserBySessionKey($sessionKey)
{ {
$sessionRow = $this->Database->sessions()->where('session_key', $sessionKey)->fetch(); $sessionRow = $this->getDatabase()->sessions()->where('session_key', $sessionKey)->fetch();
if ($sessionRow !== null) if ($sessionRow !== null)
{ {
return $this->Database->users($sessionRow->user_id); return $this->getDatabase()->users($sessionRow->user_id);
} }
return null; return null;
} }
public function GetDefaultUser() public function GetDefaultUser()
{ {
return $this->Database->users(1); return $this->getDatabase()->users(1);
} }
private function GenerateSessionKey() private function GenerateSessionKey()

View File

@@ -27,9 +27,9 @@ class StockService extends BaseService
$sql = 'SELECT * FROM stock_current WHERE best_before_date IS NOT NULL UNION SELECT id, 0, 0, null, 0, 0, 0 FROM ' . $missingProductsView . ' WHERE id NOT IN (SELECT product_id FROM stock_current)'; $sql = 'SELECT * FROM stock_current WHERE best_before_date IS NOT NULL UNION SELECT id, 0, 0, null, 0, 0, 0 FROM ' . $missingProductsView . ' WHERE id NOT IN (SELECT product_id FROM stock_current)';
} }
$currentStockMapped = $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ); $currentStockMapped = $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_OBJ);
$relevantProducts = $this->Database->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)'); $relevantProducts = $this->getDatabase()->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)');
foreach ($relevantProducts as $product) foreach ($relevantProducts as $product)
{ {
$currentStockMapped[$product->id][0]->product_id = $product->id; $currentStockMapped[$product->id][0]->product_id = $product->id;
@@ -42,19 +42,19 @@ class StockService extends BaseService
public function GetCurrentStockLocationContent() public function GetCurrentStockLocationContent()
{ {
$sql = 'SELECT * FROM stock_current_location_content'; $sql = 'SELECT * FROM stock_current_location_content';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetCurrentStockLocations() public function GetCurrentStockLocations()
{ {
$sql = 'SELECT * FROM stock_current_locations'; $sql = 'SELECT * FROM stock_current_locations';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetCurrentProductPrices() public function GetCurrentProductPrices()
{ {
$sql = 'SELECT * FROM products_current_price'; $sql = 'SELECT * FROM products_current_price';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetMissingProducts() public function GetMissingProducts()
@@ -65,17 +65,17 @@ class StockService extends BaseService
$sql = 'SELECT * FROM stock_missing_products'; $sql = 'SELECT * FROM stock_missing_products';
} }
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetProductStockLocations($productId) public function GetProductStockLocations($productId)
{ {
return $this->Database->stock_current_locations()->where('product_id', $productId)->fetchAll(); return $this->getDatabase()->stock_current_locations()->where('product_id', $productId)->fetchAll();
} }
public function GetProductIdFromBarcode(string $barcode) public function GetProductIdFromBarcode(string $barcode)
{ {
$potentialProduct = $this->Database->products()->where("',' || barcode || ',' LIKE '%,' || :1 || ',%' AND IFNULL(barcode, '') != ''", $barcode)->limit(1)->fetch(); $potentialProduct = $this->getDatabase()->products()->where("',' || barcode || ',' LIKE '%,' || :1 || ',%' AND IFNULL(barcode, '') != ''", $barcode)->limit(1)->fetch();
if ($potentialProduct === null) if ($potentialProduct === null)
{ {
@@ -117,24 +117,24 @@ class StockService extends BaseService
$stockCurrentRow->is_aggregated_amount = 0; $stockCurrentRow->is_aggregated_amount = 0;
} }
$product = $this->Database->products($productId); $product = $this->getDatabase()->products($productId);
$productLastPurchased = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_PURCHASE)->where('undone', 0)->max('purchased_date'); $productLastPurchased = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_PURCHASE)->where('undone', 0)->max('purchased_date');
$productLastUsed = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone', 0)->max('used_date'); $productLastUsed = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone', 0)->max('used_date');
$nextBestBeforeDate = $this->Database->stock()->where('product_id', $productId)->min('best_before_date'); $nextBestBeforeDate = $this->getDatabase()->stock()->where('product_id', $productId)->min('best_before_date');
$quPurchase = $this->Database->quantity_units($product->qu_id_purchase); $quPurchase = $this->getDatabase()->quantity_units($product->qu_id_purchase);
$quStock = $this->Database->quantity_units($product->qu_id_stock); $quStock = $this->getDatabase()->quantity_units($product->qu_id_stock);
$location = $this->Database->locations($product->location_id); $location = $this->getDatabase()->locations($product->location_id);
$averageShelfLifeDays = intval($this->Database->stock_average_product_shelf_life()->where('id', $productId)->fetch()->average_shelf_life_days); $averageShelfLifeDays = intval($this->getDatabase()->stock_average_product_shelf_life()->where('id', $productId)->fetch()->average_shelf_life_days);
$lastPrice = null; $lastPrice = null;
$lastLogRow = $this->Database->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->orderBy('row_created_timestamp', 'DESC')->limit(1)->fetch(); $lastLogRow = $this->getDatabase()->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->orderBy('row_created_timestamp', 'DESC')->limit(1)->fetch();
if ($lastLogRow !== null && !empty($lastLogRow)) if ($lastLogRow !== null && !empty($lastLogRow))
{ {
$lastPrice = $lastLogRow->price; $lastPrice = $lastLogRow->price;
} }
$consumeCount = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 0')->sum('amount') * -1; $consumeCount = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 0')->sum('amount') * -1;
$consumeCountSpoiled = $this->Database->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 1')->sum('amount') * -1; $consumeCountSpoiled = $this->getDatabase()->stock_log()->where('product_id', $productId)->where('transaction_type', self::TRANSACTION_TYPE_CONSUME)->where('undone = 0 AND spoiled = 1')->sum('amount') * -1;
if ($consumeCount == 0) if ($consumeCount == 0)
{ {
$consumeCount = 1; $consumeCount = 1;
@@ -168,7 +168,7 @@ class StockService extends BaseService
} }
$returnData = array(); $returnData = array();
$rows = $this->Database->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->whereNOT('price', null)->orderBy('purchased_date', 'DESC'); $rows = $this->getDatabase()->stock_log()->where('product_id = :1 AND transaction_type IN (:2, :3) AND undone = 0', $productId, self::TRANSACTION_TYPE_PURCHASE, self::TRANSACTION_TYPE_INVENTORY_CORRECTION)->whereNOT('price', null)->orderBy('purchased_date', 'DESC');
foreach ($rows as $row) foreach ($rows as $row)
{ {
$returnData[] = array( $returnData[] = array(
@@ -181,7 +181,7 @@ class StockService extends BaseService
public function GetStockEntry($entryId) public function GetStockEntry($entryId)
{ {
return $this->Database->stock()->where('id', $entryId)->fetch(); return $this->getDatabase()->stock()->where('id', $entryId)->fetch();
} }
public function GetProductStockEntries($productId, $excludeOpened = false, $allowSubproductSubstitution = false) public function GetProductStockEntries($productId, $excludeOpened = false, $allowSubproductSubstitution = false)
@@ -201,7 +201,7 @@ class StockService extends BaseService
$sqlWhereAndOpen = 'AND open = 0'; $sqlWhereAndOpen = 'AND open = 0';
} }
return $this->Database->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll(); return $this->getDatabase()->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId)->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC')->fetchAll();
} }
public function GetProductStockEntriesForLocation($productId, $locationId, $excludeOpened = false, $allowSubproductSubstitution = false) public function GetProductStockEntriesForLocation($productId, $locationId, $excludeOpened = false, $allowSubproductSubstitution = false)
@@ -257,7 +257,7 @@ class StockService extends BaseService
$stockId = uniqid(); $stockId = uniqid();
$logRow = $this->Database->stock_log()->createRow(array( $logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $productId, 'product_id' => $productId,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@@ -270,9 +270,9 @@ class StockService extends BaseService
)); ));
$logRow->save(); $logRow->save();
$returnValue = $this->Database->lastInsertId(); $returnValue = $this->getDatabase()->lastInsertId();
$stockRow = $this->Database->stock()->createRow(array( $stockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $productId, 'product_id' => $productId,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@@ -319,6 +319,7 @@ class StockService extends BaseService
if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION) if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION)
{ {
if ($locationId === null) // Consume from any location if ($locationId === null) // Consume from any location
{ {
$potentialStockEntries = $this->GetProductStockEntries($productId, false, $allowSubproductSubstitution); $potentialStockEntries = $this->GetProductStockEntries($productId, false, $allowSubproductSubstitution);
@@ -353,7 +354,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount) // Take the whole stock entry if ($amount >= $stockEntry->amount) // Take the whole stock entry
{ {
$logRow = $this->Database->stock_log()->createRow(array( $logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1, 'amount' => $stockEntry->amount * -1,
'best_before_date' => $stockEntry->best_before_date, 'best_before_date' => $stockEntry->best_before_date,
@@ -377,7 +378,7 @@ class StockService extends BaseService
{ {
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$logRow = $this->Database->stock_log()->createRow(array( $logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $amount * -1, 'amount' => $amount * -1,
'best_before_date' => $stockEntry->best_before_date, 'best_before_date' => $stockEntry->best_before_date,
@@ -401,7 +402,7 @@ class StockService extends BaseService
} }
} }
return $this->Database->lastInsertId(); return $this->getDatabase()->lastInsertId();
} }
else else
{ {
@@ -443,7 +444,7 @@ class StockService extends BaseService
$amount = abs($amount - floatval($productDetails->stock_amount) - floatval($productDetails->product->tare_weight)); $amount = abs($amount - floatval($productDetails->stock_amount) - floatval($productDetails->product->tare_weight));
} }
$productStockAmountAtFromLocation = $this->Database->stock()->where('product_id = :1 AND location_id = :2', $productId, $locationIdFrom)->sum('amount'); $productStockAmountAtFromLocation = $this->getDatabase()->stock()->where('product_id = :1 AND location_id = :2', $productId, $locationIdFrom)->sum('amount');
$potentialStockEntriesAtFromLocation = $this->GetProductStockEntriesForLocation($productId, $locationIdFrom); $potentialStockEntriesAtFromLocation = $this->GetProductStockEntriesForLocation($productId, $locationIdFrom);
if ($amount > $productStockAmountAtFromLocation) if ($amount > $productStockAmountAtFromLocation)
@@ -472,8 +473,8 @@ class StockService extends BaseService
if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING) if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING)
{ {
$locationFrom = $this->Database->locations()->where('id', $locationIdFrom)->fetch(); $locationFrom = $this->getDatabase()->locations()->where('id', $locationIdFrom)->fetch();
$locationTo = $this->Database->locations()->where('id', $locationIdTo)->fetch(); $locationTo = $this->getDatabase()->locations()->where('id', $locationIdTo)->fetch();
// Product was moved from a non-freezer to freezer location -> freeze // Product was moved from a non-freezer to freezer location -> freeze
if (intval($locationFrom->is_freezer) === 0 && intval($locationTo->is_freezer) === 1 && $productDetails->product->default_best_before_days_after_freezing > 0) if (intval($locationFrom->is_freezer) === 0 && intval($locationTo->is_freezer) === 1 && $productDetails->product->default_best_before_days_after_freezing > 0)
@@ -491,7 +492,7 @@ class StockService extends BaseService
$correlationId = uniqid(); $correlationId = uniqid();
if ($amount >= $stockEntry->amount) // Take the whole stock entry if ($amount >= $stockEntry->amount) // Take the whole stock entry
{ {
$logRowForLocationFrom = $this->Database->stock_log()->createRow(array( $logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1, 'amount' => $stockEntry->amount * -1,
'best_before_date' => $stockEntry->best_before_date, 'best_before_date' => $stockEntry->best_before_date,
@@ -506,7 +507,7 @@ class StockService extends BaseService
)); ));
$logRowForLocationFrom->save(); $logRowForLocationFrom->save();
$logRowForLocationTo = $this->Database->stock_log()->createRow(array( $logRowForLocationTo = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount, 'amount' => $stockEntry->amount,
'best_before_date' => $newBestBeforeDate, 'best_before_date' => $newBestBeforeDate,
@@ -532,7 +533,7 @@ class StockService extends BaseService
{ {
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$logRowForLocationFrom = $this->Database->stock_log()->createRow(array( $logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $amount * -1, 'amount' => $amount * -1,
'best_before_date' => $stockEntry->best_before_date, 'best_before_date' => $stockEntry->best_before_date,
@@ -547,7 +548,7 @@ class StockService extends BaseService
)); ));
$logRowForLocationFrom->save(); $logRowForLocationFrom->save();
$logRowForLocationTo = $this->Database->stock_log()->createRow(array( $logRowForLocationTo = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $newBestBeforeDate, 'best_before_date' => $newBestBeforeDate,
@@ -568,7 +569,7 @@ class StockService extends BaseService
)); ));
// The transfered amount gets into a new stock entry // The transfered amount gets into a new stock entry
$stockEntryNew = $this->Database->stock()->createRow(array( $stockEntryNew = $this->getDatabase()->stock()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $newBestBeforeDate, 'best_before_date' => $newBestBeforeDate,
@@ -585,13 +586,13 @@ class StockService extends BaseService
} }
} }
return $this->Database->lastInsertId(); return $this->getDatabase()->lastInsertId();
} }
public function EditStockEntry(int $stockRowId, int $amount, $bestBeforeDate, $locationId, $price, $open, $purchasedDate) public function EditStockEntry(int $stockRowId, int $amount, $bestBeforeDate, $locationId, $price, $open, $purchasedDate)
{ {
$stockRow = $this->Database->stock()->where('id = :1', $stockRowId)->fetch(); $stockRow = $this->getDatabase()->stock()->where('id = :1', $stockRowId)->fetch();
if ($stockRow === null) if ($stockRow === null)
{ {
@@ -600,7 +601,7 @@ class StockService extends BaseService
$correlationId = uniqid(); $correlationId = uniqid();
$transactionId = uniqid(); $transactionId = uniqid();
$logOldRowForStockUpdate = $this->Database->stock_log()->createRow(array( $logOldRowForStockUpdate = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockRow->product_id, 'product_id' => $stockRow->product_id,
'amount' => $stockRow->amount, 'amount' => $stockRow->amount,
'best_before_date' => $stockRow->best_before_date, 'best_before_date' => $stockRow->best_before_date,
@@ -636,7 +637,7 @@ class StockService extends BaseService
'purchased_date' => $purchasedDate 'purchased_date' => $purchasedDate
)); ));
$logNewRowForStockUpdate = $this->Database->stock_log()->createRow(array( $logNewRowForStockUpdate = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockRow->product_id, 'product_id' => $stockRow->product_id,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@@ -652,7 +653,7 @@ class StockService extends BaseService
)); ));
$logNewRowForStockUpdate->save(); $logNewRowForStockUpdate->save();
return $this->Database->lastInsertId(); return $this->getDatabase()->lastInsertId();
} }
public function InventoryProduct(int $productId, float $newAmount, $bestBeforeDate, $locationId = null, $price = null) public function InventoryProduct(int $productId, float $newAmount, $bestBeforeDate, $locationId = null, $price = null)
@@ -713,9 +714,9 @@ class StockService extends BaseService
throw new \Exception('Product does not exist'); throw new \Exception('Product does not exist');
} }
$productStockAmountUnopened = $this->Database->stock()->where('product_id = :1 AND open = 0', $productId)->sum('amount'); $productStockAmountUnopened = $this->getDatabase()->stock()->where('product_id = :1 AND open = 0', $productId)->sum('amount');
$potentialStockEntries = $this->GetProductStockEntries($productId, true); $potentialStockEntries = $this->GetProductStockEntries($productId, true);
$product = $this->Database->products($productId); $product = $this->getDatabase()->products($productId);
if ($amount > $productStockAmountUnopened) if ($amount > $productStockAmountUnopened)
{ {
@@ -742,7 +743,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount) // Mark the whole stock entry as opened if ($amount >= $stockEntry->amount) // Mark the whole stock entry as opened
{ {
$logRow = $this->Database->stock_log()->createRow(array( $logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount, 'amount' => $stockEntry->amount,
'best_before_date' => $stockEntry->best_before_date, 'best_before_date' => $stockEntry->best_before_date,
@@ -766,7 +767,7 @@ class StockService extends BaseService
{ {
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$newStockRow = $this->Database->stock()->createRow(array( $newStockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $restStockAmount, 'amount' => $restStockAmount,
'best_before_date' => $stockEntry->best_before_date, 'best_before_date' => $stockEntry->best_before_date,
@@ -776,7 +777,7 @@ class StockService extends BaseService
)); ));
$newStockRow->save(); $newStockRow->save();
$logRow = $this->Database->stock_log()->createRow(array( $logRow = $this->getDatabase()->stock_log()->createRow(array(
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $stockEntry->best_before_date, 'best_before_date' => $stockEntry->best_before_date,
@@ -799,7 +800,7 @@ class StockService extends BaseService
} }
} }
return $this->Database->lastInsertId(); return $this->getDatabase()->lastInsertId();
} }
public function AddMissingProductsToShoppingList($listId = 1) public function AddMissingProductsToShoppingList($listId = 1)
@@ -812,10 +813,10 @@ class StockService extends BaseService
$missingProducts = $this->GetMissingProducts(); $missingProducts = $this->GetMissingProducts();
foreach ($missingProducts as $missingProduct) foreach ($missingProducts as $missingProduct)
{ {
$product = $this->Database->products()->where('id', $missingProduct->id)->fetch(); $product = $this->getDatabase()->products()->where('id', $missingProduct->id)->fetch();
$amountToAdd = ceil($missingProduct->amount_missing / $product->qu_factor_purchase_to_stock); $amountToAdd = ceil($missingProduct->amount_missing / $product->qu_factor_purchase_to_stock);
$alreadyExistingEntry = $this->Database->shopping_list()->where('product_id', $missingProduct->id)->fetch(); $alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch();
if ($alreadyExistingEntry) // Update if ($alreadyExistingEntry) // Update
{ {
if ($alreadyExistingEntry->amount < $amountToAdd) if ($alreadyExistingEntry->amount < $amountToAdd)
@@ -828,7 +829,7 @@ class StockService extends BaseService
} }
else // Insert else // Insert
{ {
$shoppinglistRow = $this->Database->shopping_list()->createRow(array( $shoppinglistRow = $this->getDatabase()->shopping_list()->createRow(array(
'product_id' => $missingProduct->id, 'product_id' => $missingProduct->id,
'amount' => $amountToAdd, 'amount' => $amountToAdd,
'shopping_list_id' => $listId 'shopping_list_id' => $listId
@@ -845,7 +846,7 @@ class StockService extends BaseService
throw new \Exception('Shopping list does not exist'); throw new \Exception('Shopping list does not exist');
} }
$this->Database->shopping_list()->where('shopping_list_id = :1', $listId)->delete(); $this->getDatabase()->shopping_list()->where('shopping_list_id = :1', $listId)->delete();
} }
@@ -856,7 +857,7 @@ class StockService extends BaseService
throw new \Exception('Shopping list does not exist'); throw new \Exception('Shopping list does not exist');
} }
$productRow = $this->Database->shopping_list()->where('product_id = :1', $productId)->fetch(); $productRow = $this->getDatabase()->shopping_list()->where('product_id = :1', $productId)->fetch();
//If no entry was found with for this product, we return gracefully //If no entry was found with for this product, we return gracefully
if ($productRow != null && !empty($productRow)) if ($productRow != null && !empty($productRow))
@@ -886,7 +887,7 @@ class StockService extends BaseService
throw new \Exception('Product does not exist'); throw new \Exception('Product does not exist');
} }
$alreadyExistingEntry = $this->Database->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch(); $alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch();
if ($alreadyExistingEntry) // Update if ($alreadyExistingEntry) // Update
{ {
$alreadyExistingEntry->update(array( $alreadyExistingEntry->update(array(
@@ -897,7 +898,7 @@ class StockService extends BaseService
} }
else // Insert else // Insert
{ {
$shoppinglistRow = $this->Database->shopping_list()->createRow(array( $shoppinglistRow = $this->getDatabase()->shopping_list()->createRow(array(
'product_id' => $productId, 'product_id' => $productId,
'amount' => $amount, 'amount' => $amount,
'shopping_list_id' => $listId, 'shopping_list_id' => $listId,
@@ -909,19 +910,19 @@ class StockService extends BaseService
private function ProductExists($productId) private function ProductExists($productId)
{ {
$productRow = $this->Database->products()->where('id = :1', $productId)->fetch(); $productRow = $this->getDatabase()->products()->where('id = :1', $productId)->fetch();
return $productRow !== null; return $productRow !== null;
} }
private function LocationExists($locationId) private function LocationExists($locationId)
{ {
$locationRow = $this->Database->locations()->where('id = :1', $locationId)->fetch(); $locationRow = $this->getDatabase()->locations()->where('id = :1', $locationId)->fetch();
return $locationRow !== null; return $locationRow !== null;
} }
private function ShoppingListExists($listId) private function ShoppingListExists($listId)
{ {
$shoppingListRow = $this->Database->shopping_lists()->where('id = :1', $listId)->fetch(); $shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch();
return $shoppingListRow !== null; return $shoppingListRow !== null;
} }
@@ -937,7 +938,7 @@ class StockService extends BaseService
if (file_exists($path)) if (file_exists($path))
{ {
require_once $path; require_once $path;
return new $pluginName($this->Database->locations()->fetchAll(), $this->Database->quantity_units()->fetchAll()); return new $pluginName($this->getDatabase()->locations()->fetchAll(), $this->getDatabase()->quantity_units()->fetchAll());
} }
else else
{ {
@@ -955,7 +956,7 @@ class StockService extends BaseService
if ($addFoundProduct === true) if ($addFoundProduct === true)
{ {
// Add product to database and include new product id in output // Add product to database and include new product id in output
$newRow = $this->Database->products()->createRow($pluginOutput); $newRow = $this->getDatabase()->products()->createRow($pluginOutput);
$newRow->save(); $newRow->save();
$pluginOutput['id'] = $newRow->id; $pluginOutput['id'] = $newRow->id;
@@ -967,7 +968,7 @@ class StockService extends BaseService
public function UndoBooking($bookingId, $skipCorrelatedBookings = false) public function UndoBooking($bookingId, $skipCorrelatedBookings = false)
{ {
$logRow = $this->Database->stock_log()->where('id = :1 AND undone = 0', $bookingId)->fetch(); $logRow = $this->getDatabase()->stock_log()->where('id = :1 AND undone = 0', $bookingId)->fetch();
if ($logRow == null) if ($logRow == null)
{ {
throw new \Exception('Booking does not exist or was already undone'); throw new \Exception('Booking does not exist or was already undone');
@@ -976,7 +977,7 @@ class StockService extends BaseService
// Undo all correlated bookings first, in order from newest first to the oldest // Undo all correlated bookings first, in order from newest first to the oldest
if (!$skipCorrelatedBookings && !empty($logRow->correlation_id)) if (!$skipCorrelatedBookings && !empty($logRow->correlation_id))
{ {
$correlatedBookings = $this->Database->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll(); $correlatedBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll();
foreach ($correlatedBookings as $correlatedBooking) foreach ($correlatedBookings as $correlatedBooking)
{ {
$this->UndoBooking($correlatedBooking->id, true); $this->UndoBooking($correlatedBooking->id, true);
@@ -984,7 +985,7 @@ class StockService extends BaseService
return; return;
} }
$hasSubsequentBookings = $this->Database->stock_log()->where('stock_id = :1 AND id != :2 AND (correlation_id is not null OR correlation_id != :3) AND id > :2 AND undone = 0', $logRow->stock_id, $logRow->id, $logRow->correlation_id)->count() > 0; $hasSubsequentBookings = $this->getDatabase()->stock_log()->where('stock_id = :1 AND id != :2 AND (correlation_id is not null OR correlation_id != :3) AND id > :2 AND undone = 0', $logRow->stock_id, $logRow->id, $logRow->correlation_id)->count() > 0;
if ($hasSubsequentBookings) if ($hasSubsequentBookings)
{ {
throw new \Exception('Booking has subsequent dependent bookings, undo not possible'); throw new \Exception('Booking has subsequent dependent bookings, undo not possible');
@@ -993,7 +994,7 @@ class StockService extends BaseService
if ($logRow->transaction_type === self::TRANSACTION_TYPE_PURCHASE || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount > 0)) if ($logRow->transaction_type === self::TRANSACTION_TYPE_PURCHASE || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount > 0))
{ {
// Remove corresponding stock entry // Remove corresponding stock entry
$stockRows = $this->Database->stock()->where('stock_id', $logRow->stock_id); $stockRows = $this->getDatabase()->stock()->where('stock_id', $logRow->stock_id);
$stockRows->delete(); $stockRows->delete();
// Update log entry // Update log entry
@@ -1005,7 +1006,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_CONSUME || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount < 0)) elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_CONSUME || ($logRow->transaction_type === self::TRANSACTION_TYPE_INVENTORY_CORRECTION && $logRow->amount < 0))
{ {
// Add corresponding amount back to stock // Add corresponding amount back to stock
$stockRow = $this->Database->stock()->createRow(array( $stockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $logRow->product_id, 'product_id' => $logRow->product_id,
'amount' => $logRow->amount * -1, 'amount' => $logRow->amount * -1,
'best_before_date' => $logRow->best_before_date, 'best_before_date' => $logRow->best_before_date,
@@ -1024,7 +1025,7 @@ class StockService extends BaseService
} }
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_TO) elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_TO)
{ {
$stockRow = $this->Database->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); $stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
if ($stockRow === null) if ($stockRow === null)
{ {
throw new \Exception('Booking does not exist or was already undone'); throw new \Exception('Booking does not exist or was already undone');
@@ -1051,10 +1052,10 @@ class StockService extends BaseService
{ {
// Add corresponding amount back to stock or // Add corresponding amount back to stock or
// create a row if missing // create a row if missing
$stockRow = $this->Database->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); $stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
if ($stockRow === null) if ($stockRow === null)
{ {
$stockRow = $this->Database->stock()->createRow(array( $stockRow = $this->getDatabase()->stock()->createRow(array(
'product_id' => $logRow->product_id, 'product_id' => $logRow->product_id,
'amount' => $logRow->amount * -1, 'amount' => $logRow->amount * -1,
'best_before_date' => $logRow->best_before_date, 'best_before_date' => $logRow->best_before_date,
@@ -1079,7 +1080,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_PRODUCT_OPENED) elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_PRODUCT_OPENED)
{ {
// Remove opened flag from corresponding log entry // Remove opened flag from corresponding log entry
$stockRows = $this->Database->stock()->where('stock_id = :1 AND amount = :2 AND purchased_date = :3', $logRow->stock_id, $logRow->amount, $logRow->purchased_date)->limit(1); $stockRows = $this->getDatabase()->stock()->where('stock_id = :1 AND amount = :2 AND purchased_date = :3', $logRow->stock_id, $logRow->amount, $logRow->purchased_date)->limit(1);
$stockRows->update(array( $stockRows->update(array(
'open' => 0, 'open' => 0,
'opened_date' => null 'opened_date' => null
@@ -1102,7 +1103,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_STOCK_EDIT_OLD) elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_STOCK_EDIT_OLD)
{ {
// Make sure there is a stock row still // Make sure there is a stock row still
$stockRow = $this->Database->stock()->where('id = :1', $logRow->stock_row_id)->fetch(); $stockRow = $this->getDatabase()->stock()->where('id = :1', $logRow->stock_row_id)->fetch();
if ($stockRow == null) if ($stockRow == null)
{ {
throw new \Exception('Booking does not exist or was already undone'); throw new \Exception('Booking does not exist or was already undone');
@@ -1139,7 +1140,7 @@ class StockService extends BaseService
public function UndoTransaction($transactionId) public function UndoTransaction($transactionId)
{ {
$transactionBookings = $this->Database->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll(); $transactionBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll();
if (count($transactionBookings) === 0) if (count($transactionBookings) === 0)
{ {

View File

@@ -7,7 +7,7 @@ class TasksService extends BaseService
public function GetCurrent() public function GetCurrent()
{ {
$sql = 'SELECT * from tasks_current'; $sql = 'SELECT * from tasks_current';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function MarkTaskAsCompleted($taskId, $doneTime) public function MarkTaskAsCompleted($taskId, $doneTime)
@@ -17,7 +17,7 @@ class TasksService extends BaseService
throw new \Exception('Task does not exist'); throw new \Exception('Task does not exist');
} }
$taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch(); $taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
$taskRow->update(array( $taskRow->update(array(
'done' => 1, 'done' => 1,
'done_timestamp' => $doneTime 'done_timestamp' => $doneTime
@@ -33,7 +33,7 @@ class TasksService extends BaseService
throw new \Exception('Task does not exist'); throw new \Exception('Task does not exist');
} }
$taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch(); $taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
$taskRow->update(array( $taskRow->update(array(
'done' => 0, 'done' => 0,
'done_timestamp' => null 'done_timestamp' => null
@@ -44,7 +44,7 @@ class TasksService extends BaseService
private function TaskExists($taskId) private function TaskExists($taskId)
{ {
$taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch(); $taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
return $taskRow !== null; return $taskRow !== null;
} }
} }

View File

@@ -18,10 +18,18 @@ class UserfieldsService extends BaseService
public function __construct() public function __construct()
{ {
parent::__construct(); parent::__construct();
$this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json'));
} }
protected $OpenApiSpec; protected $OpenApiSpec = null;
protected function getOpenApispec()
{
if($this->OpenApiSpec == null)
{
$this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json'));
}
return $this->OpenApiSpec;
}
public function GetFields($entity) public function GetFields($entity)
{ {
@@ -30,17 +38,17 @@ class UserfieldsService extends BaseService
throw new \Exception('Entity does not exist or is not exposed'); throw new \Exception('Entity does not exist or is not exposed');
} }
return $this->Database->userfields()->where('entity', $entity)->orderBy('name')->fetchAll(); return $this->getDatabase()->userfields()->where('entity', $entity)->orderBy('name')->fetchAll();
} }
public function GetField($fieldId) public function GetField($fieldId)
{ {
return $this->Database->userfields($fieldId); return $this->getDatabase()->userfields($fieldId);
} }
public function GetAllFields() public function GetAllFields()
{ {
return $this->Database->userfields()->orderBy('name')->fetchAll(); return $this->getDatabase()->userfields()->orderBy('name')->fetchAll();
} }
public function GetValues($entity, $objectId) public function GetValues($entity, $objectId)
@@ -50,7 +58,7 @@ class UserfieldsService extends BaseService
throw new \Exception('Entity does not exist or is not exposed'); throw new \Exception('Entity does not exist or is not exposed');
} }
$userfields = $this->Database->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name')->fetchAll(); $userfields = $this->getDatabase()->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name')->fetchAll();
$userfieldKeyValuePairs = array(); $userfieldKeyValuePairs = array();
foreach ($userfields as $userfield) foreach ($userfields as $userfield)
{ {
@@ -67,7 +75,7 @@ class UserfieldsService extends BaseService
throw new \Exception('Entity does not exist or is not exposed'); throw new \Exception('Entity does not exist or is not exposed');
} }
return $this->Database->userfield_values_resolved()->where('entity', $entity)->orderBy('name')->fetchAll(); return $this->getDatabase()->userfield_values_resolved()->where('entity', $entity)->orderBy('name')->fetchAll();
} }
public function SetValues($entity, $objectId, $userfields) public function SetValues($entity, $objectId, $userfields)
@@ -79,7 +87,7 @@ class UserfieldsService extends BaseService
foreach ($userfields as $key => $value) foreach ($userfields as $key => $value)
{ {
$fieldRow = $this->Database->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch(); $fieldRow = $this->getDatabase()->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch();
if ($fieldRow === null) if ($fieldRow === null)
{ {
@@ -88,7 +96,7 @@ class UserfieldsService extends BaseService
$fieldId = $fieldRow->id; $fieldId = $fieldRow->id;
$alreadyExistingEntry = $this->Database->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch(); $alreadyExistingEntry = $this->getDatabase()->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch();
if ($alreadyExistingEntry) // Update if ($alreadyExistingEntry) // Update
{ {
$alreadyExistingEntry->update(array( $alreadyExistingEntry->update(array(
@@ -97,7 +105,7 @@ class UserfieldsService extends BaseService
} }
else // Insert else // Insert
{ {
$newRow = $this->Database->userfield_values()->createRow(array( $newRow = $this->getDatabase()->userfield_values()->createRow(array(
'field_id' => $fieldId, 'field_id' => $fieldId,
'object_id' => $objectId, 'object_id' => $objectId,
'value' => $value 'value' => $value
@@ -109,10 +117,10 @@ class UserfieldsService extends BaseService
public function GetEntities() public function GetEntities()
{ {
$exposedDefaultEntities = $this->OpenApiSpec->components->internalSchemas->ExposedEntity->enum; $exposedDefaultEntities = $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum;
$userentities = array(); $userentities = array();
foreach ($this->Database->userentities()->orderBy('name') as $userentity) foreach ($this->getDatabase()->userentities()->orderBy('name') as $userentity)
{ {
$userentities[] = 'userentity-' . $userentity->name; $userentities[] = 'userentity-' . $userentity->name;
} }

View File

@@ -6,7 +6,7 @@ class UsersService extends BaseService
{ {
public function CreateUser(string $username, string $firstName, string $lastName, string $password) public function CreateUser(string $username, string $firstName, string $lastName, string $password)
{ {
$newUserRow = $this->Database->users()->createRow(array( $newUserRow = $this->getDatabase()->users()->createRow(array(
'username' => $username, 'username' => $username,
'first_name' => $firstName, 'first_name' => $firstName,
'last_name' => $lastName, 'last_name' => $lastName,
@@ -22,7 +22,7 @@ class UsersService extends BaseService
throw new \Exception('User does not exist'); throw new \Exception('User does not exist');
} }
$user = $this->Database->users($userId); $user = $this->getDatabase()->users($userId);
$user->update(array( $user->update(array(
'username' => $username, 'username' => $username,
'first_name' => $firstName, 'first_name' => $firstName,
@@ -33,13 +33,13 @@ class UsersService extends BaseService
public function DeleteUser($userId) public function DeleteUser($userId)
{ {
$row = $this->Database->users($userId); $row = $this->getDatabase()->users($userId);
$row->delete(); $row->delete();
} }
public function GetUsersAsDto() public function GetUsersAsDto()
{ {
$users = $this->Database->users(); $users = $this->getDatabase()->users();
$returnUsers = array(); $returnUsers = array();
foreach ($users as $user) foreach ($users as $user)
{ {
@@ -52,7 +52,7 @@ class UsersService extends BaseService
public function GetUserSetting($userId, $settingKey) public function GetUserSetting($userId, $settingKey)
{ {
$settingRow = $this->Database->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); $settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
if ($settingRow !== null) if ($settingRow !== null)
{ {
return $settingRow->value; return $settingRow->value;
@@ -67,7 +67,7 @@ class UsersService extends BaseService
{ {
$settings = array(); $settings = array();
$settingRows = $this->Database->user_settings()->where('user_id = :1', $userId)->fetchAll(); $settingRows = $this->getDatabase()->user_settings()->where('user_id = :1', $userId)->fetchAll();
foreach ($settingRows as $settingRow) foreach ($settingRows as $settingRow)
{ {
$settings[$settingRow->key] = $settingRow->value; $settings[$settingRow->key] = $settingRow->value;
@@ -80,7 +80,7 @@ class UsersService extends BaseService
public function SetUserSetting($userId, $settingKey, $settingValue) public function SetUserSetting($userId, $settingKey, $settingValue)
{ {
$settingRow = $this->Database->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); $settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
if ($settingRow !== null) if ($settingRow !== null)
{ {
$settingRow->update(array( $settingRow->update(array(
@@ -90,7 +90,7 @@ class UsersService extends BaseService
} }
else else
{ {
$settingRow = $this->Database->user_settings()->createRow(array( $settingRow = $this->getDatabase()->user_settings()->createRow(array(
'user_id' => $userId, 'user_id' => $userId,
'key' => $settingKey, 'key' => $settingKey,
'value' => $settingValue 'value' => $settingValue
@@ -101,7 +101,7 @@ class UsersService extends BaseService
private function UserExists($userId) private function UserExists($userId)
{ {
$userRow = $this->Database->users()->where('id = :1', $userId)->fetch(); $userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch();
return $userRow !== null; return $userRow !== null;
} }
} }