Optimized controller / services structure

This commit is contained in:
Bernd Bestel 2026-04-20 22:46:47 +02:00
parent 496f8ece8d
commit 6210077984
No known key found for this signature in database
GPG Key ID: 71BD34C0D4891300
66 changed files with 1087 additions and 1179 deletions

View File

@ -2,6 +2,7 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
use Grocy\Services\DatabaseService;
use Grocy\Services\StockService; use Grocy\Services\StockService;
$PRODUCTS = [3, 4, 5, 6, 7, 8]; $PRODUCTS = [3, 4, 5, 6, 7, 8];
@ -11,11 +12,11 @@ $days = -1;
while ($i <= 500) while ($i <= 500)
{ {
$productId = $PRODUCTS[array_rand($PRODUCTS)]; $productId = $PRODUCTS[array_rand($PRODUCTS)];
$transactionId1 = $this->getStockService()->AddProduct($productId, 1, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE, date('Y-m-d', strtotime("$days days")), XRandomPrice()); $transactionId1 = StockService::GetInstance()->AddProduct($productId, 1, date('Y-m-d', strtotime('+180 days')), StockService::TRANSACTION_TYPE_PURCHASE, date('Y-m-d', strtotime("$days days")), XRandomPrice());
$transactionId2 = $this->getStockService()->ConsumeProduct($productId, 1, false, StockService::TRANSACTION_TYPE_CONSUME); $transactionId2 = StockService::GetInstance()->ConsumeProduct($productId, 1, false, StockService::TRANSACTION_TYPE_CONSUME);
$this->getDatabaseService()->ExecuteDbStatement("UPDATE stock_log SET row_created_timestamp = DATETIME(row_created_timestamp, '$days days') WHERE transaction_id = '$transactionId1'"); DatabaseService::GetInstance()->ExecuteDbStatement("UPDATE stock_log SET row_created_timestamp = DATETIME(row_created_timestamp, '$days days') WHERE transaction_id = '$transactionId1'");
$this->getDatabaseService()->ExecuteDbStatement("UPDATE stock_log SET row_created_timestamp = DATETIME(row_created_timestamp, '$days days') WHERE transaction_id = '$transactionId2'"); DatabaseService::GetInstance()->ExecuteDbStatement("UPDATE stock_log SET row_created_timestamp = DATETIME(row_created_timestamp, '$days days') WHERE transaction_id = '$transactionId2'");
$days--; $days--;
$i++; $i++;

View File

@ -4,7 +4,7 @@
use Grocy\Services\RecipesService; use Grocy\Services\RecipesService;
$recipesService = RecipesService::getInstance(); $recipesService = RecipesService::GetInstance();
for ($i = 1; $i <= 87; $i++) for ($i = 1; $i <= 87; $i++)
{ {

View File

@ -2,7 +2,9 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
$db = $this->getDatabaseService()->GetDbConnection(); use Grocy\Services\DatabaseService;
$db = DatabaseService::GetInstance()->GetDbConnection();
// Reset the password of the user "admin" to "admin" // Reset the password of the user "admin" to "admin"
$adminUserRow = $db->users()->where('username', 'admin')->fetch(); $adminUserRow = $db->users()->where('username', 'admin')->fetch();

View File

@ -121,9 +121,7 @@ $app->add(new $authMiddlewareClass($container, $app->getResponseFactory()));
$app->addBodyParsingMiddleware(); $app->addBodyParsingMiddleware();
$app->addRoutingMiddleware(); $app->addRoutingMiddleware();
$errorMiddleware = $app->addErrorMiddleware(true, false, false); $errorMiddleware = $app->addErrorMiddleware(true, false, false);
$errorMiddleware->setDefaultErrorHandler( $errorMiddleware->setDefaultErrorHandler(new ExceptionController($container, $app->getResponseFactory()));
new ExceptionController($app, $container)
);
$app->getRouteCollector()->setCacheFile(GROCY_DATAPATH . '/viewcache/route_cache.php'); $app->getRouteCollector()->setCacheFile(GROCY_DATAPATH . '/viewcache/route_cache.php');

View File

@ -1,7 +1,8 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\BaseController;
use LessQL\Result; use LessQL\Result;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Slim\Exception\HttpException; use Slim\Exception\HttpException;
@ -32,22 +33,24 @@ class BaseApiController extends BaseController
protected function GenericErrorResponse(Response $response, $errorMessage, $status = 400) protected function GenericErrorResponse(Response $response, $errorMessage, $status = 400)
{ {
return $response->withStatus($status)->withJson([ $response = $response->withStatus($status);
return $this->ApiResponse($response, [
'error_message' => $errorMessage 'error_message' => $errorMessage
]); ]);
} }
public function FilteredApiResponse(Response $response, Result $data, array $query) public function FilteredApiResponse(Response $response, Result $data, array $query)
{ {
$data = $this->queryData($data, $query); $data = $this->QueryData($data, $query);
return $this->ApiResponse($response, $data); return $this->ApiResponse($response, $data);
} }
protected function queryData(Result $data, array $query) protected function QueryData(Result $data, array $query)
{ {
if (isset($query['query'])) if (isset($query['query']))
{ {
$data = $this->filter($data, $query['query']); $data = $this->FilterData($data, $query['query']);
} }
if (isset($query['limit']) || isset($query['offset'])) if (isset($query['limit']) || isset($query['offset']))
@ -82,7 +85,7 @@ class BaseApiController extends BaseController
return $data; return $data;
} }
protected function filter(Result $data, array $query): Result protected function FilterData(Result $data, array $query): Result
{ {
foreach ($query as $q) foreach ($query as $q)
{ {
@ -141,11 +144,11 @@ class BaseApiController extends BaseController
return $data; return $data;
} }
protected function getOpenApispec() protected function GetOpenApispec()
{ {
if ($this->OpenApiSpec == null) if ($this->OpenApiSpec == null)
{ {
$this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../grocy.openapi.json')); $this->OpenApiSpec = json_decode(file_get_contents(__DIR__ . '/../../grocy.openapi.json'));
} }
return $this->OpenApiSpec; return $this->OpenApiSpec;

View File

@ -1,10 +1,11 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Helpers\WebhookRunner; use Grocy\Helpers\WebhookRunner;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
use Grocy\Services\BatteriesService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -14,7 +15,8 @@ class BatteriesApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->getBatteriesService()->GetBatteryDetails($args['batteryId'])); throw new \Exception('df');
return $this->ApiResponse($response, BatteriesService::GetInstance()->GetBatteryDetails($args['batteryId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -24,12 +26,12 @@ class BatteriesApiController extends BaseApiController
public function Current(Request $request, Response $response, array $args) public function Current(Request $request, Response $response, array $args)
{ {
return $this->FilteredApiResponse($response, $this->getBatteriesService()->GetCurrent(), $request->getQueryParams()); return $this->FilteredApiResponse($response, BatteriesService::GetInstance()->GetCurrent(), $request->getQueryParams());
} }
public function TrackChargeCycle(Request $request, Response $response, array $args) public function TrackChargeCycle(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_BATTERIES_TRACK_CHARGE_CYCLE); User::CheckPermission($request, User::PERMISSION_BATTERIES_TRACK_CHARGE_CYCLE);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -41,8 +43,8 @@ class BatteriesApiController extends BaseApiController
$trackedTime = $requestBody['tracked_time']; $trackedTime = $requestBody['tracked_time'];
} }
$chargeCycleId = $this->getBatteriesService()->TrackChargeCycle($args['batteryId'], $trackedTime); $chargeCycleId = BatteriesService::GetInstance()->TrackChargeCycle($args['batteryId'], $trackedTime);
return $this->ApiResponse($response, $this->getDatabase()->battery_charge_cycles($chargeCycleId)); return $this->ApiResponse($response, $this->DB->battery_charge_cycles($chargeCycleId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -52,11 +54,11 @@ class BatteriesApiController extends BaseApiController
public function UndoChargeCycle(Request $request, Response $response, array $args) public function UndoChargeCycle(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_BATTERIES_UNDO_CHARGE_CYCLE); User::CheckPermission($request, User::PERMISSION_BATTERIES_UNDO_CHARGE_CYCLE);
try try
{ {
$this->ApiResponse($response, $this->getBatteriesService()->UndoChargeCycle($args['chargeCycleId'])); $this->ApiResponse($response, BatteriesService::GetInstance()->UndoChargeCycle($args['chargeCycleId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -69,7 +71,7 @@ class BatteriesApiController extends BaseApiController
{ {
try try
{ {
$batteryDetails = (object)$this->getBatteriesService()->GetBatteryDetails($args['batteryId']); $batteryDetails = (object)BatteriesService::GetInstance()->GetBatteryDetails($args['batteryId']);
$webhookData = array_merge([ $webhookData = array_merge([
'battery' => $batteryDetails->battery->name, 'battery' => $batteryDetails->battery->name,

View File

@ -1,7 +1,8 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Services\CalendarService;
use Grocy\Services\ApiKeyService; use Grocy\Services\ApiKeyService;
use Eluceo\iCal\Domain\Entity\Calendar; use Eluceo\iCal\Domain\Entity\Calendar;
use Eluceo\iCal\Domain\Entity\Event; use Eluceo\iCal\Domain\Entity\Event;
@ -20,7 +21,7 @@ class CalendarApiController extends BaseApiController
{ {
try try
{ {
$events = $this->getCalendarService()->GetEvents(); $events = CalendarService::GetInstance()->GetEvents();
$minDate = null; $minDate = null;
$maxDate = null; $maxDate = null;
@ -95,7 +96,7 @@ class CalendarApiController extends BaseApiController
try try
{ {
return $this->ApiResponse($response, [ return $this->ApiResponse($response, [
'url' => $this->AppContainer->get('UrlManager')->ConstructUrl('/api/calendar/ical?secret=' . $this->getApiKeyService()->GetOrCreateApiKey(ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL)) 'url' => $this->AppContainer->get('UrlManager')->ConstructUrl('/api/calendar/ical?secret=' . ApiKeyService::GetInstance()->GetOrCreateApiKey(ApiKeyService::API_KEY_TYPE_SPECIAL_PURPOSE_CALENDAR_ICAL))
]); ]);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@ -1,10 +1,11 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Helpers\WebhookRunner; use Grocy\Helpers\WebhookRunner;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
use Grocy\Services\ChoresService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -25,15 +26,15 @@ class ChoresApiController extends BaseApiController
if ($choreId === null) if ($choreId === null)
{ {
$chores = $this->getDatabase()->chores(); $chores = $this->DB->chores();
foreach ($chores as $chore) foreach ($chores as $chore)
{ {
$this->getChoresService()->CalculateNextExecutionAssignment($chore->id); ChoresService::GetInstance()->CalculateNextExecutionAssignment($chore->id);
} }
} }
else else
{ {
$this->getChoresService()->CalculateNextExecutionAssignment($choreId); ChoresService::GetInstance()->CalculateNextExecutionAssignment($choreId);
} }
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
@ -48,7 +49,7 @@ class ChoresApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->getChoresService()->GetChoreDetails($args['choreId'])); return $this->ApiResponse($response, ChoresService::GetInstance()->GetChoreDetails($args['choreId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -58,7 +59,7 @@ class ChoresApiController extends BaseApiController
public function Current(Request $request, Response $response, array $args) public function Current(Request $request, Response $response, array $args)
{ {
return $this->FilteredApiResponse($response, $this->getChoresService()->GetCurrent(), $request->getQueryParams()); return $this->FilteredApiResponse($response, ChoresService::GetInstance()->GetCurrent(), $request->getQueryParams());
} }
public function TrackChoreExecution(Request $request, Response $response, array $args) public function TrackChoreExecution(Request $request, Response $response, array $args)
@ -67,7 +68,7 @@ class ChoresApiController extends BaseApiController
try try
{ {
User::checkPermission($request, User::PERMISSION_CHORE_TRACK_EXECUTION); User::CheckPermission($request, User::PERMISSION_CHORE_TRACK_EXECUTION);
$trackedTime = date('Y-m-d H:i:s'); $trackedTime = date('Y-m-d H:i:s');
if (array_key_exists('tracked_time', $requestBody) && (IsIsoDateTime($requestBody['tracked_time']) || IsIsoDate($requestBody['tracked_time']))) if (array_key_exists('tracked_time', $requestBody) && (IsIsoDateTime($requestBody['tracked_time']) || IsIsoDate($requestBody['tracked_time'])))
@ -89,11 +90,11 @@ class ChoresApiController extends BaseApiController
if ($doneBy != GROCY_USER_ID) if ($doneBy != GROCY_USER_ID)
{ {
User::checkPermission($request, User::PERMISSION_CHORE_TRACK_EXECUTION); User::CheckPermission($request, User::PERMISSION_CHORE_TRACK_EXECUTION);
} }
$choreExecutionId = $this->getChoresService()->TrackChore($args['choreId'], $trackedTime, $doneBy, $skipped); $choreExecutionId = ChoresService::GetInstance()->TrackChore($args['choreId'], $trackedTime, $doneBy, $skipped);
return $this->ApiResponse($response, $this->getDatabase()->chores_log($choreExecutionId)); return $this->ApiResponse($response, $this->DB->chores_log($choreExecutionId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -105,9 +106,9 @@ class ChoresApiController extends BaseApiController
{ {
try try
{ {
User::checkPermission($request, User::PERMISSION_CHORE_UNDO_EXECUTION); User::CheckPermission($request, User::PERMISSION_CHORE_UNDO_EXECUTION);
$this->ApiResponse($response, $this->getChoresService()->UndoChoreExecution($args['executionId'])); $this->ApiResponse($response, ChoresService::GetInstance()->UndoChoreExecution($args['executionId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -120,7 +121,7 @@ class ChoresApiController extends BaseApiController
{ {
try try
{ {
$choreDetails = (object)$this->getChoresService()->GetChoreDetails($args['choreId']); $choreDetails = (object)ChoresService::GetInstance()->GetChoreDetails($args['choreId']);
$webhookData = array_merge([ $webhookData = array_merge([
'chore' => $choreDetails->chore->name, 'chore' => $choreDetails->chore->name,
@ -143,7 +144,7 @@ class ChoresApiController extends BaseApiController
public function MergeChores(Request $request, Response $response, array $args) public function MergeChores(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); User::CheckPermission($request, User::PERMISSION_MASTER_DATA_EDIT);
try try
{ {
@ -152,7 +153,7 @@ class ChoresApiController extends BaseApiController
throw new \Exception('Provided {choreIdToKeep} or {choreIdToRemove} is not a valid integer'); throw new \Exception('Provided {choreIdToKeep} or {choreIdToRemove} is not a valid integer');
} }
$this->ApiResponse($response, $this->getChoresService()->MergeChores($args['choreIdToKeep'], $args['choreIdToRemove'])); $this->ApiResponse($response, ChoresService::GetInstance()->MergeChores($args['choreIdToKeep'], $args['choreIdToRemove']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@ -1,6 +1,6 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Services\FilesService; use Grocy\Services\FilesService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
@ -14,7 +14,7 @@ class FilesApiController extends BaseApiController
{ {
try try
{ {
if (!in_array($args['group'], $this->getOpenApiSpec()->components->schemas->FileGroups->enum)) if (!in_array($args['group'], $this->GetOpenApispec()->components->schemas->FileGroups->enum))
{ {
throw new \Exception('Invalid file group'); throw new \Exception('Invalid file group');
} }
@ -28,7 +28,7 @@ class FilesApiController extends BaseApiController
throw new \Exception('Invalid filename'); throw new \Exception('Invalid filename');
} }
$this->getFilesService()->DeleteFile($args['group'], $fileName); FilesService::GetInstance()->DeleteFile($args['group'], $fileName);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
@ -42,13 +42,13 @@ class FilesApiController extends BaseApiController
{ {
try try
{ {
if (!in_array($args['group'], $this->getOpenApiSpec()->components->schemas->FileGroups->enum)) if (!in_array($args['group'], $this->GetOpenApispec()->components->schemas->FileGroups->enum))
{ {
throw new \Exception('Invalid file group'); throw new \Exception('Invalid file group');
} }
$fileName = $this->checkFileName($args['fileName']); $fileName = $this->CheckFileName($args['fileName']);
$filePath = $this->getFilePath($args['group'], $fileName, $request->getQueryParams()); $filePath = $this->GetFilePath($args['group'], $fileName, $request->getQueryParams());
if (file_exists($filePath)) if (file_exists($filePath))
{ {
@ -72,14 +72,14 @@ class FilesApiController extends BaseApiController
{ {
try try
{ {
if (!in_array($args['group'], $this->getOpenApiSpec()->components->schemas->FileGroups->enum)) if (!in_array($args['group'], $this->GetOpenApispec()->components->schemas->FileGroups->enum))
{ {
throw new \Exception('Invalid file group'); throw new \Exception('Invalid file group');
} }
$fileInfo = explode('_', $args['fileName']); $fileInfo = explode('_', $args['fileName']);
$fileName = $this->checkFileName($fileInfo[1]); $fileName = $this->CheckFileName($fileInfo[1]);
$filePath = $this->getFilePath($args['group'], base64_decode($fileInfo[0]), $request->getQueryParams()); $filePath = $this->GetFilePath($args['group'], base64_decode($fileInfo[0]), $request->getQueryParams());
if (file_exists($filePath)) if (file_exists($filePath))
{ {
@ -103,15 +103,15 @@ class FilesApiController extends BaseApiController
{ {
try try
{ {
if (!in_array($args['group'], $this->getOpenApiSpec()->components->schemas->FileGroups->enum)) if (!in_array($args['group'], $this->GetOpenApispec()->components->schemas->FileGroups->enum))
{ {
throw new \Exception('Invalid file group'); throw new \Exception('Invalid file group');
} }
$fileName = $this->checkFileName($args['fileName']); $fileName = $this->CheckFileName($args['fileName']);
$fileHandle = fopen($this->getFilesService()->GetFilePath($args['group'], $fileName), 'xb'); $fileHandle = fopen(FilesService::GetInstance()->GetFilePath($args['group'], $fileName), 'xb');
if($fileHandle === false) if ($fileHandle === false)
{ {
throw new \Exception("Error while creating file $fileName"); throw new \Exception("Error while creating file $fileName");
} }
@ -139,7 +139,7 @@ class FilesApiController extends BaseApiController
} }
} }
protected function checkFileName(string $fileName) protected function CheckFileName(string $fileName)
{ {
if (IsValidFileName(base64_decode($fileName))) if (IsValidFileName(base64_decode($fileName)))
{ {
@ -153,7 +153,7 @@ class FilesApiController extends BaseApiController
return $fileName; return $fileName;
} }
protected function getFilePath(string $group, string $fileName, array $queryParams = []) protected function GetFilePath(string $group, string $fileName, array $queryParams = [])
{ {
$forceServeAs = null; $forceServeAs = null;
if (isset($queryParams['force_serve_as']) && !empty($queryParams['force_serve_as'])) if (isset($queryParams['force_serve_as']) && !empty($queryParams['force_serve_as']))
@ -175,11 +175,11 @@ class FilesApiController extends BaseApiController
$bestFitWidth = $queryParams['best_fit_width']; $bestFitWidth = $queryParams['best_fit_width'];
} }
$filePath = $this->getFilesService()->DownscaleImage($group, $fileName, $bestFitHeight, $bestFitWidth); $filePath = FilesService::GetInstance()->DownscaleImage($group, $fileName, $bestFitHeight, $bestFitWidth);
} }
else else
{ {
$filePath = $this->getFilesService()->GetFilePath($group, $fileName); $filePath = FilesService::GetInstance()->GetFilePath($group, $fileName);
} }
return $filePath; return $filePath;

View File

@ -1,8 +1,11 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\StockService;
use Grocy\Services\UsersService;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -12,30 +15,30 @@ class GenericEntityApiController extends BaseApiController
{ {
if ($args['entity'] == 'shopping_list' || $args['entity'] == 'shopping_lists') if ($args['entity'] == 'shopping_list' || $args['entity'] == 'shopping_lists')
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD);
} }
elseif ($args['entity'] == 'recipes' || $args['entity'] == 'recipes_pos' || $args['entity'] == 'recipes_nestings') elseif ($args['entity'] == 'recipes' || $args['entity'] == 'recipes_pos' || $args['entity'] == 'recipes_nestings')
{ {
User::checkPermission($request, User::PERMISSION_RECIPES); User::CheckPermission($request, User::PERMISSION_RECIPES);
} }
elseif ($args['entity'] == 'meal_plan') elseif ($args['entity'] == 'meal_plan')
{ {
User::checkPermission($request, User::PERMISSION_RECIPES_MEALPLAN); User::CheckPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
} }
elseif ($args['entity'] == 'equipment') elseif ($args['entity'] == 'equipment')
{ {
User::checkPermission($request, User::PERMISSION_EQUIPMENT); User::CheckPermission($request, User::PERMISSION_EQUIPMENT);
} }
else else
{ {
User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); User::CheckPermission($request, User::PERMISSION_MASTER_DATA_EDIT);
} }
if ($this->IsValidExposedEntity($args['entity']) && !$this->IsEntityWithNoEdit($args['entity'])) if ($this->IsValidExposedEntity($args['entity']) && !$this->IsEntityWithNoEdit($args['entity']))
{ {
if ($this->IsEntityWithEditRequiresAdmin($args['entity'])) if ($this->IsEntityWithEditRequiresAdmin($args['entity']))
{ {
User::checkPermission($request, User::PERMISSION_ADMIN); User::CheckPermission($request, User::PERMISSION_ADMIN);
} }
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -47,14 +50,14 @@ 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->getDatabase()->{$args['entity']}()->createRow($requestBody); $newRow = $this->DB->{$args['entity']}()->createRow($requestBody);
$newRow->save(); $newRow->save();
$newObjectId = $this->getDatabase()->lastInsertId(); $newObjectId = $this->DB->lastInsertId();
// TODO: This should be better done somehow in StockService // TODO: This should be better done somehow in StockService
if ($args['entity'] == 'products' && boolval($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount'))) if ($args['entity'] == 'products' && boolval(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount')))
{ {
$this->getStockService()->AddMissingProductsToShoppingList($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id')); StockService::GetInstance()->AddMissingProductsToShoppingList(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id'));
} }
return $this->ApiResponse($response, [ return $this->ApiResponse($response, [
@ -76,19 +79,19 @@ class GenericEntityApiController extends BaseApiController
{ {
if ($args['entity'] == 'shopping_list' || $args['entity'] == 'shopping_lists') if ($args['entity'] == 'shopping_list' || $args['entity'] == 'shopping_lists')
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE);
} }
elseif ($args['entity'] == 'recipes' || $args['entity'] == 'recipes_pos' || $args['entity'] == 'recipes_nestings') elseif ($args['entity'] == 'recipes' || $args['entity'] == 'recipes_pos' || $args['entity'] == 'recipes_nestings')
{ {
User::checkPermission($request, User::PERMISSION_RECIPES); User::CheckPermission($request, User::PERMISSION_RECIPES);
} }
elseif ($args['entity'] == 'meal_plan') elseif ($args['entity'] == 'meal_plan')
{ {
User::checkPermission($request, User::PERMISSION_RECIPES_MEALPLAN); User::CheckPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
} }
elseif ($args['entity'] == 'equipment') elseif ($args['entity'] == 'equipment')
{ {
User::checkPermission($request, User::PERMISSION_EQUIPMENT); User::CheckPermission($request, User::PERMISSION_EQUIPMENT);
} }
elseif ($args['entity'] == 'api_keys') elseif ($args['entity'] == 'api_keys')
{ {
@ -96,17 +99,17 @@ class GenericEntityApiController extends BaseApiController
} }
else else
{ {
User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); User::CheckPermission($request, User::PERMISSION_MASTER_DATA_EDIT);
} }
if ($this->IsValidExposedEntity($args['entity']) && !$this->IsEntityWithNoDelete($args['entity'])) if ($this->IsValidExposedEntity($args['entity']) && !$this->IsEntityWithNoDelete($args['entity']))
{ {
if ($this->IsEntityWithEditRequiresAdmin($args['entity'])) if ($this->IsEntityWithEditRequiresAdmin($args['entity']))
{ {
User::checkPermission($request, User::PERMISSION_ADMIN); User::CheckPermission($request, User::PERMISSION_ADMIN);
} }
$row = $this->getDatabase()->{$args['entity']}($args['objectId']); $row = $this->DB->{$args['entity']}($args['objectId']);
if ($row == null) if ($row == null)
{ {
return $this->GenericErrorResponse($response, 'Object not found', 400); return $this->GenericErrorResponse($response, 'Object not found', 400);
@ -126,30 +129,30 @@ class GenericEntityApiController extends BaseApiController
{ {
if ($args['entity'] == 'shopping_list' || $args['entity'] == 'shopping_lists') if ($args['entity'] == 'shopping_list' || $args['entity'] == 'shopping_lists')
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD);
} }
elseif ($args['entity'] == 'recipes' || $args['entity'] == 'recipes_pos' || $args['entity'] == 'recipes_nestings') elseif ($args['entity'] == 'recipes' || $args['entity'] == 'recipes_pos' || $args['entity'] == 'recipes_nestings')
{ {
User::checkPermission($request, User::PERMISSION_RECIPES); User::CheckPermission($request, User::PERMISSION_RECIPES);
} }
elseif ($args['entity'] == 'meal_plan') elseif ($args['entity'] == 'meal_plan')
{ {
User::checkPermission($request, User::PERMISSION_RECIPES_MEALPLAN); User::CheckPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
} }
elseif ($args['entity'] == 'equipment') elseif ($args['entity'] == 'equipment')
{ {
User::checkPermission($request, User::PERMISSION_EQUIPMENT); User::CheckPermission($request, User::PERMISSION_EQUIPMENT);
} }
else else
{ {
User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); User::CheckPermission($request, User::PERMISSION_MASTER_DATA_EDIT);
} }
if ($this->IsValidExposedEntity($args['entity']) && !$this->IsEntityWithNoEdit($args['entity'])) if ($this->IsValidExposedEntity($args['entity']) && !$this->IsEntityWithNoEdit($args['entity']))
{ {
if ($this->IsEntityWithEditRequiresAdmin($args['entity'])) if ($this->IsEntityWithEditRequiresAdmin($args['entity']))
{ {
User::checkPermission($request, User::PERMISSION_ADMIN); User::CheckPermission($request, User::PERMISSION_ADMIN);
} }
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -161,7 +164,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->getDatabase()->{$args['entity']}($args['objectId']); $row = $this->DB->{$args['entity']}($args['objectId']);
if ($row == null) if ($row == null)
{ {
return $this->GenericErrorResponse($response, 'Object not found', 400); return $this->GenericErrorResponse($response, 'Object not found', 400);
@ -170,9 +173,9 @@ class GenericEntityApiController extends BaseApiController
$row->update($requestBody); $row->update($requestBody);
// TODO: This should be better done somehow in StockService // TODO: This should be better done somehow in StockService
if ($args['entity'] == 'products' && boolval($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount'))) if ($args['entity'] == 'products' && boolval(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount')))
{ {
$this->getStockService()->AddMissingProductsToShoppingList($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id')); StockService::GetInstance()->AddMissingProductsToShoppingList(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id'));
} }
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
@ -195,7 +198,7 @@ class GenericEntityApiController extends BaseApiController
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed'); return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
} }
$object = $this->getDatabase()->{$args['entity']}($args['objectId']); $object = $this->DB->{$args['entity']}($args['objectId']);
if ($object == null) if ($object == null)
{ {
return $this->GenericErrorResponse($response, 'Object not found', 404); return $this->GenericErrorResponse($response, 'Object not found', 404);
@ -207,7 +210,7 @@ class GenericEntityApiController extends BaseApiController
{ {
$referencingId = $object->stock_id; $referencingId = $object->stock_id;
} }
$userfields = $this->getUserfieldsService()->GetValues($args['entity'], $referencingId); $userfields = UserfieldsService::GetInstance()->GetValues($args['entity'], $referencingId);
if (count($userfields) === 0) if (count($userfields) === 0)
{ {
$userfields = null; $userfields = null;
@ -224,12 +227,12 @@ class GenericEntityApiController extends BaseApiController
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed'); return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
} }
$objects = $this->queryData($this->getDatabase()->{$args['entity']}(), $request->getQueryParams()); $objects = $this->QueryData($this->DB->{$args['entity']}(), $request->getQueryParams());
$userfields = $this->getUserfieldsService()->GetFields($args['entity']); $userfields = UserfieldsService::GetInstance()->GetFields($args['entity']);
if (count($userfields) > 0) if (count($userfields) > 0)
{ {
$allUserfieldValues = $this->getUserfieldsService()->GetAllValues($args['entity']); $allUserfieldValues = UserfieldsService::GetInstance()->GetAllValues($args['entity']);
foreach ($objects as $object) foreach ($objects as $object)
{ {
@ -265,7 +268,7 @@ class GenericEntityApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->getUserfieldsService()->GetValues($args['entity'], $args['objectId'])); return $this->ApiResponse($response, UserfieldsService::GetInstance()->GetValues($args['entity'], $args['objectId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -275,7 +278,7 @@ class GenericEntityApiController extends BaseApiController
public function SetUserfields(Request $request, Response $response, array $args) public function SetUserfields(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); User::CheckPermission($request, User::PERMISSION_MASTER_DATA_EDIT);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -286,7 +289,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->getUserfieldsService()->SetValues($args['entity'], $args['objectId'], $requestBody); UserfieldsService::GetInstance()->SetValues($args['entity'], $args['objectId'], $requestBody);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -297,26 +300,26 @@ class GenericEntityApiController extends BaseApiController
private function IsEntityWithEditRequiresAdmin($entity) private function IsEntityWithEditRequiresAdmin($entity)
{ {
return in_array($entity, $this->getOpenApiSpec()->components->schemas->ExposedEntityEditRequiresAdmin->enum); return in_array($entity, $this->GetOpenApispec()->components->schemas->ExposedEntityEditRequiresAdmin->enum);
} }
private function IsEntityWithNoListing($entity) private function IsEntityWithNoListing($entity)
{ {
return in_array($entity, $this->getOpenApiSpec()->components->schemas->ExposedEntityNoListing->enum); return in_array($entity, $this->GetOpenApispec()->components->schemas->ExposedEntityNoListing->enum);
} }
private function IsEntityWithNoEdit($entity) private function IsEntityWithNoEdit($entity)
{ {
return in_array($entity, $this->getOpenApiSpec()->components->schemas->ExposedEntityNoEdit->enum); return in_array($entity, $this->GetOpenApispec()->components->schemas->ExposedEntityNoEdit->enum);
} }
private function IsEntityWithNoDelete($entity) private function IsEntityWithNoDelete($entity)
{ {
return in_array($entity, $this->getOpenApiSpec()->components->schemas->ExposedEntityNoDelete->enum); return in_array($entity, $this->GetOpenApispec()->components->schemas->ExposedEntityNoDelete->enum);
} }
private function IsValidExposedEntity($entity) private function IsValidExposedEntity($entity)
{ {
return in_array($entity, $this->getOpenApiSpec()->components->schemas->ExposedEntity->enum); return in_array($entity, $this->GetOpenApispec()->components->schemas->ExposedEntity->enum);
} }
} }

View File

@ -1,9 +1,11 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\ApiKeyService; use Grocy\Services\ApiKeyService;
use Grocy\Services\ApplicationService;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -17,15 +19,15 @@ class OpenApiController extends BaseApiController
$selectedKeyId = $request->getQueryParams()['key']; $selectedKeyId = $request->getQueryParams()['key'];
} }
$apiKeys = $this->getDatabase()->api_keys(); $apiKeys = $this->DB->api_keys();
if (!User::hasPermissions(User::PERMISSION_ADMIN)) if (!User::HasPermissions(User::PERMISSION_ADMIN))
{ {
$apiKeys = $apiKeys->where('user_id', GROCY_USER_ID); $apiKeys = $apiKeys->where('user_id', GROCY_USER_ID);
} }
return $this->renderPage($response, 'manageapikeys', [ return $this->RenderPage($response, 'manageapikeys', [
'apiKeys' => $apiKeys, 'apiKeys' => $apiKeys,
'users' => $this->getDatabase()->users(), 'users' => $this->DB->users(),
'selectedKeyId' => $selectedKeyId 'selectedKeyId' => $selectedKeyId
]); ]);
} }
@ -38,16 +40,16 @@ class OpenApiController extends BaseApiController
$description = $request->getQueryParams()['description']; $description = $request->getQueryParams()['description'];
} }
$newApiKey = $this->getApiKeyService()->CreateApiKey(ApiKeyService::API_KEY_TYPE_DEFAULT, $description); $newApiKey = ApiKeyService::GetInstance()->CreateApiKey(ApiKeyService::API_KEY_TYPE_DEFAULT, $description);
$newApiKeyId = $this->getApiKeyService()->GetApiKeyId($newApiKey); $newApiKeyId = ApiKeyService::GetInstance()->GetApiKeyId($newApiKey);
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl("/manageapikeys?key=$newApiKeyId")); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl("/manageapikeys?key=$newApiKeyId"));
} }
public function DocumentationSpec(Request $request, Response $response, array $args) public function DocumentationSpec(Request $request, Response $response, array $args)
{ {
$spec = $this->getOpenApiSpec(); $spec = $this->GetOpenApispec();
$applicationService = $this->getApplicationService(); $applicationService = ApplicationService::GetInstance();
$versionInfo = $applicationService->GetInstalledVersion(); $versionInfo = $applicationService->GetInstalledVersion();
$spec->info->version = $versionInfo->Version; $spec->info->version = $versionInfo->Version;
$spec->info->description = str_replace('PlaceHolderManageApiKeysUrl', $this->AppContainer->get('UrlManager')->ConstructUrl('/manageapikeys'), $spec->info->description); $spec->info->description = str_replace('PlaceHolderManageApiKeysUrl', $this->AppContainer->get('UrlManager')->ConstructUrl('/manageapikeys'), $spec->info->description);
@ -55,7 +57,7 @@ class OpenApiController extends BaseApiController
$spec->components->schemas->ExposedEntity_IncludingUserEntities = clone $spec->components->schemas->StringEnumTemplate; $spec->components->schemas->ExposedEntity_IncludingUserEntities = clone $spec->components->schemas->StringEnumTemplate;
; ;
foreach ($this->getUserfieldsService()->GetEntities() as $userEntity) foreach (UserfieldsService::GetInstance()->GetEntities() as $userEntity)
{ {
array_push($spec->components->schemas->ExposedEntity_IncludingUserEntities->enum, $userEntity); array_push($spec->components->schemas->ExposedEntity_IncludingUserEntities->enum, $userEntity);
} }
@ -107,6 +109,6 @@ class OpenApiController extends BaseApiController
public function DocumentationUi(Request $request, Response $response, array $args) public function DocumentationUi(Request $request, Response $response, array $args)
{ {
return $this->render($response, 'openapiui'); return $this->Render($response, 'openapiui');
} }
} }

View File

@ -1,8 +1,10 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\PrintService;
use Grocy\Services\StockService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -12,7 +14,7 @@ class PrintApiController extends BaseApiController
{ {
try try
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST);
$params = $request->getQueryParams(); $params = $request->getQueryParams();
@ -27,8 +29,8 @@ class PrintApiController extends BaseApiController
{ {
$printHeader = ($params['printHeader'] === 'true'); $printHeader = ($params['printHeader'] === 'true');
} }
$items = $this->getStockService()->GetShoppinglistInPrintableStrings($listId); $items = StockService::GetInstance()->GetShoppinglistInPrintableStrings($listId);
return $this->ApiResponse($response, $this->getPrintService()->printShoppingList($printHeader, $items)); return $this->ApiResponse($response, PrintService::GetInstance()->printShoppingList($printHeader, $items));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {

View File

@ -1,10 +1,11 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Helpers\WebhookRunner; use Grocy\Helpers\WebhookRunner;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
use Grocy\Services\RecipesService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -12,7 +13,7 @@ class RecipesApiController extends BaseApiController
{ {
public function AddNotFulfilledProductsToShoppingList(Request $request, Response $response, array $args) public function AddNotFulfilledProductsToShoppingList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
$excludedProductIds = null; $excludedProductIds = null;
@ -22,17 +23,17 @@ class RecipesApiController extends BaseApiController
$excludedProductIds = $requestBody['excludedProductIds']; $excludedProductIds = $requestBody['excludedProductIds'];
} }
$this->getRecipesService()->AddNotFulfilledProductsToShoppingList($args['recipeId'], $excludedProductIds); RecipesService::GetInstance()->AddNotFulfilledProductsToShoppingList($args['recipeId'], $excludedProductIds);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
public function ConsumeRecipe(Request $request, Response $response, array $args) public function ConsumeRecipe(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_CONSUME); User::CheckPermission($request, User::PERMISSION_STOCK_CONSUME);
try try
{ {
$this->getRecipesService()->ConsumeRecipe($args['recipeId']); RecipesService::GetInstance()->ConsumeRecipe($args['recipeId']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -47,10 +48,10 @@ class RecipesApiController extends BaseApiController
{ {
if (!isset($args['recipeId'])) if (!isset($args['recipeId']))
{ {
return $this->FilteredApiResponse($response, $this->getRecipesService()->GetRecipesResolved(), $request->getQueryParams()); return $this->FilteredApiResponse($response, RecipesService::GetInstance()->GetRecipesResolved(), $request->getQueryParams());
} }
$recipeResolved = FindObjectInArrayByPropertyValue($this->getRecipesService()->GetRecipesResolved(), 'recipe_id', $args['recipeId']); $recipeResolved = FindObjectInArrayByPropertyValue(RecipesService::GetInstance()->GetRecipesResolved(), 'recipe_id', $args['recipeId']);
if (!$recipeResolved) if (!$recipeResolved)
{ {
@ -72,7 +73,7 @@ class RecipesApiController extends BaseApiController
try try
{ {
return $this->ApiResponse($response, [ return $this->ApiResponse($response, [
'created_object_id' => $this->getRecipesService()->CopyRecipe($args['recipeId']) 'created_object_id' => RecipesService::GetInstance()->CopyRecipe($args['recipeId'])
]); ]);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -85,7 +86,7 @@ class RecipesApiController extends BaseApiController
{ {
try try
{ {
$recipe = $this->getDatabase()->recipes()->where('id', $args['recipeId'])->fetch(); $recipe = $this->DB->recipes()->where('id', $args['recipeId'])->fetch();
$webhookData = array_merge([ $webhookData = array_merge([
'recipe' => $recipe->name, 'recipe' => $recipe->name,

View File

@ -1,8 +1,9 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\LocalizationService;
use Grocy\Services\StockService; use Grocy\Services\StockService;
use Grocy\Helpers\WebhookRunner; use Grocy\Helpers\WebhookRunner;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
@ -13,7 +14,7 @@ class StockApiController extends BaseApiController
{ {
public function AddMissingProductsToShoppingList(Request $request, Response $response, array $args) public function AddMissingProductsToShoppingList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD);
try try
{ {
@ -26,7 +27,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']); $listId = intval($requestBody['list_id']);
} }
$this->getStockService()->AddMissingProductsToShoppingList($listId); StockService::GetInstance()->AddMissingProductsToShoppingList($listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -37,7 +38,7 @@ class StockApiController extends BaseApiController
public function AddOverdueProductsToShoppingList(Request $request, Response $response, array $args) public function AddOverdueProductsToShoppingList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD);
try try
{ {
@ -50,7 +51,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']); $listId = intval($requestBody['list_id']);
} }
$this->getStockService()->AddOverdueProductsToShoppingList($listId); StockService::GetInstance()->AddOverdueProductsToShoppingList($listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -61,7 +62,7 @@ class StockApiController extends BaseApiController
public function AddExpiredProductsToShoppingList(Request $request, Response $response, array $args) public function AddExpiredProductsToShoppingList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD);
try try
{ {
@ -74,7 +75,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']); $listId = intval($requestBody['list_id']);
} }
$this->getStockService()->AddExpiredProductsToShoppingList($listId); StockService::GetInstance()->AddExpiredProductsToShoppingList($listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -85,7 +86,7 @@ class StockApiController extends BaseApiController
public function AddProduct(Request $request, Response $response, array $args) public function AddProduct(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_PURCHASE); User::CheckPermission($request, User::PERMISSION_STOCK_PURCHASE);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -149,7 +150,7 @@ class StockApiController extends BaseApiController
$note = $requestBody['note']; $note = $requestBody['note'];
} }
$transactionId = $this->getStockService()->AddProduct($args['productId'], $requestBody['amount'], $bestBeforeDate, $transactionType, $purchasedDate, $price, $locationId, $shoppingLocationId, $unusedTransactionId, $stockLabelType, false, $note); $transactionId = StockService::GetInstance()->AddProduct($args['productId'], $requestBody['amount'], $bestBeforeDate, $transactionType, $purchasedDate, $price, $locationId, $shoppingLocationId, $unusedTransactionId, $stockLabelType, false, $note);
$args['transactionId'] = $transactionId; $args['transactionId'] = $transactionId;
return $this->StockTransactions($request, $response, $args); return $this->StockTransactions($request, $response, $args);
@ -164,7 +165,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); $args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
return $this->AddProduct($request, $response, $args); return $this->AddProduct($request, $response, $args);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -175,7 +176,7 @@ class StockApiController extends BaseApiController
public function AddProductToShoppingList(Request $request, Response $response, array $args) public function AddProductToShoppingList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_ADD);
try try
{ {
@ -217,7 +218,7 @@ class StockApiController extends BaseApiController
throw new \Exception('No product id was supplied'); throw new \Exception('No product id was supplied');
} }
$this->getStockService()->AddProductToShoppingList($productId, $amount, $quId, $note, $listId); StockService::GetInstance()->AddProductToShoppingList($productId, $amount, $quId, $note, $listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -228,7 +229,7 @@ class StockApiController extends BaseApiController
public function ClearShoppingList(Request $request, Response $response, array $args) public function ClearShoppingList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE);
try try
{ {
@ -246,7 +247,7 @@ class StockApiController extends BaseApiController
$doneOnly = boolval($requestBody['done_only']); $doneOnly = boolval($requestBody['done_only']);
} }
$this->getStockService()->ClearShoppingList($listId, $doneOnly); StockService::GetInstance()->ClearShoppingList($listId, $doneOnly);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -257,7 +258,7 @@ class StockApiController extends BaseApiController
public function ConsumeProduct(Request $request, Response $response, array $args) public function ConsumeProduct(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_CONSUME); User::CheckPermission($request, User::PERMISSION_STOCK_CONSUME);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -316,7 +317,7 @@ class StockApiController extends BaseApiController
} }
$transactionId = null; $transactionId = null;
$transactionId = $this->getStockService()->ConsumeProduct($args['productId'], $requestBody['amount'], $spoiled, $transactionType, $specificStockEntryId, $recipeId, $locationId, $transactionId, $allowSubproductSubstitution, $consumeExact); $transactionId = StockService::GetInstance()->ConsumeProduct($args['productId'], $requestBody['amount'], $spoiled, $transactionType, $specificStockEntryId, $recipeId, $locationId, $transactionId, $allowSubproductSubstitution, $consumeExact);
$args['transactionId'] = $transactionId; $args['transactionId'] = $transactionId;
return $this->StockTransactions($request, $response, $args); return $this->StockTransactions($request, $response, $args);
} }
@ -330,7 +331,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); $args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
if (Grocycode::Validate($args['barcode'])) if (Grocycode::Validate($args['barcode']))
{ {
@ -353,7 +354,7 @@ class StockApiController extends BaseApiController
public function CurrentStock(Request $request, Response $response, array $args) public function CurrentStock(Request $request, Response $response, array $args)
{ {
return $this->ApiResponse($response, $this->getStockService()->GetCurrentStock()); return $this->ApiResponse($response, StockService::GetInstance()->GetCurrentStock());
} }
public function CurrentVolatileStock(Request $request, Response $response, array $args) public function CurrentVolatileStock(Request $request, Response $response, array $args)
@ -365,10 +366,10 @@ class StockApiController extends BaseApiController
$nextXDays = $request->getQueryParams()['due_soon_days']; $nextXDays = $request->getQueryParams()['due_soon_days'];
} }
$dueProducts = $this->getStockService()->GetDueProducts($nextXDays, true); $dueProducts = StockService::GetInstance()->GetDueProducts($nextXDays, true);
$overdueProducts = $this->getStockService()->GetDueProducts(-1); $overdueProducts = StockService::GetInstance()->GetDueProducts(-1);
$expiredProducts = $this->getStockService()->GetExpiredProducts(); $expiredProducts = StockService::GetInstance()->GetExpiredProducts();
$missingProducts = $this->getStockService()->GetMissingProducts(); $missingProducts = StockService::GetInstance()->GetMissingProducts();
return $this->ApiResponse($response, [ return $this->ApiResponse($response, [
'due_products' => $dueProducts, 'due_products' => $dueProducts,
'overdue_products' => $overdueProducts, 'overdue_products' => $overdueProducts,
@ -379,7 +380,7 @@ class StockApiController extends BaseApiController
public function EditStockEntry(Request $request, Response $response, array $args) public function EditStockEntry(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_EDIT); User::CheckPermission($request, User::PERMISSION_STOCK_EDIT);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -425,7 +426,7 @@ class StockApiController extends BaseApiController
$note = $requestBody['note']; $note = $requestBody['note'];
} }
$transactionId = $this->getStockService()->EditStockEntry($args['entryId'], $requestBody['amount'], $bestBeforeDate, $locationId, $shoppingLocationId, $price, $requestBody['open'], $requestBody['purchased_date'], $note); $transactionId = StockService::GetInstance()->EditStockEntry($args['entryId'], $requestBody['amount'], $bestBeforeDate, $locationId, $shoppingLocationId, $price, $requestBody['open'], $requestBody['purchased_date'], $note);
$args['transactionId'] = $transactionId; $args['transactionId'] = $transactionId;
return $this->StockTransactions($request, $response, $args); return $this->StockTransactions($request, $response, $args);
} }
@ -437,7 +438,7 @@ class StockApiController extends BaseApiController
public function ExternalBarcodeLookup(Request $request, Response $response, array $args) public function ExternalBarcodeLookup(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_MASTER_DATA_EDIT); User::CheckPermission($request, User::PERMISSION_MASTER_DATA_EDIT);
try try
{ {
@ -447,7 +448,7 @@ class StockApiController extends BaseApiController
$addFoundProduct = true; $addFoundProduct = true;
} }
return $this->ApiResponse($response, $this->getStockService()->ExternalBarcodeLookup($args['barcode'], $addFoundProduct)); return $this->ApiResponse($response, StockService::GetInstance()->ExternalBarcodeLookup($args['barcode'], $addFoundProduct));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -457,7 +458,7 @@ class StockApiController extends BaseApiController
public function InventoryProduct(Request $request, Response $response, array $args) public function InventoryProduct(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_INVENTORY); User::CheckPermission($request, User::PERMISSION_STOCK_INVENTORY);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -515,7 +516,7 @@ class StockApiController extends BaseApiController
$note = $requestBody['note']; $note = $requestBody['note'];
} }
$transactionId = $this->getStockService()->InventoryProduct($args['productId'], $requestBody['new_amount'], $bestBeforeDate, $locationId, $price, $shoppingLocationId, $purchasedDate, $stockLabelType, $note); $transactionId = StockService::GetInstance()->InventoryProduct($args['productId'], $requestBody['new_amount'], $bestBeforeDate, $locationId, $price, $shoppingLocationId, $purchasedDate, $stockLabelType, $note);
$args['transactionId'] = $transactionId; $args['transactionId'] = $transactionId;
return $this->StockTransactions($request, $response, $args); return $this->StockTransactions($request, $response, $args);
} }
@ -529,7 +530,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); $args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
return $this->InventoryProduct($request, $response, $args); return $this->InventoryProduct($request, $response, $args);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -540,7 +541,7 @@ class StockApiController extends BaseApiController
public function OpenProduct(Request $request, Response $response, array $args) public function OpenProduct(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_OPEN); User::CheckPermission($request, User::PERMISSION_STOCK_OPEN);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -569,7 +570,7 @@ class StockApiController extends BaseApiController
} }
$transactionId = null; $transactionId = null;
$transactionId = $this->getStockService()->OpenProduct($args['productId'], $requestBody['amount'], $specificStockEntryId, $transactionId, $allowSubproductSubstitution); $transactionId = StockService::GetInstance()->OpenProduct($args['productId'], $requestBody['amount'], $specificStockEntryId, $transactionId, $allowSubproductSubstitution);
$args['transactionId'] = $transactionId; $args['transactionId'] = $transactionId;
return $this->StockTransactions($request, $response, $args); return $this->StockTransactions($request, $response, $args);
} }
@ -583,7 +584,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); $args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
if (Grocycode::Validate($args['barcode'])) if (Grocycode::Validate($args['barcode']))
{ {
@ -608,7 +609,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($args['productId'])); return $this->ApiResponse($response, StockService::GetInstance()->GetProductDetails($args['productId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -620,8 +621,8 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$productId = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); $productId = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($productId)); return $this->ApiResponse($response, StockService::GetInstance()->GetProductDetails($productId));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -633,7 +634,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->getStockService()->GetProductPriceHistory($args['productId'])); return $this->ApiResponse($response, StockService::GetInstance()->GetProductPriceHistory($args['productId']));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -649,12 +650,12 @@ class StockApiController extends BaseApiController
$allowSubproductSubstitution = true; $allowSubproductSubstitution = true;
} }
return $this->FilteredApiResponse($response, $this->getStockService()->GetProductStockEntries($args['productId'], false, $allowSubproductSubstitution), $request->getQueryParams()); return $this->FilteredApiResponse($response, StockService::GetInstance()->GetProductStockEntries($args['productId'], false, $allowSubproductSubstitution), $request->getQueryParams());
} }
public function LocationStockEntries(Request $request, Response $response, array $args) public function LocationStockEntries(Request $request, Response $response, array $args)
{ {
return $this->FilteredApiResponse($response, $this->getStockService()->GetLocationStockEntries($args['locationId']), $request->getQueryParams()); return $this->FilteredApiResponse($response, StockService::GetInstance()->GetLocationStockEntries($args['locationId']), $request->getQueryParams());
} }
public function ProductStockLocations(Request $request, Response $response, array $args) public function ProductStockLocations(Request $request, Response $response, array $args)
@ -665,14 +666,14 @@ class StockApiController extends BaseApiController
$allowSubproductSubstitution = true; $allowSubproductSubstitution = true;
} }
return $this->FilteredApiResponse($response, $this->getStockService()->GetProductStockLocations($args['productId'], $allowSubproductSubstitution), $request->getQueryParams()); return $this->FilteredApiResponse($response, StockService::GetInstance()->GetProductStockLocations($args['productId'], $allowSubproductSubstitution), $request->getQueryParams());
} }
public function ProductPrintLabel(Request $request, Response $response, array $args) public function ProductPrintLabel(Request $request, Response $response, array $args)
{ {
try try
{ {
$productDetails = (object)$this->getStockService()->GetProductDetails($args['productId']); $productDetails = (object)StockService::GetInstance()->GetProductDetails($args['productId']);
$webhookData = array_merge([ $webhookData = array_merge([
'product' => $productDetails->product->name, 'product' => $productDetails->product->name,
@ -697,8 +698,8 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$stockEntry = $this->getDatabase()->stock()->where('id', $args['entryId'])->fetch(); $stockEntry = $this->DB->stock()->where('id', $args['entryId'])->fetch();
$productDetails = (object)$this->getStockService()->GetProductDetails($stockEntry->product_id); $productDetails = (object)StockService::GetInstance()->GetProductDetails($stockEntry->product_id);
$webhookData = array_merge([ $webhookData = array_merge([
'product' => $productDetails->product->name, 'product' => $productDetails->product->name,
@ -709,7 +710,7 @@ class StockApiController extends BaseApiController
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
$webhookData['due_date'] = $this->getLocalizationService()->__t('DD') . ': ' . $stockEntry->best_before_date; $webhookData['due_date'] = LocalizationService::GetInstance()->__t('DD') . ': ' . $stockEntry->best_before_date;
} }
if (GROCY_LABEL_PRINTER_RUN_SERVER) if (GROCY_LABEL_PRINTER_RUN_SERVER)
@ -727,7 +728,7 @@ class StockApiController extends BaseApiController
public function RemoveProductFromShoppingList(Request $request, Response $response, array $args) public function RemoveProductFromShoppingList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE); User::CheckPermission($request, User::PERMISSION_SHOPPINGLIST_ITEMS_DELETE);
try try
{ {
@ -757,7 +758,7 @@ class StockApiController extends BaseApiController
throw new \Exception('No product id was supplied'); throw new \Exception('No product id was supplied');
} }
$this->getStockService()->RemoveProductFromShoppingList($productId, $amount, $listId); StockService::GetInstance()->RemoveProductFromShoppingList($productId, $amount, $listId);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -770,7 +771,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$stockLogRow = $this->getDatabase()->stock_log($args['bookingId']); $stockLogRow = $this->DB->stock_log($args['bookingId']);
if ($stockLogRow === null) if ($stockLogRow === null)
{ {
@ -787,14 +788,14 @@ class StockApiController extends BaseApiController
public function StockEntry(Request $request, Response $response, array $args) public function StockEntry(Request $request, Response $response, array $args)
{ {
return $this->ApiResponse($response, $this->getStockService()->GetStockEntry($args['entryId'])); return $this->ApiResponse($response, StockService::GetInstance()->GetStockEntry($args['entryId']));
} }
public function StockTransactions(Request $request, Response $response, array $args) public function StockTransactions(Request $request, Response $response, array $args)
{ {
try try
{ {
$transactionRows = $this->getDatabase()->stock_log()->where('transaction_id = :1', $args['transactionId'])->fetchAll(); $transactionRows = $this->DB->stock_log()->where('transaction_id = :1', $args['transactionId'])->fetchAll();
if (count($transactionRows) === 0) if (count($transactionRows) === 0)
{ {
throw new \Exception('No transaction was found by the given transaction id'); throw new \Exception('No transaction was found by the given transaction id');
@ -810,7 +811,7 @@ class StockApiController extends BaseApiController
public function TransferProduct(Request $request, Response $response, array $args) public function TransferProduct(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_TRANSFER); User::CheckPermission($request, User::PERMISSION_STOCK_TRANSFER);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -843,7 +844,7 @@ class StockApiController extends BaseApiController
$specificStockEntryId = $requestBody['stock_entry_id']; $specificStockEntryId = $requestBody['stock_entry_id'];
} }
$transactionId = $this->getStockService()->TransferProduct($args['productId'], $requestBody['amount'], $requestBody['location_id_from'], $requestBody['location_id_to'], $specificStockEntryId); $transactionId = StockService::GetInstance()->TransferProduct($args['productId'], $requestBody['amount'], $requestBody['location_id_from'], $requestBody['location_id_to'], $specificStockEntryId);
$args['transactionId'] = $transactionId; $args['transactionId'] = $transactionId;
return $this->StockTransactions($request, $response, $args); return $this->StockTransactions($request, $response, $args);
} }
@ -857,7 +858,7 @@ class StockApiController extends BaseApiController
{ {
try try
{ {
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']); $args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
if (Grocycode::Validate($args['barcode'])) if (Grocycode::Validate($args['barcode']))
{ {
@ -880,11 +881,11 @@ class StockApiController extends BaseApiController
public function UndoBooking(Request $request, Response $response, array $args) public function UndoBooking(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_EDIT); User::CheckPermission($request, User::PERMISSION_STOCK_EDIT);
try try
{ {
$this->ApiResponse($response, $this->getStockService()->UndoBooking($args['bookingId'])); $this->ApiResponse($response, StockService::GetInstance()->UndoBooking($args['bookingId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -895,11 +896,11 @@ class StockApiController extends BaseApiController
public function UndoTransaction(Request $request, Response $response, array $args) public function UndoTransaction(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_EDIT); User::CheckPermission($request, User::PERMISSION_STOCK_EDIT);
try try
{ {
$this->ApiResponse($response, $this->getStockService()->UndoTransaction($args['transactionId'])); $this->ApiResponse($response, StockService::GetInstance()->UndoTransaction($args['transactionId']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -910,7 +911,7 @@ class StockApiController extends BaseApiController
public function MergeProducts(Request $request, Response $response, array $args) public function MergeProducts(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_STOCK_EDIT); User::CheckPermission($request, User::PERMISSION_STOCK_EDIT);
try try
{ {
@ -919,7 +920,7 @@ class StockApiController extends BaseApiController
throw new \Exception('Provided {productIdToKeep} or {productIdToRemove} is not a valid integer'); throw new \Exception('Provided {productIdToKeep} or {productIdToRemove} is not a valid integer');
} }
$this->ApiResponse($response, $this->getStockService()->MergeProducts($args['productIdToKeep'], $args['productIdToRemove'])); $this->ApiResponse($response, StockService::GetInstance()->MergeProducts($args['productIdToKeep'], $args['productIdToRemove']));
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@ -1,7 +1,10 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Services\ApplicationService;
use Grocy\Services\DatabaseService;
use Grocy\Services\LocalizationService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -37,13 +40,13 @@ class SystemApiController extends BaseApiController
public function GetDbChangedTime(Request $request, Response $response, array $args) public function GetDbChangedTime(Request $request, Response $response, array $args)
{ {
return $this->ApiResponse($response, [ return $this->ApiResponse($response, [
'changed_time' => $this->getDatabaseService()->GetDbChangedTime() 'changed_time' => DatabaseService::GetInstance()->GetDbChangedTime()
]); ]);
} }
public function GetSystemInfo(Request $request, Response $response, array $args) public function GetSystemInfo(Request $request, Response $response, array $args)
{ {
return $this->ApiResponse($response, $this->getApplicationService()->GetSystemInfo()); return $this->ApiResponse($response, ApplicationService::GetInstance()->GetSystemInfo());
} }
public function GetSystemTime(Request $request, Response $response, array $args) public function GetSystemTime(Request $request, Response $response, array $args)
@ -62,7 +65,7 @@ class SystemApiController extends BaseApiController
$offset = $params['offset']; $offset = $params['offset'];
} }
return $this->ApiResponse($response, $this->getApplicationService()->GetSystemTime($offset)); return $this->ApiResponse($response, ApplicationService::GetInstance()->GetSystemTime($offset));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -78,7 +81,7 @@ class SystemApiController extends BaseApiController
{ {
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
$this->getLocalizationService()->CheckAndAddMissingTranslationToPot($requestBody['text']); LocalizationService::GetInstance()->CheckAndAddMissingTranslationToPot($requestBody['text']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -90,6 +93,6 @@ class SystemApiController extends BaseApiController
public function GetLocalizationStrings(Request $request, Response $response, array $args) public function GetLocalizationStrings(Request $request, Response $response, array $args)
{ {
return $this->ApiResponse($response, json_decode($this->getLocalizationService()->GetPoAsJsonString()), true); return $this->ApiResponse($response, json_decode(LocalizationService::GetInstance()->GetPoAsJsonString()), true);
} }
} }

View File

@ -1,8 +1,9 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\TasksService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -10,12 +11,12 @@ class TasksApiController extends BaseApiController
{ {
public function Current(Request $request, Response $response, array $args) public function Current(Request $request, Response $response, array $args)
{ {
return $this->FilteredApiResponse($response, $this->getTasksService()->GetCurrent(), $request->getQueryParams()); return $this->FilteredApiResponse($response, TasksService::GetInstance()->GetCurrent(), $request->getQueryParams());
} }
public function MarkTaskAsCompleted(Request $request, Response $response, array $args) public function MarkTaskAsCompleted(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_TASKS_MARK_COMPLETED); User::CheckPermission($request, User::PERMISSION_TASKS_MARK_COMPLETED);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -28,7 +29,7 @@ class TasksApiController extends BaseApiController
$doneTime = $requestBody['done_time']; $doneTime = $requestBody['done_time'];
} }
$this->getTasksService()->MarkTaskAsCompleted($args['taskId'], $doneTime); TasksService::GetInstance()->MarkTaskAsCompleted($args['taskId'], $doneTime);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -39,11 +40,11 @@ class TasksApiController extends BaseApiController
public function UndoTask(Request $request, Response $response, array $args) public function UndoTask(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_TASKS_UNDO_EXECUTION); User::CheckPermission($request, User::PERMISSION_TASKS_UNDO_EXECUTION);
try try
{ {
$this->getTasksService()->UndoTask($args['taskId']); TasksService::GetInstance()->UndoTask($args['taskId']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@ -1,8 +1,9 @@
<?php <?php
namespace Grocy\Controllers; namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\UsersService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -12,10 +13,10 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
User::checkPermission($request, User::PERMISSION_ADMIN); User::CheckPermission($request, User::PERMISSION_ADMIN);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
$this->getDatabase()->user_permissions()->createRow([ $this->DB->user_permissions()->createRow([
'user_id' => $args['userId'], 'user_id' => $args['userId'],
'permission_id' => $requestBody['permission_id'] 'permission_id' => $requestBody['permission_id']
])->save(); ])->save();
@ -33,7 +34,7 @@ class UsersApiController extends BaseApiController
public function CreateUser(Request $request, Response $response, array $args) public function CreateUser(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_USERS_CREATE); User::CheckPermission($request, User::PERMISSION_USERS_CREATE);
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
try try
@ -49,7 +50,7 @@ class UsersApiController extends BaseApiController
} }
unset($requestBody['password_base64']); unset($requestBody['password_base64']);
$this->getUsersService()->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password'], $requestBody['picture_file_name']); UsersService::GetInstance()->CreateUser($requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password'], $requestBody['picture_file_name']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -60,10 +61,10 @@ class UsersApiController extends BaseApiController
public function DeleteUser(Request $request, Response $response, array $args) public function DeleteUser(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_USERS_EDIT); User::CheckPermission($request, User::PERMISSION_USERS_EDIT);
try try
{ {
$this->getUsersService()->DeleteUser($args['userId']); UsersService::GetInstance()->DeleteUser($args['userId']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -76,11 +77,11 @@ class UsersApiController extends BaseApiController
{ {
if ($args['userId'] == GROCY_USER_ID) if ($args['userId'] == GROCY_USER_ID)
{ {
User::checkPermission($request, User::PERMISSION_USERS_EDIT_SELF); User::CheckPermission($request, User::PERMISSION_USERS_EDIT_SELF);
} }
else else
{ {
User::checkPermission($request, User::PERMISSION_USERS_EDIT); User::CheckPermission($request, User::PERMISSION_USERS_EDIT);
} }
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -93,7 +94,7 @@ class UsersApiController extends BaseApiController
} }
unset($requestBody['password_base64']); unset($requestBody['password_base64']);
$this->getUsersService()->EditUser($args['userId'], $requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password'], $requestBody['picture_file_name']); UsersService::GetInstance()->EditUser($args['userId'], $requestBody['username'], $requestBody['first_name'], $requestBody['last_name'], $requestBody['password'], $requestBody['picture_file_name']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -106,7 +107,7 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
$value = $this->getUsersService()->GetUserSetting(GROCY_USER_ID, $args['settingKey']); $value = UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, $args['settingKey']);
return $this->ApiResponse($response, ['value' => $value]); return $this->ApiResponse($response, ['value' => $value]);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -119,7 +120,7 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->getUsersService()->GetUserSettings(GROCY_USER_ID)); return $this->ApiResponse($response, UsersService::GetInstance()->GetUserSettings(GROCY_USER_ID));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -129,10 +130,10 @@ class UsersApiController extends BaseApiController
public function GetUsers(Request $request, Response $response, array $args) public function GetUsers(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_USERS_READ); User::CheckPermission($request, User::PERMISSION_USERS_READ);
try try
{ {
return $this->FilteredApiResponse($response, $this->getUsersService()->GetUsersAsDto(), $request->getQueryParams()); return $this->FilteredApiResponse($response, UsersService::GetInstance()->GetUsersAsDto(), $request->getQueryParams());
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -144,7 +145,7 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
return $this->ApiResponse($response, $this->getUsersService()->GetUsersAsDto()->where('id', GROCY_USER_ID)); return $this->ApiResponse($response, UsersService::GetInstance()->GetUsersAsDto()->where('id', GROCY_USER_ID));
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -156,11 +157,11 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
User::checkPermission($request, User::PERMISSION_ADMIN); User::CheckPermission($request, User::PERMISSION_ADMIN);
return $this->ApiResponse( return $this->ApiResponse(
$response, $response,
$this->getDatabase()->user_permissions()->where('user_id', $args['userId']) $this->DB->user_permissions()->where('user_id', $args['userId'])
); );
} }
catch (\Slim\Exception\HttpSpecializedException $ex) catch (\Slim\Exception\HttpSpecializedException $ex)
@ -177,10 +178,10 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
User::checkPermission($request, User::PERMISSION_ADMIN); User::CheckPermission($request, User::PERMISSION_ADMIN);
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
$db = $this->getDatabase(); $db = $this->DB;
$db->user_permissions() $db->user_permissions()
->where('user_id', $args['userId']) ->where('user_id', $args['userId'])
->delete(); ->delete();
@ -224,7 +225,7 @@ class UsersApiController extends BaseApiController
{ {
$requestBody = $this->GetParsedAndFilteredRequestBody($request); $requestBody = $this->GetParsedAndFilteredRequestBody($request);
$value = $this->getUsersService()->SetUserSetting(GROCY_USER_ID, $args['settingKey'], $requestBody['value']); $value = UsersService::GetInstance()->SetUserSetting(GROCY_USER_ID, $args['settingKey'], $requestBody['value']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)
@ -237,7 +238,7 @@ class UsersApiController extends BaseApiController
{ {
try try
{ {
$value = $this->getUsersService()->DeleteUserSetting(GROCY_USER_ID, $args['settingKey']); $value = UsersService::GetInstance()->DeleteUserSetting(GROCY_USER_ID, $args['settingKey']);
return $this->EmptyApiResponse($response); return $this->EmptyApiResponse($response);
} }
catch (\Exception $ex) catch (\Exception $ex)

View File

@ -3,20 +3,9 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\ApiKeyService;
use Grocy\Services\ApplicationService; use Grocy\Services\ApplicationService;
use Grocy\Services\BatteriesService;
use Grocy\Services\CalendarService;
use Grocy\Services\ChoresService;
use Grocy\Services\DatabaseService; use Grocy\Services\DatabaseService;
use Grocy\Services\FilesService;
use Grocy\Services\LocalizationService; use Grocy\Services\LocalizationService;
use Grocy\Services\PrintService;
use Grocy\Services\RecipesService;
use Grocy\Services\SessionService;
use Grocy\Services\StockService;
use Grocy\Services\TasksService;
use Grocy\Services\UserfieldsService;
use Grocy\Services\UsersService; use Grocy\Services\UsersService;
use DI\Container; use DI\Container;
@ -26,104 +15,21 @@ class BaseController
{ {
$this->AppContainer = $container; $this->AppContainer = $container;
$this->View = $container->get('view'); $this->View = $container->get('view');
$this->DB = DatabaseService::GetInstance()->GetDbConnection();
} }
protected $AppContainer; protected $AppContainer;
protected $View; protected $View;
protected $DB;
protected function getApiKeyService() protected function Render($response, $viewName, $data = [])
{
return ApiKeyService::getInstance();
}
protected function getApplicationservice()
{
return ApplicationService::getInstance();
}
protected function getBatteriesService()
{
return BatteriesService::getInstance();
}
protected function getCalendarService()
{
return CalendarService::getInstance();
}
protected function getChoresService()
{
return ChoresService::getInstance();
}
protected function getDatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getFilesService()
{
return FilesService::getInstance();
}
protected function getLocalizationService()
{
if (!defined('GROCY_LOCALE'))
{
define('GROCY_LOCALE', GROCY_DEFAULT_LOCALE);
}
return LocalizationService::getInstance(GROCY_LOCALE);
}
protected function getRecipesService()
{
return RecipesService::getInstance();
}
protected function getSessionService()
{
return SessionService::getInstance();
}
protected function getStockService()
{
return StockService::getInstance();
}
protected function getPrintService()
{
return PrintService::getInstance();
}
protected function getTasksService()
{
return TasksService::getInstance();
}
protected function getUserfieldsService()
{
return UserfieldsService::getInstance();
}
protected function getUsersService()
{
return UsersService::getInstance();
}
protected function render($response, $viewName, $data = [])
{ {
$container = $this->AppContainer; $container = $this->AppContainer;
$versionInfo = $this->getApplicationService()->GetInstalledVersion(); $versionInfo = ApplicationService::GetInstance()->GetInstalledVersion();
$this->View->set('version', $versionInfo->Version); $this->View->set('version', $versionInfo->Version);
$localizationService = $this->getLocalizationService(); $localizationService = LocalizationService::GetInstance();
$this->View->set('__t', function (string $text, ...$placeholderValues) use ($localizationService) $this->View->set('__t', function (string $text, ...$placeholderValues) use ($localizationService)
{ {
return $localizationService->__t($text, $placeholderValues); return $localizationService->__t($text, $placeholderValues);
@ -169,7 +75,7 @@ class BaseController
{ {
$this->View->set('permissions', User::PermissionList()); $this->View->set('permissions', User::PermissionList());
$decimalPlacesAmounts = $this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'stock_decimal_places_amounts'); $decimalPlacesAmounts = UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'stock_decimal_places_amounts');
if ($decimalPlacesAmounts <= 0) if ($decimalPlacesAmounts <= 0)
{ {
$defaultMinAmount = 1; $defaultMinAmount = 1;
@ -183,15 +89,15 @@ class BaseController
$this->View->set('viewName', $viewName); $this->View->set('viewName', $viewName);
return $this->View->render($response, $viewName, $data); return $this->View->Render($response, $viewName, $data);
} }
protected function renderPage($response, $viewName, $data = []) protected function RenderPage($response, $viewName, $data = [])
{ {
$this->View->set('userentitiesForSidebar', $this->getDatabase()->userentities()->where('show_in_sidebar_menu = 1')->orderBy('name')); $this->View->set('userentitiesForSidebar', $this->DB->userentities()->where('show_in_sidebar_menu = 1')->orderBy('name'));
try try
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
if (defined('GROCY_USER_ID')) if (defined('GROCY_USER_ID'))
{ {
$this->View->set('userSettings', $usersService->GetUserSettings(GROCY_USER_ID)); $this->View->set('userSettings', $usersService->GetUserSettings(GROCY_USER_ID));
@ -206,6 +112,6 @@ class BaseController
// Happens when database is not initialised or migrated... // Happens when database is not initialised or migrated...
} }
return $this->render($response, $viewName, $data); return $this->Render($response, $viewName, $data);
} }
} }

View File

@ -3,6 +3,9 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
use Grocy\Services\BatteriesService;
use Grocy\Services\UsersService;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -14,40 +17,40 @@ class BatteriesController extends BaseController
{ {
if (isset($request->getQueryParams()['include_disabled'])) if (isset($request->getQueryParams()['include_disabled']))
{ {
$batteries = $this->getDatabase()->batteries()->orderBy('name', 'COLLATE NOCASE'); $batteries = $this->DB->batteries()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$batteries = $this->getDatabase()->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $batteries = $this->DB->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
} }
return $this->renderPage($response, 'batteries', [ return $this->RenderPage($response, 'batteries', [
'batteries' => $batteries, 'batteries' => $batteries,
'userfields' => $this->getUserfieldsService()->GetFields('batteries'), 'userfields' => UserfieldsService::GetInstance()->GetFields('batteries'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('batteries')
]); ]);
} }
public function BatteriesSettings(Request $request, Response $response, array $args) public function BatteriesSettings(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'batteriessettings'); return $this->RenderPage($response, 'batteriessettings');
} }
public function BatteryEditForm(Request $request, Response $response, array $args) public function BatteryEditForm(Request $request, Response $response, array $args)
{ {
if ($args['batteryId'] == 'new') if ($args['batteryId'] == 'new')
{ {
return $this->renderPage($response, 'batteryform', [ return $this->RenderPage($response, 'batteryform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('batteries') 'userfields' => UserfieldsService::GetInstance()->GetFields('batteries')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'batteryform', [ return $this->RenderPage($response, 'batteryform', [
'battery' => $this->getDatabase()->batteries($args['batteryId']), 'battery' => $this->DB->batteries($args['batteryId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('batteries') 'userfields' => UserfieldsService::GetInstance()->GetFields('batteries')
]); ]);
} }
} }
@ -71,21 +74,21 @@ class BatteriesController extends BaseController
$where .= " AND battery_id = $batteryId"; $where .= " AND battery_id = $batteryId";
} }
return $this->renderPage($response, 'batteriesjournal', [ return $this->RenderPage($response, 'batteriesjournal', [
'chargeCycles' => $this->getDatabase()->battery_charge_cycles()->where($where)->orderBy('tracked_time', 'DESC'), 'chargeCycles' => $this->DB->battery_charge_cycles()->where($where)->orderBy('tracked_time', 'DESC'),
'batteries' => $this->getDatabase()->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'batteries' => $this->DB->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('battery_charge_cycles'), 'userfields' => UserfieldsService::GetInstance()->GetFields('battery_charge_cycles'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('battery_charge_cycles') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('battery_charge_cycles')
]); ]);
} }
public function Overview(Request $request, Response $response, array $args) public function Overview(Request $request, Response $response, array $args)
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['batteries_due_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['batteries_due_soon_days'];
$batteries = $this->getDatabase()->batteries()->where('active = 1'); $batteries = $this->DB->batteries()->where('active = 1');
$currentBatteries = $this->getBatteriesService()->GetCurrent(); $currentBatteries = BatteriesService::GetInstance()->GetCurrent();
foreach ($currentBatteries as $currentBattery) foreach ($currentBatteries as $currentBattery)
{ {
if (FindObjectInArrayByPropertyValue($batteries, 'id', $currentBattery->battery_id)->charge_interval_days > 0) if (FindObjectInArrayByPropertyValue($batteries, 'id', $currentBattery->battery_id)->charge_interval_days > 0)
@ -105,20 +108,20 @@ class BatteriesController extends BaseController
} }
} }
return $this->renderPage($response, 'batteriesoverview', [ return $this->RenderPage($response, 'batteriesoverview', [
'batteries' => $batteries, 'batteries' => $batteries,
'current' => $currentBatteries, 'current' => $currentBatteries,
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'userfields' => $this->getUserfieldsService()->GetFields('batteries'), 'userfields' => UserfieldsService::GetInstance()->GetFields('batteries'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('batteries')
]); ]);
} }
public function TrackChargeCycle(Request $request, Response $response, array $args) public function TrackChargeCycle(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'batterytracking', [ return $this->RenderPage($response, 'batterytracking', [
'batteries' => $this->getDatabase()->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'batteries' => $this->DB->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('battery_charge_cycles') 'userfields' => UserfieldsService::GetInstance()->GetFields('battery_charge_cycles')
]); ]);
} }

View File

@ -2,6 +2,7 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Services\CalendarService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -9,8 +10,8 @@ class CalendarController extends BaseController
{ {
public function Overview(Request $request, Response $response, array $args) public function Overview(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'calendar', [ return $this->RenderPage($response, 'calendar', [
'fullcalendarEventSources' => $this->getCalendarService()->GetEvents() 'fullcalendarEventSources' => CalendarService::GetInstance()->GetEvents()
]); ]);
} }
} }

View File

@ -3,6 +3,9 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
use Grocy\Services\ChoresService;
use Grocy\Services\UsersService;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -12,30 +15,30 @@ class ChoresController extends BaseController
public function ChoreEditForm(Request $request, Response $response, array $args) public function ChoreEditForm(Request $request, Response $response, array $args)
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
$users = $usersService->GetUsersAsDto(); $users = $usersService->GetUsersAsDto();
if ($args['choreId'] == 'new') if ($args['choreId'] == 'new')
{ {
return $this->renderPage($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->getUserfieldsService()->GetFields('chores'), 'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'), 'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'),
'users' => $users, 'users' => $users,
'products' => $this->getDatabase()->products()->orderBy('name', 'COLLATE NOCASE') 'products' => $this->DB->products()->orderBy('name', 'COLLATE NOCASE')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'choreform', [ return $this->RenderPage($response, 'choreform', [
'chore' => $this->getDatabase()->chores($args['choreId']), 'chore' => $this->DB->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->getUserfieldsService()->GetFields('chores'), 'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'), 'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'),
'users' => $users, 'users' => $users,
'products' => $this->getDatabase()->products()->orderBy('name', 'COLLATE NOCASE') 'products' => $this->DB->products()->orderBy('name', 'COLLATE NOCASE')
]); ]);
} }
} }
@ -44,23 +47,23 @@ class ChoresController extends BaseController
{ {
if (isset($request->getQueryParams()['include_disabled'])) if (isset($request->getQueryParams()['include_disabled']))
{ {
$chores = $this->getDatabase()->chores()->orderBy('name', 'COLLATE NOCASE'); $chores = $this->DB->chores()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$chores = $this->getDatabase()->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $chores = $this->DB->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
} }
return $this->renderPage($response, 'chores', [ return $this->RenderPage($response, 'chores', [
'chores' => $chores, 'chores' => $chores,
'userfields' => $this->getUserfieldsService()->GetFields('chores'), 'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('chores')
]); ]);
} }
public function ChoresSettings(Request $request, Response $response, array $args) public function ChoresSettings(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'choressettings'); return $this->RenderPage($response, 'choressettings');
} }
public function Journal(Request $request, Response $response, array $args) public function Journal(Request $request, Response $response, array $args)
@ -82,22 +85,22 @@ class ChoresController extends BaseController
$where .= " AND chore_id = $choreId"; $where .= " AND chore_id = $choreId";
} }
return $this->renderPage($response, 'choresjournal', [ return $this->RenderPage($response, 'choresjournal', [
'choresLog' => $this->getDatabase()->chores_log()->where($where)->orderBy('tracked_time', 'DESC'), 'choresLog' => $this->DB->chores_log()->where($where)->orderBy('tracked_time', 'DESC'),
'chores' => $this->getDatabase()->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'chores' => $this->DB->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'), 'users' => $this->DB->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('chores_log'), 'userfields' => UserfieldsService::GetInstance()->GetFields('chores_log'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores_log') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('chores_log')
]); ]);
} }
public function Overview(Request $request, Response $response, array $args) public function Overview(Request $request, Response $response, array $args)
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['chores_due_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['chores_due_soon_days'];
$chores = $this->getDatabase()->chores()->orderBy('name', 'COLLATE NOCASE'); $chores = $this->DB->chores()->orderBy('name', 'COLLATE NOCASE');
$currentChores = $this->getChoresService()->GetCurrent(); $currentChores = ChoresService::GetInstance()->GetCurrent();
foreach ($currentChores as $currentChore) foreach ($currentChores as $currentChore)
{ {
if (!empty($currentChore->next_estimated_execution_time)) if (!empty($currentChore->next_estimated_execution_time))
@ -117,22 +120,22 @@ class ChoresController extends BaseController
} }
} }
return $this->renderPage($response, 'choresoverview', [ return $this->RenderPage($response, 'choresoverview', [
'chores' => $chores, 'chores' => $chores,
'currentChores' => $currentChores, 'currentChores' => $currentChores,
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'userfields' => $this->getUserfieldsService()->GetFields('chores'), 'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores'), 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('chores'),
'users' => $usersService->GetUsersAsDto() 'users' => $usersService->GetUsersAsDto()
]); ]);
} }
public function TrackChoreExecution(Request $request, Response $response, array $args) public function TrackChoreExecution(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'choretracking', [ return $this->RenderPage($response, 'choretracking', [
'chores' => $this->getDatabase()->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'chores' => $this->DB->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'), 'users' => $this->DB->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('chores_log'), 'userfields' => UserfieldsService::GetInstance()->GetFields('chores_log'),
]); ]);
} }

View File

@ -2,6 +2,7 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -13,27 +14,27 @@ class EquipmentController extends BaseController
{ {
if ($args['equipmentId'] == 'new') if ($args['equipmentId'] == 'new')
{ {
return $this->renderPage($response, 'equipmentform', [ return $this->RenderPage($response, 'equipmentform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('equipment') 'userfields' => UserfieldsService::GetInstance()->GetFields('equipment')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'equipmentform', [ return $this->RenderPage($response, 'equipmentform', [
'equipment' => $this->getDatabase()->equipment($args['equipmentId']), 'equipment' => $this->DB->equipment($args['equipmentId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('equipment') 'userfields' => UserfieldsService::GetInstance()->GetFields('equipment')
]); ]);
} }
} }
public function Overview(Request $request, Response $response, array $args) public function Overview(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'equipment', [ return $this->RenderPage($response, 'equipment', [
'equipment' => $this->getDatabase()->equipment()->orderBy('name', 'COLLATE NOCASE'), 'equipment' => $this->DB->equipment()->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('equipment'), 'userfields' => UserfieldsService::GetInstance()->GetFields('equipment'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('equipment') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('equipment')
]); ]);
} }
} }

View File

@ -2,7 +2,10 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Controllers\Api\BaseApiController;
use Grocy\Services\ApplicationService;
use DI\Container; use DI\Container;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Slim\Exception\HttpException; use Slim\Exception\HttpException;
@ -12,17 +15,17 @@ use Throwable;
class ExceptionController extends BaseApiController class ExceptionController extends BaseApiController
{ {
public function __construct(\Slim\App $app, Container $container) public function __construct(Container $container, ResponseFactoryInterface $responseFactory)
{ {
parent::__construct($container); parent::__construct($container);
$this->app = $app; $this->ResponseFactory = $responseFactory;
} }
private $app; private $ResponseFactory;
public function __invoke(ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails, bool $logErrors, bool $logErrorDetails, ?LoggerInterface $logger = null) public function __invoke(ServerRequestInterface $request, Throwable $exception, bool $displayErrorDetails, bool $logErrors, bool $logErrorDetails, ?LoggerInterface $logger = null)
{ {
$response = $this->app->getResponseFactory()->createResponse(); $response = $this->ResponseFactory->createResponse();
$isApiRoute = string_starts_with($request->getUri()->getPath(), '/api/'); $isApiRoute = string_starts_with($request->getUri()->getPath(), '/api/');
if (!defined('GROCY_AUTHENTICATED')) if (!defined('GROCY_AUTHENTICATED'))
@ -33,7 +36,6 @@ class ExceptionController extends BaseApiController
if ($isApiRoute) if ($isApiRoute)
{ {
$status = 500; $status = 500;
if ($exception instanceof HttpException) if ($exception instanceof HttpException)
{ {
$status = $exception->getCode(); $status = $exception->getCode();
@ -62,21 +64,21 @@ class ExceptionController extends BaseApiController
define('GROCY_AUTHENTICATED', false); define('GROCY_AUTHENTICATED', false);
} }
return $this->renderPage($response->withStatus(404), 'errors/404', [ return $this->RenderPage($response->withStatus(404), 'errors/404', [
'exception' => $exception 'exception' => $exception
]); ]);
} }
if ($exception instanceof HttpForbiddenException) if ($exception instanceof HttpForbiddenException)
{ {
return $this->renderPage($response->withStatus(403), 'errors/403', [ return $this->RenderPage($response->withStatus(403), 'errors/403', [
'exception' => $exception 'exception' => $exception
]); ]);
} }
return $this->renderPage($response->withStatus(500), 'errors/500', [ return $this->RenderPage($response->withStatus(500), 'errors/500', [
'exception' => $exception, 'exception' => $exception,
'systemInfo' => $this->getApplicationService()->GetSystemInfo() 'systemInfo' => ApplicationService::GetInstance()->GetSystemInfo()
]); ]);
} }
} }

View File

@ -2,6 +2,7 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -9,8 +10,8 @@ class GenericEntityController extends BaseController
{ {
public function UserentitiesList(Request $request, Response $response, array $args) public function UserentitiesList(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'userentities', [ return $this->RenderPage($response, 'userentities', [
'userentities' => $this->getDatabase()->userentities()->orderBy('name', 'COLLATE NOCASE') 'userentities' => $this->DB->userentities()->orderBy('name', 'COLLATE NOCASE')
]); ]);
} }
@ -18,15 +19,15 @@ class GenericEntityController extends BaseController
{ {
if ($args['userentityId'] == 'new') if ($args['userentityId'] == 'new')
{ {
return $this->renderPage($response, 'userentityform', [ return $this->RenderPage($response, 'userentityform', [
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'userentityform', [ return $this->RenderPage($response, 'userentityform', [
'mode' => 'edit', 'mode' => 'edit',
'userentity' => $this->getDatabase()->userentities($args['userentityId']) 'userentity' => $this->DB->userentities($args['userentityId'])
]); ]);
} }
} }
@ -35,63 +36,63 @@ class GenericEntityController extends BaseController
{ {
if ($args['userfieldId'] == 'new') if ($args['userfieldId'] == 'new')
{ {
return $this->renderPage($response, 'userfieldform', [ return $this->RenderPage($response, 'userfieldform', [
'mode' => 'create', 'mode' => 'create',
'userfieldTypes' => $this->getUserfieldsService()->GetFieldTypes(), 'userfieldTypes' => UserfieldsService::GetInstance()->GetFieldTypes(),
'entities' => $this->getUserfieldsService()->GetEntities() 'entities' => UserfieldsService::GetInstance()->GetEntities()
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'userfieldform', [ return $this->RenderPage($response, 'userfieldform', [
'mode' => 'edit', 'mode' => 'edit',
'userfield' => $this->getUserfieldsService()->GetField($args['userfieldId']), 'userfield' => UserfieldsService::GetInstance()->GetField($args['userfieldId']),
'userfieldTypes' => $this->getUserfieldsService()->GetFieldTypes(), 'userfieldTypes' => UserfieldsService::GetInstance()->GetFieldTypes(),
'entities' => $this->getUserfieldsService()->GetEntities() 'entities' => UserfieldsService::GetInstance()->GetEntities()
]); ]);
} }
} }
public function UserfieldsList(Request $request, Response $response, array $args) public function UserfieldsList(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'userfields', [ return $this->RenderPage($response, 'userfields', [
'userfields' => $this->getUserfieldsService()->GetAllFields(), 'userfields' => UserfieldsService::GetInstance()->GetAllFields(),
'entities' => $this->getUserfieldsService()->GetEntities() 'entities' => UserfieldsService::GetInstance()->GetEntities()
]); ]);
} }
public function UserobjectEditForm(Request $request, Response $response, array $args) public function UserobjectEditForm(Request $request, Response $response, array $args)
{ {
$userentity = $this->getDatabase()->userentities()->where('name = :1', $args['userentityName'])->fetch(); $userentity = $this->DB->userentities()->where('name = :1', $args['userentityName'])->fetch();
if ($args['userobjectId'] == 'new') if ($args['userobjectId'] == 'new')
{ {
return $this->renderPage($response, 'userobjectform', [ return $this->RenderPage($response, 'userobjectform', [
'userentity' => $userentity, 'userentity' => $userentity,
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']) 'userfields' => UserfieldsService::GetInstance()->GetFields('userentity-' . $args['userentityName'])
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'userobjectform', [ return $this->RenderPage($response, 'userobjectform', [
'userentity' => $userentity, 'userentity' => $userentity,
'mode' => 'edit', 'mode' => 'edit',
'userobject' => $this->getDatabase()->userobjects($args['userobjectId']), 'userobject' => $this->DB->userobjects($args['userobjectId']),
'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']) 'userfields' => UserfieldsService::GetInstance()->GetFields('userentity-' . $args['userentityName'])
]); ]);
} }
} }
public function UserobjectsList(Request $request, Response $response, array $args) public function UserobjectsList(Request $request, Response $response, array $args)
{ {
$userentity = $this->getDatabase()->userentities()->where('name = :1', $args['userentityName'])->fetch(); $userentity = $this->DB->userentities()->where('name = :1', $args['userentityName'])->fetch();
return $this->renderPage($response, 'userobjects', [ return $this->RenderPage($response, 'userobjects', [
'userentity' => $userentity, 'userentity' => $userentity,
'userobjects' => $this->getDatabase()->userobjects()->where('userentity_id = :1', $userentity->id), 'userobjects' => $this->DB->userobjects()->where('userentity_id = :1', $userentity->id),
'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']), 'userfields' => UserfieldsService::GetInstance()->GetFields('userentity-' . $args['userentityName']),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('userentity-' . $args['userentityName']) 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('userentity-' . $args['userentityName'])
]); ]);
} }
} }

View File

@ -10,12 +10,12 @@ class LoginController extends BaseController
{ {
public function LoginPage(Request $request, Response $response, array $args) public function LoginPage(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'login'); return $this->RenderPage($response, 'login');
} }
public function Logout(Request $request, Response $response, array $args) public function Logout(Request $request, Response $response, array $args)
{ {
$this->getSessionService()->RemoveSession($_COOKIE[SessionService::SESSION_COOKIE_NAME]); SessionService::GetInstance()->RemoveSession($_COOKIE[SessionService::SESSION_COOKIE_NAME]);
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/')); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/'));
} }

View File

@ -3,6 +3,8 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Services\RecipesService; use Grocy\Services\RecipesService;
use Grocy\Services\StockService;
use Grocy\Services\UserfieldsService;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -27,9 +29,9 @@ class RecipesController extends BaseController
$mealPlanWhereTimespan = "day BETWEEN DATE('$start', '-$days days') AND DATE('$start', '+$days days')"; $mealPlanWhereTimespan = "day BETWEEN DATE('$start', '-$days days') AND DATE('$start', '+$days days')";
$recipes = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll(); $recipes = $this->DB->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->fetchAll();
$events = []; $events = [];
foreach ($this->getDatabase()->meal_plan()->where($mealPlanWhereTimespan) as $mealPlanEntry) foreach ($this->DB->meal_plan()->where($mealPlanWhereTimespan) as $mealPlanEntry)
{ {
$recipe = FindObjectInArrayByPropertyValue($recipes, 'id', $mealPlanEntry['recipe_id']); $recipe = FindObjectInArrayByPropertyValue($recipes, 'id', $mealPlanEntry['recipe_id']);
$title = ''; $title = '';
@ -42,7 +44,7 @@ class RecipesController extends BaseController
$productDetails = null; $productDetails = null;
if ($mealPlanEntry['product_id'] !== null) if ($mealPlanEntry['product_id'] !== null)
{ {
$productDetails = $this->getStockService()->GetProductDetails($mealPlanEntry['product_id']); $productDetails = StockService::GetInstance()->GetProductDetails($mealPlanEntry['product_id']);
} }
$events[] = [ $events[] = [
@ -57,36 +59,36 @@ class RecipesController extends BaseController
]; ];
} }
$weekRecipe = $this->getDatabase()->recipes()->where("type = 'mealplan-week' AND name = LTRIM(STRFTIME('%Y-%W', DATE('$start')), '0')")->fetch(); $weekRecipe = $this->DB->recipes()->where("type = 'mealplan-week' AND name = LTRIM(STRFTIME('%Y-%W', DATE('$start')), '0')")->fetch();
$weekRecipeId = 0; $weekRecipeId = 0;
if ($weekRecipe != null) if ($weekRecipe != null)
{ {
$weekRecipeId = $weekRecipe->id; $weekRecipeId = $weekRecipe->id;
} }
return $this->renderPage($response, 'mealplan', [ return $this->RenderPage($response, 'mealplan', [
'fullcalendarEventSources' => $events, 'fullcalendarEventSources' => $events,
'recipes' => $recipes, 'recipes' => $recipes,
'internalRecipes' => $this->getDatabase()->recipes()->where("id IN (SELECT recipe_id FROM meal_plan_internal_recipe_relation WHERE $mealPlanWhereTimespan) OR id = $weekRecipeId")->fetchAll(), 'internalRecipes' => $this->DB->recipes()->where("id IN (SELECT recipe_id FROM meal_plan_internal_recipe_relation WHERE $mealPlanWhereTimespan) OR id = $weekRecipeId")->fetchAll(),
'recipesResolved' => $this->getRecipesService()->GetRecipesResolved("recipe_id IN (SELECT recipe_id FROM meal_plan_internal_recipe_relation WHERE $mealPlanWhereTimespan) OR recipe_id = $weekRecipeId"), 'recipesResolved' => RecipesService::GetInstance()->GetRecipesResolved("recipe_id IN (SELECT recipe_id FROM meal_plan_internal_recipe_relation WHERE $mealPlanWhereTimespan) OR recipe_id = $weekRecipeId"),
'products' => $this->getDatabase()->products()->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'mealplanSections' => $this->getDatabase()->meal_plan_sections()->orderBy('sort_number'), 'mealplanSections' => $this->DB->meal_plan_sections()->orderBy('sort_number'),
'usedMealplanSections' => $this->getDatabase()->meal_plan_sections()->where("id IN (SELECT section_id FROM meal_plan WHERE $mealPlanWhereTimespan)")->orderBy('sort_number'), 'usedMealplanSections' => $this->DB->meal_plan_sections()->where("id IN (SELECT section_id FROM meal_plan WHERE $mealPlanWhereTimespan)")->orderBy('sort_number'),
'weekRecipe' => $weekRecipe 'weekRecipe' => $weekRecipe
]); ]);
} }
public function Overview(Request $request, Response $response, array $args) public function Overview(Request $request, Response $response, array $args)
{ {
$recipes = $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name', 'COLLATE NOCASE'); $recipes = $this->DB->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name', 'COLLATE NOCASE');
$recipesResolved = $this->getRecipesService()->GetRecipesResolved('recipe_id > 0'); $recipesResolved = RecipesService::GetInstance()->GetRecipesResolved('recipe_id > 0');
$selectedRecipe = null; $selectedRecipe = null;
if (isset($request->getQueryParams()['recipe'])) if (isset($request->getQueryParams()['recipe']))
{ {
$selectedRecipe = $this->getDatabase()->recipes($request->getQueryParams()['recipe']); $selectedRecipe = $this->DB->recipes($request->getQueryParams()['recipe']);
} }
else else
{ {
@ -108,21 +110,21 @@ class RecipesController extends BaseController
$viewData = [ $viewData = [
'recipes' => $recipes, 'recipes' => $recipes,
'recipesResolved' => $recipesResolved, 'recipesResolved' => $recipesResolved,
'recipePositionsResolved' => $this->getDatabase()->recipes_pos_resolved()->where('recipe_id', $selectedRecipe->id), 'recipePositionsResolved' => $this->DB->recipes_pos_resolved()->where('recipe_id', $selectedRecipe->id),
'selectedRecipe' => $selectedRecipe, 'selectedRecipe' => $selectedRecipe,
'products' => $this->getDatabase()->products(), 'products' => $this->DB->products(),
'quantityUnits' => $this->getDatabase()->quantity_units(), 'quantityUnits' => $this->DB->quantity_units(),
'userfields' => $this->getUserfieldsService()->GetFields('recipes'), 'userfields' => UserfieldsService::GetInstance()->GetFields('recipes'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('recipes'), 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('recipes'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'selectedRecipeTotalCosts' => $totalCosts, 'selectedRecipeTotalCosts' => $totalCosts,
'selectedRecipeTotalCalories' => $totalCalories, 'selectedRecipeTotalCalories' => $totalCalories,
'mealplanSections' => $this->getDatabase()->meal_plan_sections()->orderBy('sort_number') 'mealplanSections' => $this->DB->meal_plan_sections()->orderBy('sort_number')
]; ];
if ($selectedRecipe) if ($selectedRecipe)
{ {
$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', 'COLLATE NOCASE')->fetchAll(); $selectedRecipeSubRecipes = $this->DB->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', 'COLLATE NOCASE')->fetchAll();
$includedRecipeIdsAbsolute = []; $includedRecipeIdsAbsolute = [];
$includedRecipeIdsAbsolute[] = $selectedRecipe->id; $includedRecipeIdsAbsolute[] = $selectedRecipe->id;
@ -136,12 +138,12 @@ class RecipesController extends BaseController
$allRecipePositions = []; $allRecipePositions = [];
foreach ($includedRecipeIdsAbsolute as $id) foreach ($includedRecipeIdsAbsolute as $id)
{ {
$allRecipePositions[$id] = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); $allRecipePositions[$id] = $this->DB->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC');
foreach ($allRecipePositions[$id] as $pos) foreach ($allRecipePositions[$id] as $pos)
{ {
if ($id != $selectedRecipe->id) if ($id != $selectedRecipe->id)
{ {
$pos2 = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND recipe_pos_id = :2 AND is_nested_recipe_pos = 1', $selectedRecipe->id, $pos->recipe_pos_id)->fetch(); $pos2 = $this->DB->recipes_pos_resolved()->where('recipe_id = :1 AND recipe_pos_id = :2 AND is_nested_recipe_pos = 1', $selectedRecipe->id, $pos->recipe_pos_id)->fetch();
$pos->recipe_amount = $pos2->recipe_amount; $pos->recipe_amount = $pos2->recipe_amount;
$pos->missing_amount = $pos2->missing_amount; $pos->missing_amount = $pos2->missing_amount;
} }
@ -153,23 +155,23 @@ class RecipesController extends BaseController
$viewData['allRecipePositions'] = $allRecipePositions; $viewData['allRecipePositions'] = $allRecipePositions;
} }
return $this->renderPage($response, 'recipes', $viewData); return $this->RenderPage($response, 'recipes', $viewData);
} }
public function RecipeEditForm(Request $request, Response $response, array $args) public function RecipeEditForm(Request $request, Response $response, array $args)
{ {
$recipeId = $args['recipeId']; $recipeId = $args['recipeId'];
return $this->renderPage($response, 'recipeform', [ return $this->RenderPage($response, 'recipeform', [
'recipe' => $this->getDatabase()->recipes($recipeId), 'recipe' => $this->DB->recipes($recipeId),
'recipePositions' => $this->getDatabase()->recipes_pos()->where('recipe_id', $recipeId), 'recipePositions' => $this->DB->recipes_pos()->where('recipe_id', $recipeId),
'mode' => $recipeId == 'new' ? 'create' : 'edit', 'mode' => $recipeId == 'new' ? 'create' : 'edit',
'products' => $this->getDatabase()->products()->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->orderBy('name', 'COLLATE NOCASE'),
'quantityunits' => $this->getDatabase()->quantity_units(), 'quantityunits' => $this->DB->quantity_units(),
'recipes' => $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name', 'COLLATE NOCASE'), 'recipes' => $this->DB->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name', 'COLLATE NOCASE'),
'recipeNestings' => $this->getDatabase()->recipes_nestings()->where('recipe_id', $recipeId), 'recipeNestings' => $this->DB->recipes_nestings()->where('recipe_id', $recipeId),
'userfields' => $this->getUserfieldsService()->GetFields('recipes'), 'userfields' => UserfieldsService::GetInstance()->GetFields('recipes'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved()
]); ]);
} }
@ -177,47 +179,47 @@ class RecipesController extends BaseController
{ {
if ($args['recipePosId'] == 'new') if ($args['recipePosId'] == 'new')
{ {
return $this->renderPage($response, 'recipeposform', [ return $this->RenderPage($response, 'recipeposform', [
'mode' => 'create', 'mode' => 'create',
'recipe' => $this->getDatabase()->recipes($args['recipeId']), 'recipe' => $this->DB->recipes($args['recipeId']),
'recipePos' => new \stdClass(), 'recipePos' => new \stdClass(),
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved()
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'recipeposform', [ return $this->RenderPage($response, 'recipeposform', [
'mode' => 'edit', 'mode' => 'edit',
'recipe' => $this->getDatabase()->recipes($args['recipeId']), 'recipe' => $this->DB->recipes($args['recipeId']),
'recipePos' => $this->getDatabase()->recipes_pos($args['recipePosId']), 'recipePos' => $this->DB->recipes_pos($args['recipePosId']),
'products' => $this->getDatabase()->products()->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved()
]); ]);
} }
} }
public function RecipesSettings(Request $request, Response $response, array $args) public function RecipesSettings(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'recipessettings'); return $this->RenderPage($response, 'recipessettings');
} }
public function MealPlanSectionEditForm(Request $request, Response $response, array $args) public function MealPlanSectionEditForm(Request $request, Response $response, array $args)
{ {
if ($args['sectionId'] == 'new') if ($args['sectionId'] == 'new')
{ {
return $this->renderPage($response, 'mealplansectionform', [ return $this->RenderPage($response, 'mealplansectionform', [
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'mealplansectionform', [ return $this->RenderPage($response, 'mealplansectionform', [
'mealplanSection' => $this->getDatabase()->meal_plan_sections($args['sectionId']), 'mealplanSection' => $this->DB->meal_plan_sections($args['sectionId']),
'mode' => 'edit' 'mode' => 'edit'
]); ]);
} }
@ -225,8 +227,8 @@ class RecipesController extends BaseController
public function MealPlanSectionsList(Request $request, Response $response, array $args) public function MealPlanSectionsList(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'mealplansections', [ return $this->RenderPage($response, 'mealplansections', [
'mealplanSections' => $this->getDatabase()->meal_plan_sections()->where('id > 0')->orderBy('sort_number') 'mealplanSections' => $this->DB->meal_plan_sections()->where('id > 0')->orderBy('sort_number')
]); ]);
} }

View File

@ -3,7 +3,11 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Helpers\Grocycode; use Grocy\Helpers\Grocycode;
use Grocy\Services\LocalizationService;
use Grocy\Services\RecipesService; use Grocy\Services\RecipesService;
use Grocy\Services\StockService;
use Grocy\Services\UsersService;
use Grocy\Services\UserfieldsService;
use DI\Container; use DI\Container;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -18,7 +22,7 @@ class StockController extends BaseController
try try
{ {
$externalBarcodeLookupPluginName = $this->getStockService()->GetExternalBarcodeLookupPluginName(); $externalBarcodeLookupPluginName = StockService::GetInstance()->GetExternalBarcodeLookupPluginName();
} }
catch (\Exception) catch (\Exception)
{ {
@ -32,26 +36,26 @@ class StockController extends BaseController
public function Consume(Request $request, Response $response, array $args) public function Consume(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'consume', [ return $this->RenderPage($response, 'consume', [
'products' => $this->getDatabase()->products()->where('active = 1')->where('id IN (SELECT product_id from stock_current WHERE amount_aggregated > 0)')->orderBy('name'), 'products' => $this->DB->products()->where('active = 1')->where('id IN (SELECT product_id from stock_current WHERE amount_aggregated > 0)')->orderBy('name'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'recipes' => $this->getDatabase()->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name', 'COLLATE NOCASE'), 'recipes' => $this->DB->recipes()->where('type', RecipesService::RECIPE_TYPE_NORMAL)->orderBy('name', 'COLLATE NOCASE'),
'locations' => $this->getDatabase()->locations()->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved()
]); ]);
} }
public function Inventory(Request $request, Response $response, array $args) public function Inventory(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'inventory', [ return $this->RenderPage($response, 'inventory', [
'products' => $this->getDatabase()->products()->where('active = 1 AND no_own_stock = 0')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1 AND no_own_stock = 0')->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'userfields' => $this->getUserfieldsService()->GetFields('stock') 'userfields' => UserfieldsService::GetInstance()->GetFields('stock')
]); ]);
} }
@ -74,26 +78,26 @@ class StockController extends BaseController
$where .= " AND product_id = $productId"; $where .= " AND product_id = $productId";
} }
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
return $this->renderPage($response, 'stockjournal', [ return $this->RenderPage($response, 'stockjournal', [
'stockLog' => $this->getDatabase()->uihelper_stock_journal()->where($where)->orderBy('row_created_timestamp', 'DESC'), 'stockLog' => $this->DB->uihelper_stock_journal()->where($where)->orderBy('row_created_timestamp', 'DESC'),
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'locations' => $this->getDatabase()->locations()->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->orderBy('name', 'COLLATE NOCASE'),
'users' => $usersService->GetUsersAsDto(), 'users' => $usersService->GetUsersAsDto(),
'transactionTypes' => GetClassConstants('\Grocy\Services\StockService', 'TRANSACTION_TYPE_'), 'transactionTypes' => GetClassConstants('\Grocy\Services\StockService', 'TRANSACTION_TYPE_'),
'userfieldsStock' => $this->getUserfieldsService()->GetFields('stock'), 'userfieldsStock' => UserfieldsService::GetInstance()->GetFields('stock'),
'userfieldValuesStock' => $this->getUserfieldsService()->GetAllValues('stock') 'userfieldValuesStock' => UserfieldsService::GetInstance()->GetAllValues('stock')
]); ]);
} }
public function LocationContentSheet(Request $request, Response $response, array $args) public function LocationContentSheet(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'locationcontentsheet', [ return $this->RenderPage($response, 'locationcontentsheet', [
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityunits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'locations' => $this->getDatabase()->locations()->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->orderBy('name', 'COLLATE NOCASE'),
'currentStockLocationContent' => $this->getStockService()->GetCurrentStockLocationContent(isset($request->getQueryParams()['include_out_of_stock'])) 'currentStockLocationContent' => StockService::GetInstance()->GetCurrentStockLocationContent(isset($request->getQueryParams()['include_out_of_stock']))
]); ]);
} }
@ -101,17 +105,17 @@ class StockController extends BaseController
{ {
if ($args['locationId'] == 'new') if ($args['locationId'] == 'new')
{ {
return $this->renderPage($response, 'locationform', [ return $this->RenderPage($response, 'locationform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('locations') 'userfields' => UserfieldsService::GetInstance()->GetFields('locations')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'locationform', [ return $this->RenderPage($response, 'locationform', [
'location' => $this->getDatabase()->locations($args['locationId']), 'location' => $this->DB->locations($args['locationId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('locations') 'userfields' => UserfieldsService::GetInstance()->GetFields('locations')
]); ]);
} }
} }
@ -120,23 +124,23 @@ class StockController extends BaseController
{ {
if (isset($request->getQueryParams()['include_disabled'])) if (isset($request->getQueryParams()['include_disabled']))
{ {
$locations = $this->getDatabase()->locations()->orderBy('name', 'COLLATE NOCASE'); $locations = $this->DB->locations()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$locations = $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $locations = $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
} }
return $this->renderPage($response, 'locations', [ return $this->RenderPage($response, 'locations', [
'locations' => $locations, 'locations' => $locations,
'userfields' => $this->getUserfieldsService()->GetFields('locations'), 'userfields' => UserfieldsService::GetInstance()->GetFields('locations'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('locations') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('locations')
]); ]);
} }
public function Overview(Request $request, Response $response, array $args) public function Overview(Request $request, Response $response, array $args)
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
$userSettings = $usersService->GetUserSettings(GROCY_USER_ID); $userSettings = $usersService->GetUserSettings(GROCY_USER_ID);
$nextXDays = $userSettings['stock_due_soon_days']; $nextXDays = $userSettings['stock_due_soon_days'];
@ -146,14 +150,14 @@ class StockController extends BaseController
$where = '1=1'; $where = '1=1';
} }
return $this->renderPage($response, 'stockoverview', [ return $this->RenderPage($response, 'stockoverview', [
'currentStock' => $this->getDatabase()->uihelper_stock_current_overview()->where($where), 'currentStock' => $this->DB->uihelper_stock_current_overview()->where($where),
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'currentStockLocations' => $this->getStockService()->GetCurrentStockLocations(), 'currentStockLocations' => StockService::GetInstance()->GetCurrentStockLocations(),
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'productGroups' => $this->getDatabase()->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'productGroups' => $this->DB->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('products'), 'userfields' => UserfieldsService::GetInstance()->GetFields('products'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('products')
]); ]);
} }
@ -162,31 +166,31 @@ class StockController extends BaseController
$product = null; $product = null;
if (isset($request->getQueryParams()['product'])) if (isset($request->getQueryParams()['product']))
{ {
$product = $this->getDatabase()->products($request->getQueryParams()['product']); $product = $this->DB->products($request->getQueryParams()['product']);
} }
if ($args['productBarcodeId'] == 'new') if ($args['productBarcodeId'] == 'new')
{ {
return $this->renderPage($response, 'productbarcodeform', [ return $this->RenderPage($response, 'productbarcodeform', [
'mode' => 'create', 'mode' => 'create',
'barcodes' => $this->getDatabase()->product_barcodes()->orderBy('barcode'), 'barcodes' => $this->DB->product_barcodes()->orderBy('barcode'),
'product' => $product, 'product' => $product,
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'userfields' => $this->getUserfieldsService()->GetFields('product_barcodes') 'userfields' => UserfieldsService::GetInstance()->GetFields('product_barcodes')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'productbarcodeform', [ return $this->RenderPage($response, 'productbarcodeform', [
'mode' => 'edit', 'mode' => 'edit',
'barcode' => $this->getDatabase()->product_barcodes($args['productBarcodeId']), 'barcode' => $this->DB->product_barcodes($args['productBarcodeId']),
'product' => $product, 'product' => $product,
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'userfields' => $this->getUserfieldsService()->GetFields('product_barcodes') 'userfields' => UserfieldsService::GetInstance()->GetFields('product_barcodes')
]); ]);
} }
} }
@ -195,40 +199,40 @@ class StockController extends BaseController
{ {
if ($args['productId'] == 'new') if ($args['productId'] == 'new')
{ {
$quantityunits = $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $quantityunits = $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
return $this->renderPage($response, 'productform', [ return $this->RenderPage($response, 'productform', [
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name'),
'barcodes' => $this->getDatabase()->product_barcodes()->orderBy('barcode'), 'barcodes' => $this->DB->product_barcodes()->orderBy('barcode'),
'quantityunitsAll' => $quantityunits, 'quantityunitsAll' => $quantityunits,
'quantityunitsReferenced' => $quantityunits, 'quantityunitsReferenced' => $quantityunits,
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'productgroups' => $this->getDatabase()->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'productgroups' => $this->DB->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('products'), 'userfields' => UserfieldsService::GetInstance()->GetFields('products'),
'products' => $this->getDatabase()->products()->where('parent_product_id IS NULL and active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('parent_product_id IS NULL and active = 1')->orderBy('name', 'COLLATE NOCASE'),
'isSubProductOfOthers' => false, 'isSubProductOfOthers' => false,
'mode' => 'create' 'mode' => 'create'
]); ]);
} }
else else
{ {
$product = $this->getDatabase()->products($args['productId']); $product = $this->DB->products($args['productId']);
return $this->renderPage($response, 'productform', [ return $this->RenderPage($response, 'productform', [
'product' => $product, 'product' => $product,
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes()->orderBy('barcode'), 'barcodes' => $this->DB->product_barcodes()->orderBy('barcode'),
'quantityunitsAll' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityunitsAll' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityunitsReferenced' => $this->getDatabase()->quantity_units()->where('id IN (SELECT to_qu_id FROM cache__quantity_unit_conversions_resolved WHERE product_id = :1) OR NOT EXISTS(SELECT 1 FROM stock_log WHERE product_id = :1)', $product->id)->orderBy('name', 'COLLATE NOCASE'), 'quantityunitsReferenced' => $this->DB->quantity_units()->where('id IN (SELECT to_qu_id FROM cache__quantity_unit_conversions_resolved WHERE product_id = :1) OR NOT EXISTS(SELECT 1 FROM stock_log WHERE product_id = :1)', $product->id)->orderBy('name', 'COLLATE NOCASE'),
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'productgroups' => $this->getDatabase()->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'productgroups' => $this->DB->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('products'), 'userfields' => UserfieldsService::GetInstance()->GetFields('products'),
'products' => $this->getDatabase()->products()->where('id != :1 AND parent_product_id IS NULL and active = 1', $product->id)->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('id != :1 AND parent_product_id IS NULL and active = 1', $product->id)->orderBy('name', 'COLLATE NOCASE'),
'isSubProductOfOthers' => $this->getDatabase()->products()->where('parent_product_id = :1', $product->id)->count() !== 0, 'isSubProductOfOthers' => $this->DB->products()->where('parent_product_id = :1', $product->id)->count() !== 0,
'mode' => 'edit', 'mode' => 'edit',
'quConversions' => $this->getDatabase()->quantity_unit_conversions()->where('product_id', $product->id), 'quConversions' => $this->DB->quantity_unit_conversions()->where('product_id', $product->id),
'productBarcodeUserfields' => $this->getUserfieldsService()->GetFields('product_barcodes'), 'productBarcodeUserfields' => UserfieldsService::GetInstance()->GetFields('product_barcodes'),
'productBarcodeUserfieldValues' => $this->getUserfieldsService()->GetAllValues('product_barcodes') 'productBarcodeUserfieldValues' => UserfieldsService::GetInstance()->GetAllValues('product_barcodes')
]); ]);
} }
} }
@ -243,17 +247,17 @@ class StockController extends BaseController
{ {
if ($args['productGroupId'] == 'new') if ($args['productGroupId'] == 'new')
{ {
return $this->renderPage($response, 'productgroupform', [ return $this->RenderPage($response, 'productgroupform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('product_groups') 'userfields' => UserfieldsService::GetInstance()->GetFields('product_groups')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'productgroupform', [ return $this->RenderPage($response, 'productgroupform', [
'group' => $this->getDatabase()->product_groups($args['productGroupId']), 'group' => $this->DB->product_groups($args['productGroupId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('product_groups') 'userfields' => UserfieldsService::GetInstance()->GetFields('product_groups')
]); ]);
} }
} }
@ -262,24 +266,24 @@ class StockController extends BaseController
{ {
if (isset($request->getQueryParams()['include_disabled'])) if (isset($request->getQueryParams()['include_disabled']))
{ {
$productGroups = $this->getDatabase()->product_groups()->orderBy('name', 'COLLATE NOCASE'); $productGroups = $this->DB->product_groups()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$productGroups = $this->getDatabase()->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $productGroups = $this->DB->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
} }
return $this->renderPage($response, 'productgroups', [ return $this->RenderPage($response, 'productgroups', [
'productGroups' => $productGroups, 'productGroups' => $productGroups,
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('product_groups'), 'userfields' => UserfieldsService::GetInstance()->GetFields('product_groups'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('product_groups') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('product_groups')
]); ]);
} }
public function ProductsList(Request $request, Response $response, array $args) public function ProductsList(Request $request, Response $response, array $args)
{ {
$products = $this->getDatabase()->products(); $products = $this->DB->products();
if (!isset($request->getQueryParams()['include_disabled'])) if (!isset($request->getQueryParams()['include_disabled']))
{ {
$products = $products->where('active = 1'); $products = $products->where('active = 1');
@ -296,27 +300,27 @@ class StockController extends BaseController
$products = $products->orderBy('name', 'COLLATE NOCASE'); $products = $products->orderBy('name', 'COLLATE NOCASE');
return $this->renderPage($response, 'products', [ return $this->RenderPage($response, 'products', [
'products' => $products, 'products' => $products,
'locations' => $this->getDatabase()->locations()->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->orderBy('name', 'COLLATE NOCASE'),
'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityunits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'productGroups' => $this->getDatabase()->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'productGroups' => $this->DB->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'shoppingLocations' => $this->getDatabase()->shopping_locations()->orderBy('name', 'COLLATE NOCASE'), 'shoppingLocations' => $this->DB->shopping_locations()->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('products'), 'userfields' => UserfieldsService::GetInstance()->GetFields('products'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('products') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('products')
]); ]);
} }
public function Purchase(Request $request, Response $response, array $args) public function Purchase(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'purchase', [ return $this->RenderPage($response, 'purchase', [
'products' => $this->getDatabase()->products()->where('active = 1 AND no_own_stock = 0')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1 AND no_own_stock = 0')->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'userfields' => $this->getUserfieldsService()->GetFields('stock') 'userfields' => UserfieldsService::GetInstance()->GetFields('stock')
]); ]);
} }
@ -325,33 +329,33 @@ class StockController extends BaseController
$product = null; $product = null;
if (isset($request->getQueryParams()['product'])) if (isset($request->getQueryParams()['product']))
{ {
$product = $this->getDatabase()->products($request->getQueryParams()['product']); $product = $this->DB->products($request->getQueryParams()['product']);
} }
$defaultQuUnit = null; $defaultQuUnit = null;
if (isset($request->getQueryParams()['qu-unit'])) if (isset($request->getQueryParams()['qu-unit']))
{ {
$defaultQuUnit = $this->getDatabase()->quantity_units($request->getQueryParams()['qu-unit']); $defaultQuUnit = $this->DB->quantity_units($request->getQueryParams()['qu-unit']);
} }
if ($args['quConversionId'] == 'new') if ($args['quConversionId'] == 'new')
{ {
return $this->renderPage($response, 'quantityunitconversionform', [ return $this->RenderPage($response, 'quantityunitconversionform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('quantity_unit_conversions'), 'userfields' => UserfieldsService::GetInstance()->GetFields('quantity_unit_conversions'),
'quantityunits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityunits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'product' => $product, 'product' => $product,
'defaultQuUnit' => $defaultQuUnit 'defaultQuUnit' => $defaultQuUnit
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'quantityunitconversionform', [ return $this->RenderPage($response, 'quantityunitconversionform', [
'quConversion' => $this->getDatabase()->quantity_unit_conversions($args['quConversionId']), 'quConversion' => $this->DB->quantity_unit_conversions($args['quConversionId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('quantity_unit_conversions'), 'userfields' => UserfieldsService::GetInstance()->GetFields('quantity_unit_conversions'),
'quantityunits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityunits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'product' => $product, 'product' => $product,
'defaultQuUnit' => $defaultQuUnit 'defaultQuUnit' => $defaultQuUnit
]); ]);
@ -362,33 +366,33 @@ class StockController extends BaseController
{ {
if ($args['quantityunitId'] == 'new') if ($args['quantityunitId'] == 'new')
{ {
return $this->renderPage($response, 'quantityunitform', [ return $this->RenderPage($response, 'quantityunitform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'), 'userfields' => UserfieldsService::GetInstance()->GetFields('quantity_units'),
'pluralCount' => $this->getLocalizationService()->GetPluralCount(), 'pluralCount' => LocalizationService::GetInstance()->GetPluralCount(),
'pluralRule' => $this->getLocalizationService()->GetPluralDefinition() 'pluralRule' => LocalizationService::GetInstance()->GetPluralDefinition()
]); ]);
} }
else else
{ {
$quantityUnit = $this->getDatabase()->quantity_units($args['quantityunitId']); $quantityUnit = $this->DB->quantity_units($args['quantityunitId']);
return $this->renderPage($response, 'quantityunitform', [ return $this->RenderPage($response, 'quantityunitform', [
'quantityUnit' => $quantityUnit, 'quantityUnit' => $quantityUnit,
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'), 'userfields' => UserfieldsService::GetInstance()->GetFields('quantity_units'),
'pluralCount' => $this->getLocalizationService()->GetPluralCount(), 'pluralCount' => LocalizationService::GetInstance()->GetPluralCount(),
'pluralRule' => $this->getLocalizationService()->GetPluralDefinition(), 'pluralRule' => LocalizationService::GetInstance()->GetPluralDefinition(),
'defaultQuConversions' => $this->getDatabase()->quantity_unit_conversions()->where('from_qu_id = :1 AND product_id IS NULL', $quantityUnit->id), 'defaultQuConversions' => $this->DB->quantity_unit_conversions()->where('from_qu_id = :1 AND product_id IS NULL', $quantityUnit->id),
'quantityUnits' => $this->getDatabase()->quantity_units() 'quantityUnits' => $this->DB->quantity_units()
]); ]);
} }
} }
public function QuantityUnitPluralFormTesting(Request $request, Response $response, array $args) public function QuantityUnitPluralFormTesting(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'quantityunitpluraltesting', [ return $this->RenderPage($response, 'quantityunitpluraltesting', [
'quantityUnits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE') 'quantityUnits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE')
]); ]);
} }
@ -396,17 +400,17 @@ class StockController extends BaseController
{ {
if (isset($request->getQueryParams()['include_disabled'])) if (isset($request->getQueryParams()['include_disabled']))
{ {
$quantityUnits = $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'); $quantityUnits = $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$quantityUnits = $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $quantityUnits = $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
} }
return $this->renderPage($response, 'quantityunits', [ return $this->RenderPage($response, 'quantityunits', [
'quantityunits' => $quantityUnits, 'quantityunits' => $quantityUnits,
'userfields' => $this->getUserfieldsService()->GetFields('quantity_units'), 'userfields' => UserfieldsService::GetInstance()->GetFields('quantity_units'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('quantity_units') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('quantity_units')
]); ]);
} }
@ -418,20 +422,20 @@ class StockController extends BaseController
$listId = $request->getQueryParams()['list']; $listId = $request->getQueryParams()['list'];
} }
return $this->renderPage($response, 'shoppinglist', [ return $this->RenderPage($response, 'shoppinglist', [
'listItems' => $this->getDatabase()->uihelper_shopping_list()->where('shopping_list_id = :1', $listId)->orderBy('product_name', 'COLLATE NOCASE'), 'listItems' => $this->DB->uihelper_shopping_list()->where('shopping_list_id = :1', $listId)->orderBy('product_name', 'COLLATE NOCASE'),
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityunits' => $this->getDatabase()->quantity_units()->orderBy('name', 'COLLATE NOCASE'), 'quantityunits' => $this->DB->quantity_units()->orderBy('name', 'COLLATE NOCASE'),
'missingProducts' => $this->getStockService()->GetMissingProducts(), 'missingProducts' => StockService::GetInstance()->GetMissingProducts(),
'shoppingLists' => $this->getDatabase()->shopping_lists_view()->orderBy('name', 'COLLATE NOCASE'), 'shoppingLists' => $this->DB->shopping_lists_view()->orderBy('name', 'COLLATE NOCASE'),
'selectedShoppingListId' => $listId, 'selectedShoppingListId' => $listId,
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'productUserfields' => $this->getUserfieldsService()->GetFields('products'), 'productUserfields' => UserfieldsService::GetInstance()->GetFields('products'),
'productUserfieldValues' => $this->getUserfieldsService()->GetAllValues('products'), 'productUserfieldValues' => UserfieldsService::GetInstance()->GetAllValues('products'),
'productGroupUserfields' => $this->getUserfieldsService()->GetFields('product_groups'), 'productGroupUserfields' => UserfieldsService::GetInstance()->GetFields('product_groups'),
'productGroupUserfieldValues' => $this->getUserfieldsService()->GetAllValues('product_groups'), 'productGroupUserfieldValues' => UserfieldsService::GetInstance()->GetAllValues('product_groups'),
'userfields' => $this->getUserfieldsService()->GetFields('shopping_list'), 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_list'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('shopping_list') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('shopping_list')
]); ]);
} }
@ -439,17 +443,17 @@ class StockController extends BaseController
{ {
if ($args['listId'] == 'new') if ($args['listId'] == 'new')
{ {
return $this->renderPage($response, 'shoppinglistform', [ return $this->RenderPage($response, 'shoppinglistform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('shopping_lists') 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_lists')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'shoppinglistform', [ return $this->RenderPage($response, 'shoppinglistform', [
'shoppingList' => $this->getDatabase()->shopping_lists($args['listId']), 'shoppingList' => $this->DB->shopping_lists($args['listId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('shopping_lists') 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_lists')
]); ]);
} }
} }
@ -458,35 +462,35 @@ class StockController extends BaseController
{ {
if ($args['itemId'] == 'new') if ($args['itemId'] == 'new')
{ {
return $this->renderPage($response, 'shoppinglistitemform', [ return $this->RenderPage($response, 'shoppinglistitemform', [
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name', 'COLLATE NOCASE'), 'shoppingLists' => $this->DB->shopping_lists()->orderBy('name', 'COLLATE NOCASE'),
'mode' => 'create', 'mode' => 'create',
'quantityUnits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'userfields' => $this->getUserfieldsService()->GetFields('shopping_list') 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_list')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'shoppinglistitemform', [ return $this->RenderPage($response, 'shoppinglistitemform', [
'listItem' => $this->getDatabase()->shopping_list($args['itemId']), 'listItem' => $this->DB->shopping_list($args['itemId']),
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name', 'COLLATE NOCASE'), 'shoppingLists' => $this->DB->shopping_lists()->orderBy('name', 'COLLATE NOCASE'),
'mode' => 'edit', 'mode' => 'edit',
'quantityUnits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved(), 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved(),
'userfields' => $this->getUserfieldsService()->GetFields('shopping_list') 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_list')
]); ]);
} }
} }
public function ShoppingListSettings(Request $request, Response $response, array $args) public function ShoppingListSettings(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'shoppinglistsettings', [ return $this->RenderPage($response, 'shoppinglistsettings', [
'shoppingLists' => $this->getDatabase()->shopping_lists()->orderBy('name', 'COLLATE NOCASE') 'shoppingLists' => $this->DB->shopping_lists()->orderBy('name', 'COLLATE NOCASE')
]); ]);
} }
@ -494,17 +498,17 @@ class StockController extends BaseController
{ {
if ($args['shoppingLocationId'] == 'new') if ($args['shoppingLocationId'] == 'new')
{ {
return $this->renderPage($response, 'shoppinglocationform', [ return $this->RenderPage($response, 'shoppinglocationform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('shopping_locations') 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_locations')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'shoppinglocationform', [ return $this->RenderPage($response, 'shoppinglocationform', [
'shoppingLocation' => $this->getDatabase()->shopping_locations($args['shoppingLocationId']), 'shoppingLocation' => $this->DB->shopping_locations($args['shoppingLocationId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('shopping_locations') 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_locations')
]); ]);
} }
} }
@ -513,90 +517,90 @@ class StockController extends BaseController
{ {
if (isset($request->getQueryParams()['include_disabled'])) if (isset($request->getQueryParams()['include_disabled']))
{ {
$shoppingLocations = $this->getDatabase()->shopping_locations()->orderBy('name', 'COLLATE NOCASE'); $shoppingLocations = $this->DB->shopping_locations()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$shoppingLocations = $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $shoppingLocations = $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
} }
return $this->renderPage($response, 'shoppinglocations', [ return $this->RenderPage($response, 'shoppinglocations', [
'shoppinglocations' => $shoppingLocations, 'shoppinglocations' => $shoppingLocations,
'userfields' => $this->getUserfieldsService()->GetFields('shopping_locations'), 'userfields' => UserfieldsService::GetInstance()->GetFields('shopping_locations'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('shopping_locations') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('shopping_locations')
]); ]);
} }
public function StockEntryEditForm(Request $request, Response $response, array $args) public function StockEntryEditForm(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'stockentryform', [ return $this->RenderPage($response, 'stockentryform', [
'stockEntry' => $this->getDatabase()->stock()->where('id', $args['entryId'])->fetch(), 'stockEntry' => $this->DB->stock()->where('id', $args['entryId'])->fetch(),
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('stock') 'userfields' => UserfieldsService::GetInstance()->GetFields('stock')
]); ]);
} }
public function StockEntryGrocycodeImage(Request $request, Response $response, array $args) public function StockEntryGrocycodeImage(Request $request, Response $response, array $args)
{ {
$stockEntry = $this->getDatabase()->stock()->where('id', $args['entryId'])->fetch(); $stockEntry = $this->DB->stock()->where('id', $args['entryId'])->fetch();
$gc = new Grocycode(Grocycode::PRODUCT, $stockEntry->product_id, [$stockEntry->stock_id]); $gc = new Grocycode(Grocycode::PRODUCT, $stockEntry->product_id, [$stockEntry->stock_id]);
return $this->ServeGrocycodeImage($request, $response, $gc); return $this->ServeGrocycodeImage($request, $response, $gc);
} }
public function StockEntryGrocycodeLabel(Request $request, Response $response, array $args) public function StockEntryGrocycodeLabel(Request $request, Response $response, array $args)
{ {
$stockEntry = $this->getDatabase()->stock()->where('id', $args['entryId'])->fetch(); $stockEntry = $this->DB->stock()->where('id', $args['entryId'])->fetch();
return $this->renderPage($response, 'stockentrylabel', [ return $this->RenderPage($response, 'stockentrylabel', [
'stockEntry' => $stockEntry, 'stockEntry' => $stockEntry,
'product' => $this->getDatabase()->products($stockEntry->product_id), 'product' => $this->DB->products($stockEntry->product_id),
]); ]);
} }
public function StockSettings(Request $request, Response $response, array $args) public function StockSettings(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'stocksettings', [ return $this->RenderPage($response, 'stocksettings', [
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityunits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityunits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'productGroups' => $this->getDatabase()->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE') 'productGroups' => $this->DB->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE')
]); ]);
} }
public function Stockentries(Request $request, Response $response, array $args) public function Stockentries(Request $request, Response $response, array $args)
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_due_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['stock_due_soon_days'];
return $this->renderPage($response, 'stockentries', [ return $this->RenderPage($response, 'stockentries', [
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityunits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityunits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'shoppinglocations' => $this->getDatabase()->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'shoppinglocations' => $this->DB->shopping_locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'stockEntries' => $this->getDatabase()->uihelper_stock_entries()->orderBy('product_id'), 'stockEntries' => $this->DB->uihelper_stock_entries()->orderBy('product_id'),
'currentStockLocations' => $this->getStockService()->GetCurrentStockLocations(), 'currentStockLocations' => StockService::GetInstance()->GetCurrentStockLocations(),
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'userfieldsProducts' => $this->getUserfieldsService()->GetFields('products'), 'userfieldsProducts' => UserfieldsService::GetInstance()->GetFields('products'),
'userfieldValuesProducts' => $this->getUserfieldsService()->GetAllValues('products'), 'userfieldValuesProducts' => UserfieldsService::GetInstance()->GetAllValues('products'),
'userfieldsStock' => $this->getUserfieldsService()->GetFields('stock'), 'userfieldsStock' => UserfieldsService::GetInstance()->GetFields('stock'),
'userfieldValuesStock' => $this->getUserfieldsService()->GetAllValues('stock') 'userfieldValuesStock' => UserfieldsService::GetInstance()->GetAllValues('stock')
]); ]);
} }
public function Transfer(Request $request, Response $response, array $args) public function Transfer(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'transfer', [ return $this->RenderPage($response, 'transfer', [
'products' => $this->getDatabase()->products()->where('active = 1')->where('no_own_stock = 0 AND id IN (SELECT product_id from stock_current WHERE amount_aggregated > 0)')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->where('no_own_stock = 0 AND id IN (SELECT product_id from stock_current WHERE amount_aggregated > 0)')->orderBy('name', 'COLLATE NOCASE'),
'barcodes' => $this->getDatabase()->product_barcodes_comma_separated(), 'barcodes' => $this->DB->product_barcodes_comma_separated(),
'locations' => $this->getDatabase()->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'locations' => $this->DB->locations()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $this->getDatabase()->cache__quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->DB->cache__quantity_unit_conversions_resolved()
]); ]);
} }
public function JournalSummary(Request $request, Response $response, array $args) public function JournalSummary(Request $request, Response $response, array $args)
{ {
$entries = $this->getDatabase()->uihelper_stock_journal_summary(); $entries = $this->DB->uihelper_stock_journal_summary();
if (isset($request->getQueryParams()['product_id'])) if (isset($request->getQueryParams()['product_id']))
{ {
$entries = $entries->where('product_id', $request->getQueryParams()['product_id']); $entries = $entries->where('product_id', $request->getQueryParams()['product_id']);
@ -610,10 +614,10 @@ class StockController extends BaseController
$entries = $entries->where('transaction_type', $request->getQueryParams()['transaction_type']); $entries = $entries->where('transaction_type', $request->getQueryParams()['transaction_type']);
} }
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
return $this->renderPage($response, 'stockjournalsummary', [ return $this->RenderPage($response, 'stockjournalsummary', [
'entries' => $entries, 'entries' => $entries,
'products' => $this->getDatabase()->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'products' => $this->DB->products()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $usersService->GetUsersAsDto(), 'users' => $usersService->GetUsersAsDto(),
'transactionTypes' => GetClassConstants('\Grocy\Services\StockService', 'TRANSACTION_TYPE_') 'transactionTypes' => GetClassConstants('\Grocy\Services\StockService', 'TRANSACTION_TYPE_')
]); ]);
@ -624,17 +628,17 @@ class StockController extends BaseController
$product = null; $product = null;
if (isset($request->getQueryParams()['product'])) if (isset($request->getQueryParams()['product']))
{ {
$product = $this->getDatabase()->products($request->getQueryParams()['product']); $product = $this->DB->products($request->getQueryParams()['product']);
$quantityUnitConversionsResolved = $this->getDatabase()->cache__quantity_unit_conversions_resolved()->where('product_id', $product->id); $quantityUnitConversionsResolved = $this->DB->cache__quantity_unit_conversions_resolved()->where('product_id', $product->id);
} }
else else
{ {
$quantityUnitConversionsResolved = $this->getDatabase()->cache__quantity_unit_conversions_resolved()->where('product_id IS NULL'); $quantityUnitConversionsResolved = $this->DB->cache__quantity_unit_conversions_resolved()->where('product_id IS NULL');
} }
return $this->renderPage($response, 'quantityunitconversionsresolved', [ return $this->RenderPage($response, 'quantityunitconversionsresolved', [
'product' => $product, 'product' => $product,
'quantityUnits' => $this->getDatabase()->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'quantityUnits' => $this->DB->quantity_units()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'quantityUnitConversionsResolved' => $quantityUnitConversionsResolved 'quantityUnitConversionsResolved' => $quantityUnitConversionsResolved
]); ]);
} }

View File

@ -2,6 +2,7 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Services\DatabaseService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -95,9 +96,9 @@ class StockReportsController extends BaseController
"; ";
} }
return $this->renderPage($response, 'stockreportspendings', [ return $this->RenderPage($response, 'stockreportspendings', [
'metrics' => $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ), 'metrics' => DatabaseService::GetInstance()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ),
'productGroups' => $this->getDatabase()->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'productGroups' => $this->DB->product_groups()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'selectedGroup' => isset($request->getQueryParams()['product-group']) ? $request->getQueryParams()['product-group'] : null, 'selectedGroup' => isset($request->getQueryParams()['product-group']) ? $request->getQueryParams()['product-group'] : null,
'groupBy' => $groupBy 'groupBy' => $groupBy
]); ]);

View File

@ -2,6 +2,7 @@
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;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
@ -11,27 +12,27 @@ class SystemController extends BaseController
{ {
public function About(Request $request, Response $response, array $args) public function About(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'about', [ return $this->RenderPage($response, 'about', [
'systemInfo' => $this->getApplicationService()->GetSystemInfo(), 'systemInfo' => ApplicationService::GetInstance()->GetSystemInfo(),
'versionInfo' => $this->getApplicationService()->GetInstalledVersion(), 'versionInfo' => ApplicationService::GetInstance()->GetInstalledVersion(),
'changelog' => $this->getApplicationService()->GetChangelog() 'changelog' => ApplicationService::GetInstance()->GetChangelog()
]); ]);
} }
public function BarcodeScannerTesting(Request $request, Response $response, array $args) public function BarcodeScannerTesting(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'barcodescannertesting'); return $this->RenderPage($response, 'barcodescannertesting');
} }
public function Root(Request $request, Response $response, array $args) public function Root(Request $request, Response $response, array $args)
{ {
// Schema migration is done here // Schema migration is done here
$databaseMigrationService = DatabaseMigrationService::getInstance(); $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 = DemoDataGeneratorService::getInstance(); $demoDataGeneratorService = DemoDataGeneratorService::GetInstance();
$demoDataGeneratorService->PopulateDemoData(isset($request->getQueryParams()['nodemodata'])); $demoDataGeneratorService->PopulateDemoData(isset($request->getQueryParams()['nodemodata']));
} }

View File

@ -2,6 +2,9 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Services\TasksService;
use Grocy\Services\UsersService;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -9,16 +12,16 @@ class TasksController extends BaseController
{ {
public function Overview(Request $request, Response $response, array $args) public function Overview(Request $request, Response $response, array $args)
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
$nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['tasks_due_soon_days']; $nextXDays = $usersService->GetUserSettings(GROCY_USER_ID)['tasks_due_soon_days'];
if (isset($request->getQueryParams()['include_done'])) if (isset($request->getQueryParams()['include_done']))
{ {
$tasks = $this->getDatabase()->tasks()->orderBy('name', 'COLLATE NOCASE'); $tasks = $this->DB->tasks()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$tasks = $this->getTasksService()->GetCurrent(); $tasks = TasksService::GetInstance()->GetCurrent();
} }
foreach ($tasks as $task) foreach ($tasks as $task)
@ -41,13 +44,13 @@ class TasksController extends BaseController
} }
} }
return $this->renderPage($response, 'tasks', [ return $this->RenderPage($response, 'tasks', [
'tasks' => $tasks, 'tasks' => $tasks,
'nextXDays' => $nextXDays, 'nextXDays' => $nextXDays,
'taskCategories' => $this->getDatabase()->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'taskCategories' => $this->DB->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users(), 'users' => $this->DB->users(),
'userfields' => $this->getUserfieldsService()->GetFields('tasks'), 'userfields' => UserfieldsService::GetInstance()->GetFields('tasks'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('tasks') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('tasks')
]); ]);
} }
@ -55,17 +58,17 @@ class TasksController extends BaseController
{ {
if (isset($request->getQueryParams()['include_disabled'])) if (isset($request->getQueryParams()['include_disabled']))
{ {
$categories = $this->getDatabase()->task_categories()->orderBy('name', 'COLLATE NOCASE'); $categories = $this->DB->task_categories()->orderBy('name', 'COLLATE NOCASE');
} }
else else
{ {
$categories = $this->getDatabase()->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $categories = $this->DB->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
} }
return $this->renderPage($response, 'taskcategories', [ return $this->RenderPage($response, 'taskcategories', [
'taskCategories' => $categories, 'taskCategories' => $categories,
'userfields' => $this->getUserfieldsService()->GetFields('task_categories'), 'userfields' => UserfieldsService::GetInstance()->GetFields('task_categories'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('task_categories') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('task_categories')
]); ]);
} }
@ -73,17 +76,17 @@ class TasksController extends BaseController
{ {
if ($args['categoryId'] == 'new') if ($args['categoryId'] == 'new')
{ {
return $this->renderPage($response, 'taskcategoryform', [ return $this->RenderPage($response, 'taskcategoryform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('task_categories') 'userfields' => UserfieldsService::GetInstance()->GetFields('task_categories')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'taskcategoryform', [ return $this->RenderPage($response, 'taskcategoryform', [
'category' => $this->getDatabase()->task_categories($args['categoryId']), 'category' => $this->DB->task_categories($args['categoryId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('task_categories') 'userfields' => UserfieldsService::GetInstance()->GetFields('task_categories')
]); ]);
} }
} }
@ -92,27 +95,27 @@ class TasksController extends BaseController
{ {
if ($args['taskId'] == 'new') if ($args['taskId'] == 'new')
{ {
return $this->renderPage($response, 'taskform', [ return $this->RenderPage($response, 'taskform', [
'mode' => 'create', 'mode' => 'create',
'taskCategories' => $this->getDatabase()->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'taskCategories' => $this->DB->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'), 'users' => $this->DB->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('tasks') 'userfields' => UserfieldsService::GetInstance()->GetFields('tasks')
]); ]);
} }
else else
{ {
return $this->renderPage($response, 'taskform', [ return $this->RenderPage($response, 'taskform', [
'task' => $this->getDatabase()->tasks($args['taskId']), 'task' => $this->DB->tasks($args['taskId']),
'mode' => 'edit', 'mode' => 'edit',
'taskCategories' => $this->getDatabase()->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'), 'taskCategories' => $this->DB->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'), 'users' => $this->DB->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('tasks') 'userfields' => UserfieldsService::GetInstance()->GetFields('tasks')
]); ]);
} }
} }
public function TasksSettings(Request $request, Response $response, array $args) public function TasksSettings(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'taskssettings'); return $this->RenderPage($response, 'taskssettings');
} }
} }

View File

@ -40,43 +40,43 @@ class User
public function __construct() public function __construct()
{ {
$this->db = DatabaseService::getInstance()->GetDbConnection(); $this->DB = DatabaseService::GetInstance()->GetDbConnection();
} }
protected $db; protected $DB;
public static function PermissionList() public static function PermissionList()
{ {
$user = new self(); $user = new self();
return $user->getPermissionList(); return $user->GetPermissionList();
} }
public static function checkPermission($request, string $permission): void public static function CheckPermission($request, string $permission): void
{ {
$user = new self(); $user = new self();
if (!$user->hasPermission($permission)) if (!$user->HasPermission($permission))
{ {
throw new PermissionMissingException($request, $permission); throw new PermissionMissingException($request, $permission);
} }
} }
public function getPermissionList() public function GetPermissionList()
{ {
return $this->db->uihelper_user_permissions()->where('user_id', GROCY_USER_ID); return $this->DB->uihelper_user_permissions()->where('user_id', GROCY_USER_ID);
} }
public function hasPermission(string $permission): bool public function HasPermission(string $permission): bool
{ {
return $this->getPermissions()->where('permission_name', $permission)->fetch() !== null; return $this->GetPermissions()->where('permission_name', $permission)->fetch() !== null;
} }
public static function hasPermissions(string ...$permissions) public static function HasPermissions(string ...$permissions)
{ {
$user = new self(); $user = new self();
foreach ($permissions as $permission) foreach ($permissions as $permission)
{ {
if (!$user->hasPermission($permission)) if (!$user->HasPermission($permission))
{ {
return false; return false;
} }
@ -85,8 +85,8 @@ class User
return true; return true;
} }
protected function getPermissions(): Result protected function GetPermissions(): Result
{ {
return $this->db->user_permissions_resolved()->where('user_id', GROCY_USER_ID); return $this->DB->user_permissions_resolved()->where('user_id', GROCY_USER_ID);
} }
} }

View File

@ -3,6 +3,7 @@
namespace Grocy\Controllers; namespace Grocy\Controllers;
use Grocy\Controllers\Users\User; use Grocy\Controllers\Users\User;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
@ -10,10 +11,10 @@ class UsersController extends BaseController
{ {
public function PermissionList(Request $request, Response $response, array $args) public function PermissionList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_USERS_READ); User::CheckPermission($request, User::PERMISSION_USERS_READ);
return $this->renderPage($response, 'userpermissions', [ return $this->RenderPage($response, 'userpermissions', [
'user' => $this->getDatabase()->users($args['userId']), 'user' => $this->DB->users($args['userId']),
'permissions' => $this->getDatabase()->uihelper_user_permissions() 'permissions' => $this->DB->uihelper_user_permissions()
->where('parent IS NULL')->where('user_id', $args['userId']) ->where('parent IS NULL')->where('user_id', $args['userId'])
]); ]);
} }
@ -22,35 +23,35 @@ class UsersController extends BaseController
{ {
if ($args['userId'] == 'new') if ($args['userId'] == 'new')
{ {
User::checkPermission($request, User::PERMISSION_USERS_CREATE); User::CheckPermission($request, User::PERMISSION_USERS_CREATE);
return $this->renderPage($response, 'userform', [ return $this->RenderPage($response, 'userform', [
'mode' => 'create', 'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('users') 'userfields' => UserfieldsService::GetInstance()->GetFields('users')
]); ]);
} }
else else
{ {
if ($args['userId'] == GROCY_USER_ID) if ($args['userId'] == GROCY_USER_ID)
{ {
User::checkPermission($request, User::PERMISSION_USERS_EDIT_SELF); User::CheckPermission($request, User::PERMISSION_USERS_EDIT_SELF);
} }
else else
{ {
User::checkPermission($request, User::PERMISSION_USERS_EDIT); User::CheckPermission($request, User::PERMISSION_USERS_EDIT);
} }
return $this->renderPage($response, 'userform', [ return $this->RenderPage($response, 'userform', [
'user' => $this->getDatabase()->users($args['userId']), 'user' => $this->DB->users($args['userId']),
'mode' => 'edit', 'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('users'), 'userfields' => UserfieldsService::GetInstance()->GetFields('users'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('users') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('users')
]); ]);
} }
} }
public function UserSettings(Request $request, Response $response, array $args) public function UserSettings(Request $request, Response $response, array $args)
{ {
return $this->renderPage($response, 'usersettings', [ return $this->RenderPage($response, 'usersettings', [
'languages' => array_filter(scandir(__DIR__ . '/../localization'), function ($item) 'languages' => array_filter(scandir(__DIR__ . '/../localization'), function ($item)
{ {
if ($item == '.' || $item == '..') if ($item == '.' || $item == '..')
@ -65,11 +66,11 @@ class UsersController extends BaseController
public function UsersList(Request $request, Response $response, array $args) public function UsersList(Request $request, Response $response, array $args)
{ {
User::checkPermission($request, User::PERMISSION_USERS_READ); User::CheckPermission($request, User::PERMISSION_USERS_READ);
return $this->renderPage($response, 'users', [ return $this->RenderPage($response, 'users', [
'users' => $this->getDatabase()->users()->orderBy('username'), 'users' => $this->DB->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('users'), 'userfields' => UserfieldsService::GetInstance()->GetFields('users'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('users') 'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('users')
]); ]);
} }
} }

View File

@ -17,7 +17,7 @@ class SlimBladeView
protected $CachePath; protected $CachePath;
protected $ViewData = []; protected $ViewData = [];
public function render(ResponseInterface $response, string $template, array $data = []) public function Render(ResponseInterface $response, string $template, array $data = [])
{ {
$data = array_merge($this->ViewData, $data); $data = array_merge($this->ViewData, $data);
$renderer = new Blade($this->ViewPaths, $this->CachePath, null); $renderer = new Blade($this->ViewPaths, $this->CachePath, null);

View File

@ -3,8 +3,6 @@
namespace Grocy\Helpers; namespace Grocy\Helpers;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\ExceptionRequestException;
use Psr\Http\Message\ResponseInterface;
class WebhookRunner class WebhookRunner
{ {

View File

@ -29,7 +29,7 @@ abstract class AuthMiddleware extends BaseMiddleware
if (GROCY_MODE === 'dev' || GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease' || GROCY_IS_EMBEDDED_INSTALL || GROCY_DISABLE_AUTH) if (GROCY_MODE === 'dev' || GROCY_MODE === 'demo' || GROCY_MODE === 'prerelease' || GROCY_IS_EMBEDDED_INSTALL || GROCY_DISABLE_AUTH)
{ {
$sessionService = SessionService::getInstance(); $sessionService = SessionService::GetInstance();
$user = $sessionService->GetDefaultUser(); $user = $sessionService->GetDefaultUser();
define('GROCY_AUTHENTICATED', true); define('GROCY_AUTHENTICATED', true);

View File

@ -12,7 +12,7 @@ class BaseMiddleware
{ {
$this->AppContainer = $container; $this->AppContainer = $container;
$this->ResponseFactory = $responseFactory; $this->ResponseFactory = $responseFactory;
$this->ApplicationService = ApplicationService::getInstance(); $this->ApplicationService = ApplicationService::GetInstance();
} }
protected $AppContainer; protected $AppContainer;

View File

@ -29,7 +29,7 @@ class DefaultAuthMiddleware extends AuthMiddleware
{ {
if (isset($postParams['username']) && isset($postParams['password'])) if (isset($postParams['username']) && isset($postParams['password']))
{ {
$db = DatabaseService::getInstance()->GetDbConnection(); $db = DatabaseService::GetInstance()->GetDbConnection();
$user = $db->users()->where('username', $postParams['username'])->fetch(); $user = $db->users()->where('username', $postParams['username'])->fetch();
$inputPassword = $postParams['password']; $inputPassword = $postParams['password'];
@ -37,7 +37,7 @@ class DefaultAuthMiddleware extends AuthMiddleware
if ($user !== null && password_verify($inputPassword, $user->password)) if ($user !== null && password_verify($inputPassword, $user->password))
{ {
$sessionKey = SessionService::getInstance()->CreateSession($user->id, $stayLoggedInPermanently); $sessionKey = SessionService::GetInstance()->CreateSession($user->id, $stayLoggedInPermanently);
self::SetSessionCookie($sessionKey); self::SetSessionCookie($sessionKey);
if (password_needs_rehash($user->password, PASSWORD_ARGON2ID)) if (password_needs_rehash($user->password, PASSWORD_ARGON2ID))

View File

@ -75,14 +75,14 @@ class LdapAuthMiddleware extends AuthMiddleware
{ {
ldap_close($connect); ldap_close($connect);
$db = DatabaseService::getInstance()->GetDbConnection(); $db = DatabaseService::GetInstance()->GetDbConnection();
$user = $db->users()->where('username', $ldapUidAttribute)->fetch(); $user = $db->users()->where('username', $ldapUidAttribute)->fetch();
if ($user == null) if ($user == null)
{ {
$user = UsersService::getInstance()->CreateUser($ldapUidAttribute, $ldapFirstName, $ldapLastName, ''); $user = UsersService::GetInstance()->CreateUser($ldapUidAttribute, $ldapFirstName, $ldapLastName, '');
} }
$sessionKey = SessionService::getInstance()->CreateSession($user->id, $postParams['stay_logged_in'] == 'on'); $sessionKey = SessionService::GetInstance()->CreateSession($user->id, $postParams['stay_logged_in'] == 'on');
self::SetSessionCookie($sessionKey); self::SetSessionCookie($sessionKey);
return true; return true;

View File

@ -20,7 +20,7 @@ class LocaleMiddleware extends BaseMiddleware
{ {
if (defined('GROCY_AUTHENTICATED') && GROCY_AUTHENTICATED) if (defined('GROCY_AUTHENTICATED') && GROCY_AUTHENTICATED)
{ {
$locale = UsersService::getInstance()->GetUserSetting(GROCY_USER_ID, 'locale'); $locale = UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'locale');
if (isset($locale) && !empty($locale)) if (isset($locale) && !empty($locale))
{ {
if (in_array($locale, scandir(__DIR__ . '/../localization'))) if (in_array($locale, scandir(__DIR__ . '/../localization')))

View File

@ -12,7 +12,7 @@ class ReverseProxyAuthMiddleware extends AuthMiddleware
{ {
define('GROCY_EXTERNALLY_MANAGED_AUTHENTICATION', true); define('GROCY_EXTERNALLY_MANAGED_AUTHENTICATION', true);
$db = DatabaseService::getInstance()->GetDbConnection(); $db = DatabaseService::GetInstance()->GetDbConnection();
// API key authentication is also ok // API key authentication is also ok
$auth = new ApiKeyAuthMiddleware($this->AppContainer, $this->ResponseFactory); $auth = new ApiKeyAuthMiddleware($this->AppContainer, $this->ResponseFactory);
@ -51,7 +51,7 @@ class ReverseProxyAuthMiddleware extends AuthMiddleware
$user = $db->users()->where('username', $username)->fetch(); $user = $db->users()->where('username', $username)->fetch();
if ($user == null) if ($user == null)
{ {
$user = UsersService::getInstance()->CreateUser($username, '', '', ''); $user = UsersService::GetInstance()->CreateUser($username, '', '', '');
} }
return $user; return $user;

View File

@ -9,7 +9,7 @@ class SessionAuthMiddleware extends AuthMiddleware
{ {
public function authenticate(Request $request) public function authenticate(Request $request)
{ {
$sessionService = SessionService::getInstance(); $sessionService = SessionService::GetInstance();
if (!isset($_COOKIE[SessionService::SESSION_COOKIE_NAME]) || !$sessionService->IsValidSession($_COOKIE[SessionService::SESSION_COOKIE_NAME])) if (!isset($_COOKIE[SessionService::SESSION_COOKIE_NAME]) || !$sessionService->IsValidSession($_COOKIE[SessionService::SESSION_COOKIE_NAME]))
{ {

View File

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

View File

@ -2,8 +2,11 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
$localizationService = $this->getLocalizationService(); use Grocy\Services\DatabaseService;
$db = $this->getDatabaseService()->GetDbConnection(); use Grocy\Services\LocalizationService;
$localizationService = LocalizationService::GetInstance(GROCY_DEFAULT_LOCALE);
$db = DatabaseService::GetInstance()->GetDbConnection();
if ($db->quantity_units()->count() === 0) if ($db->quantity_units()->count() === 0)
{ {

View File

@ -2,8 +2,11 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
$localizationService = $this->getLocalizationService(); use Grocy\Services\DatabaseService;
$db = $this->getDatabaseService()->GetDbConnection(); use Grocy\Services\LocalizationService;
$localizationService = LocalizationService::GetInstance(GROCY_DEFAULT_LOCALE);
$db = DatabaseService::GetInstance()->GetDbConnection();
$defaultShoppingList = $db->shopping_lists()->where('id = 1')->fetch(); $defaultShoppingList = $db->shopping_lists()->where('id = 1')->fetch();
$defaultShoppingList->update([ $defaultShoppingList->update([

View File

@ -2,4 +2,6 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
$this->getStockService()->CompactStockEntries(); use Grocy\Services\StockService;
StockService::GetInstance()->CompactStockEntries();

View File

@ -2,6 +2,8 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
use Grocy\Services\DatabaseService;
// Migrate the old config.php setting FEATURE_SETTING_STOCK_COUNT_OPENED_PRODUCTS_AGAINST_MINIMUM_STOCK_AMOUNT // Migrate the old config.php setting FEATURE_SETTING_STOCK_COUNT_OPENED_PRODUCTS_AGAINST_MINIMUM_STOCK_AMOUNT
// to the new product option treat_opened_as_out_of_stock // to the new product option treat_opened_as_out_of_stock
// New and old default was/is enabled, so only disable it for all existing products when it was disabled // New and old default was/is enabled, so only disable it for all existing products when it was disabled
@ -13,6 +15,6 @@ if (!defined('GROCY_FEATURE_SETTING_STOCK_COUNT_OPENED_PRODUCTS_AGAINST_MINIMUM_
if (!GROCY_FEATURE_SETTING_STOCK_COUNT_OPENED_PRODUCTS_AGAINST_MINIMUM_STOCK_AMOUNT) if (!GROCY_FEATURE_SETTING_STOCK_COUNT_OPENED_PRODUCTS_AGAINST_MINIMUM_STOCK_AMOUNT)
{ {
$this->getDatabaseService()->ExecuteDbStatement('UPDATE products SET treat_opened_as_out_of_stock = 0'); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE products SET treat_opened_as_out_of_stock = 0');
$this->getDatabaseService()->ExecuteDbStatement("INSERT INTO user_settings (user_id, key, value) SELECT id, 'product_presets_treat_opened_as_out_of_stock', '0' FROM users"); DatabaseService::GetInstance()->ExecuteDbStatement("INSERT INTO user_settings (user_id, key, value) SELECT id, 'product_presets_treat_opened_as_out_of_stock', '0' FROM users");
} }

View File

@ -2,8 +2,10 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
use Grocy\Services\DatabaseService;
// Assign a new stock_id to all opened stock entries where there is also an unopened one with the same stock_id // Assign a new stock_id to all opened stock entries where there is also an unopened one with the same stock_id
$db = $this->getDatabaseService(); $db = DatabaseService::GetInstance();
$sql = 'SELECT s1.id $sql = 'SELECT s1.id
FROM stock s1 FROM stock s1

View File

@ -4,12 +4,14 @@
// This is executed inside DatabaseMigrationService class/context // This is executed inside DatabaseMigrationService class/context
use Grocy\Services\DatabaseService;
// When FEATURE_FLAG_STOCK_LOCATION_TRACKING is disabled, // When FEATURE_FLAG_STOCK_LOCATION_TRACKING is disabled,
// some places assume that there exists a location with id 1, // some places assume that there exists a location with id 1,
// so make sure that this location is available in that case // so make sure that this location is available in that case
if (!GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING) if (!GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{ {
$db = $this->getDatabaseService()->GetDbConnection(); $db = DatabaseService::GetInstance()->GetDbConnection();
if ($db->locations()->where('id', 1)->count() === 0) if ($db->locations()->where('id', 1)->count() === 0)
{ {

View File

@ -1,28 +1,28 @@
<?php <?php
use Grocy\Controllers\BatteriesApiController; use Grocy\Controllers\Api\BatteriesApiController;
use Grocy\Controllers\Api\CalendarApiController;
use Grocy\Controllers\Api\ChoresApiController;
use Grocy\Controllers\Api\FilesApiController;
use Grocy\Controllers\Api\GenericEntityApiController;
use Grocy\Controllers\Api\OpenApiController;
use Grocy\Controllers\Api\PrintApiController;
use Grocy\Controllers\Api\RecipesApiController;
use Grocy\Controllers\Api\StockApiController;
use Grocy\Controllers\Api\SystemApiController;
use Grocy\Controllers\Api\TasksApiController;
use Grocy\Controllers\Api\UsersApiController;
use Grocy\Controllers\BatteriesController; use Grocy\Controllers\BatteriesController;
use Grocy\Controllers\CalendarApiController;
use Grocy\Controllers\CalendarController; use Grocy\Controllers\CalendarController;
use Grocy\Controllers\ChoresApiController;
use Grocy\Controllers\ChoresController; use Grocy\Controllers\ChoresController;
use Grocy\Controllers\EquipmentController; use Grocy\Controllers\EquipmentController;
use Grocy\Controllers\FilesApiController;
use Grocy\Controllers\GenericEntityApiController;
use Grocy\Controllers\GenericEntityController; use Grocy\Controllers\GenericEntityController;
use Grocy\Controllers\LoginController; use Grocy\Controllers\LoginController;
use Grocy\Controllers\OpenApiController;
use Grocy\Controllers\PrintApiController;
use Grocy\Controllers\RecipesApiController;
use Grocy\Controllers\RecipesController; use Grocy\Controllers\RecipesController;
use Grocy\Controllers\StockApiController;
use Grocy\Controllers\StockController; use Grocy\Controllers\StockController;
use Grocy\Controllers\StockReportsController; use Grocy\Controllers\StockReportsController;
use Grocy\Controllers\SystemApiController;
use Grocy\Controllers\SystemController; use Grocy\Controllers\SystemController;
use Grocy\Controllers\TasksApiController;
use Grocy\Controllers\TasksController; use Grocy\Controllers\TasksController;
use Grocy\Controllers\UsersApiController;
use Grocy\Controllers\UsersController; use Grocy\Controllers\UsersController;
use Grocy\Middleware\CorsMiddleware; use Grocy\Middleware\CorsMiddleware;
use Grocy\Middleware\JsonMiddleware; use Grocy\Middleware\JsonMiddleware;

View File

@ -11,7 +11,7 @@ class ApiKeyService extends BaseService
{ {
$newApiKey = $this->GenerateApiKey(); $newApiKey = $this->GenerateApiKey();
$apiKeyRow = $this->getDatabase()->api_keys()->createRow([ $apiKeyRow = $this->DB->api_keys()->createRow([
'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 never expire 'expires' => '2999-12-31 23:59:59', // Default is that API keys never expire
@ -25,7 +25,7 @@ class ApiKeyService extends BaseService
public function GetApiKeyId($apiKey) public function GetApiKeyId($apiKey)
{ {
$apiKey = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch(); $apiKey = $this->DB->api_keys()->where('api_key', $apiKey)->fetch();
return $apiKey->id; return $apiKey->id;
} }
@ -39,7 +39,7 @@ class ApiKeyService extends BaseService
} }
else else
{ {
$apiKeyRow = $this->getDatabase()->api_keys()->where('key_type = :1 AND expires > :2', $keyType, date('Y-m-d H:i:s', time()))->fetch(); $apiKeyRow = $this->DB->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)
{ {
@ -54,11 +54,11 @@ class ApiKeyService extends BaseService
public function GetUserByApiKey($apiKey) public function GetUserByApiKey($apiKey)
{ {
$apiKeyRow = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch(); $apiKeyRow = $this->DB->api_keys()->where('api_key', $apiKey)->fetch();
if ($apiKeyRow !== null) if ($apiKeyRow !== null)
{ {
return $this->getDatabase()->users($apiKeyRow->user_id); return $this->DB->users($apiKeyRow->user_id);
} }
return null; return null;
@ -72,17 +72,17 @@ class ApiKeyService extends BaseService
} }
else else
{ {
$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(); $apiKeyRow = $this->DB->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->getDatabaseService()->GetDbChangedTime(); $dbModTime = DatabaseService::GetInstance()->GetDbChangedTime();
$apiKeyRow->update([ $apiKeyRow->update([
'last_used' => date('Y-m-d H:i:s', time()) 'last_used' => date('Y-m-d H:i:s', time())
]); ]);
$this->getDatabaseService()->SetDbChangedTime($dbModTime); DatabaseService::GetInstance()->SetDbChangedTime($dbModTime);
return true; return true;
} }
@ -95,7 +95,7 @@ class ApiKeyService extends BaseService
public function RemoveApiKey($apiKey) public function RemoveApiKey($apiKey)
{ {
$this->getDatabase()->api_keys()->where('api_key', $apiKey)->delete(); $this->DB->api_keys()->where('api_key', $apiKey)->delete();
} }
private function GenerateApiKey() private function GenerateApiKey()

View File

@ -69,7 +69,7 @@ class ApplicationService extends BaseService
'grocy_version' => $this->GetInstalledVersion(), 'grocy_version' => $this->GetInstalledVersion(),
'php_version' => phpversion(), 'php_version' => phpversion(),
'sqlite_version' => $sqliteVersion, 'sqlite_version' => $sqliteVersion,
'db_version' => $this->getDatabase()->migrations()->max('migration'), 'db_version' => $this->DB->migrations()->max('migration'),
'os' => php_uname('s') . ' ' . php_uname('r') . ' ' . php_uname('v') . ' ' . php_uname('m'), 'os' => php_uname('s') . ' ' . php_uname('r') . ' ' . php_uname('v') . ' ' . php_uname('m'),
'client' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown' 'client' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown'
]; ];

View File

@ -4,76 +4,22 @@ namespace Grocy\Services;
class BaseService class BaseService
{ {
private static $instances = []; public function __construct()
{
$this->DB = DatabaseService::GetInstance()->GetDbConnection();
}
public static function getInstance() private static $Instances = [];
protected $DB;
public static function GetInstance()
{ {
$className = get_called_class(); $className = get_called_class();
if (!isset(self::$instances[$className])) if (!isset(self::$Instances[$className]))
{ {
self::$instances[$className] = new $className(); self::$Instances[$className] = new $className();
} }
return self::$instances[$className]; return self::$Instances[$className];
}
protected function getBatteriesService()
{
return BatteriesService::getInstance();
}
protected function getChoresService()
{
return ChoresService::getInstance();
}
protected function getDatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getLocalizationService()
{
if (!defined('GROCY_LOCALE'))
{
define('GROCY_LOCALE', GROCY_DEFAULT_LOCALE);
}
return LocalizationService::getInstance(GROCY_LOCALE);
}
protected function getStockService()
{
return StockService::getInstance();
}
protected function getTasksService()
{
return TasksService::getInstance();
}
protected function getUsersService()
{
return UsersService::getInstance();
}
protected function getPrintService()
{
return PrintService::getInstance();
}
protected function getFilesService()
{
return FilesService::getInstance();
}
protected function getApplicationService()
{
return ApplicationService::getInstance();
} }
} }

View File

@ -11,10 +11,10 @@ class BatteriesService extends BaseService
throw new \Exception('Battery does not exist'); throw new \Exception('Battery does not exist');
} }
$battery = $this->getDatabase()->batteries($batteryId); $battery = $this->DB->batteries($batteryId);
$batteryChargeCyclesCount = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count(); $batteryChargeCyclesCount = $this->DB->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->count();
$batteryLastChargedTime = $this->getDatabase()->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time'); $batteryLastChargedTime = $this->DB->battery_charge_cycles()->where('battery_id = :1 AND undone = 0', $batteryId)->max('tracked_time');
$nextChargeTime = $this->getDatabase()->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time'); $nextChargeTime = $this->DB->batteries_current()->where('battery_id', $batteryId)->min('next_estimated_charge_time');
return [ return [
'battery' => $battery, 'battery' => $battery,
@ -26,8 +26,8 @@ class BatteriesService extends BaseService
public function GetCurrent() public function GetCurrent()
{ {
$batteries = $this->getDatabase()->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'); $batteries = $this->DB->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE');
$currentBatteries = $this->getDatabase()->batteries_current(); $currentBatteries = $this->DB->batteries_current();
foreach ($currentBatteries as $currentBattery) foreach ($currentBatteries as $currentBattery)
{ {
$currentBattery->battery = FindObjectInArrayByPropertyValue($batteries, 'id', $currentBattery->battery_id); $currentBattery->battery = FindObjectInArrayByPropertyValue($batteries, 'id', $currentBattery->battery_id);
@ -43,18 +43,18 @@ class BatteriesService extends BaseService
throw new \Exception('Battery does not exist'); throw new \Exception('Battery does not exist');
} }
$logRow = $this->getDatabase()->battery_charge_cycles()->createRow([ $logRow = $this->DB->battery_charge_cycles()->createRow([
'battery_id' => $batteryId, 'battery_id' => $batteryId,
'tracked_time' => $trackedTime 'tracked_time' => $trackedTime
]); ]);
$logRow->save(); $logRow->save();
return $this->getDatabase()->lastInsertId(); return $this->DB->lastInsertId();
} }
public function UndoChargeCycle($chargeCycleId) public function UndoChargeCycle($chargeCycleId)
{ {
$logRow = $this->getDatabase()->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch(); $logRow = $this->DB->battery_charge_cycles()->where('id = :1 AND undone = 0', $chargeCycleId)->fetch();
if ($logRow == null) if ($logRow == null)
{ {
@ -70,7 +70,7 @@ class BatteriesService extends BaseService
private function BatteryExists($batteryId) private function BatteryExists($batteryId)
{ {
$batteryRow = $this->getDatabase()->batteries()->where('id = :1', $batteryId)->fetch(); $batteryRow = $this->DB->batteries()->where('id = :1', $batteryId)->fetch();
return $batteryRow !== null; return $batteryRow !== null;
} }
} }

View File

@ -8,6 +8,7 @@ class CalendarService extends BaseService
{ {
public function __construct() public function __construct()
{ {
parent::__construct();
$this->UrlManager = new UrlManager(GROCY_BASE_URL); $this->UrlManager = new UrlManager(GROCY_BASE_URL);
} }
@ -15,15 +16,15 @@ class CalendarService extends BaseService
public function GetEvents() public function GetEvents()
{ {
$usersService = $this->getUsersService(); $usersService = UsersService::GetInstance();
$stockEvents = []; $stockEvents = [];
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
$products = $this->getDatabase()->products(); $products = $this->DB->products();
$titlePrefix = $this->getLocalizationService()->__t('Product due') . ': '; $titlePrefix = LocalizationService::GetInstance()->__t('Product due') . ': ';
foreach ($this->getStockService()->GetCurrentStock() as $currentStockEntry) foreach (StockService::GetInstance()->GetCurrentStock() as $currentStockEntry)
{ {
if ($currentStockEntry->amount > 0) if ($currentStockEntry->amount > 0)
{ {
@ -41,9 +42,9 @@ class CalendarService extends BaseService
$taskEvents = []; $taskEvents = [];
if (GROCY_FEATURE_FLAG_TASKS) if (GROCY_FEATURE_FLAG_TASKS)
{ {
$titlePrefix = $this->getLocalizationService()->__t('Task due') . ': '; $titlePrefix = LocalizationService::GetInstance()->__t('Task due') . ': ';
foreach ($this->getTasksService()->GetCurrent() as $currentTaskEntry) foreach (TasksService::GetInstance()->GetCurrent() as $currentTaskEntry)
{ {
$taskEvents[] = [ $taskEvents[] = [
'title' => $titlePrefix . $currentTaskEntry->name, 'title' => $titlePrefix . $currentTaskEntry->name,
@ -58,18 +59,18 @@ class CalendarService extends BaseService
$choreEvents = []; $choreEvents = [];
if (GROCY_FEATURE_FLAG_CHORES) if (GROCY_FEATURE_FLAG_CHORES)
{ {
$users = $this->getUsersService()->GetUsersAsDto(); $users = UsersService::GetInstance()->GetUsersAsDto();
$chores = $this->getDatabase()->chores()->where('active = 1'); $chores = $this->DB->chores()->where('active = 1');
$titlePrefix = $this->getLocalizationService()->__t('Chore due') . ': '; $titlePrefix = LocalizationService::GetInstance()->__t('Chore due') . ': ';
foreach ($this->getChoresService()->GetCurrent() as $currentChoreEntry) foreach (ChoresService::GetInstance()->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->getLocalizationService()->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')'; $assignedToText = ' (' . LocalizationService::GetInstance()->__t('assigned to %s', FindObjectInArrayByPropertyValue($users, 'id', $currentChoreEntry->next_execution_assigned_to_user_id)->display_name) . ')';
} }
$choreEvents[] = [ $choreEvents[] = [
@ -86,10 +87,10 @@ class CalendarService extends BaseService
$batteryEvents = []; $batteryEvents = [];
if (GROCY_FEATURE_FLAG_BATTERIES) if (GROCY_FEATURE_FLAG_BATTERIES)
{ {
$batteries = $this->getDatabase()->batteries()->where('active = 1'); $batteries = $this->DB->batteries()->where('active = 1');
$titlePrefix = $this->getLocalizationService()->__t('Battery charge cycle due') . ': '; $titlePrefix = LocalizationService::GetInstance()->__t('Battery charge cycle due') . ': ';
foreach ($this->getBatteriesService()->GetCurrent() as $currentBatteryEntry) foreach (BatteriesService::GetInstance()->GetCurrent() as $currentBatteryEntry)
{ {
$batteryEvents[] = [ $batteryEvents[] = [
'title' => $titlePrefix . FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name, 'title' => $titlePrefix . FindObjectInArrayByPropertyValue($batteries, 'id', $currentBatteryEntry->battery_id)->name,
@ -106,11 +107,11 @@ class CalendarService extends BaseService
$mealPlanProductEvents = []; $mealPlanProductEvents = [];
if (GROCY_FEATURE_FLAG_RECIPES_MEALPLAN) if (GROCY_FEATURE_FLAG_RECIPES_MEALPLAN)
{ {
$mealPlanSections = $this->getDatabase()->meal_plan_sections(); $mealPlanSections = $this->DB->meal_plan_sections();
$recipes = $this->getDatabase()->recipes()->where('type', 'normal'); $recipes = $this->DB->recipes()->where('type', 'normal');
$mealPlanDayRecipes = $this->getDatabase()->meal_plan()->where('type', 'recipe'); $mealPlanDayRecipes = $this->DB->meal_plan()->where('type', 'recipe');
$titlePrefix = $this->getLocalizationService()->__t('Meal plan recipe') . ': '; $titlePrefix = LocalizationService::GetInstance()->__t('Meal plan recipe') . ': ';
foreach ($mealPlanDayRecipes as $mealPlanDayRecipe) foreach ($mealPlanDayRecipes as $mealPlanDayRecipe)
{ {
$start = $mealPlanDayRecipe->day; $start = $mealPlanDayRecipe->day;
@ -138,8 +139,8 @@ class CalendarService extends BaseService
]; ];
} }
$mealPlanDayNotes = $this->getDatabase()->meal_plan()->where('type', 'note'); $mealPlanDayNotes = $this->DB->meal_plan()->where('type', 'note');
$titlePrefix = $this->getLocalizationService()->__t('Meal plan note') . ': '; $titlePrefix = LocalizationService::GetInstance()->__t('Meal plan note') . ': ';
foreach ($mealPlanDayNotes as $mealPlanDayNote) foreach ($mealPlanDayNotes as $mealPlanDayNote)
{ {
$start = $mealPlanDayNote->day; $start = $mealPlanDayNote->day;
@ -167,9 +168,9 @@ class CalendarService extends BaseService
]; ];
} }
$products = $this->getDatabase()->products(); $products = $this->DB->products();
$mealPlanDayProducts = $this->getDatabase()->meal_plan()->where('type', 'product'); $mealPlanDayProducts = $this->DB->meal_plan()->where('type', 'product');
$titlePrefix = $this->getLocalizationService()->__t('Meal plan product') . ': '; $titlePrefix = LocalizationService::GetInstance()->__t('Meal plan product') . ': ';
foreach ($mealPlanDayProducts as $mealPlanDayProduct) foreach ($mealPlanDayProducts as $mealPlanDayProduct)
{ {
$start = $mealPlanDayProduct->day; $start = $mealPlanDayProduct->day;

View File

@ -23,7 +23,7 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist'); throw new \Exception('Chore does not exist');
} }
$chore = $this->getDatabase()->chores($choreId); $chore = $this->DB->chores($choreId);
if (!empty($chore->rescheduled_next_execution_assigned_to_user_id)) if (!empty($chore->rescheduled_next_execution_assigned_to_user_id))
{ {
@ -31,11 +31,11 @@ class ChoresService extends BaseService
} }
else else
{ {
$choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time'); $choreLastTrackedTime = $this->DB->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->orderBy('row_created_timestamp', 'DESC')->fetch(); $lastChoreLogRow = $this->DB->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->orderBy('row_created_timestamp', 'DESC')->fetch();
$lastDoneByUserId = $lastChoreLogRow->done_by_user_id; $lastDoneByUserId = $lastChoreLogRow->done_by_user_id;
$users = $this->getUsersService()->GetUsersAsDto(); $users = UsersService::GetInstance()->GetUsersAsDto();
$assignedUsers = []; $assignedUsers = [];
foreach ($users as $user) foreach ($users as $user)
{ {
@ -88,7 +88,7 @@ class ChoresService extends BaseService
} }
elseif ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST) elseif ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST)
{ {
$row = $this->getDatabase()->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch(); $row = $this->DB->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;
@ -108,15 +108,15 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist'); throw new \Exception('Chore does not exist');
} }
$users = $this->getUsersService()->GetUsersAsDto(); $users = UsersService::GetInstance()->GetUsersAsDto();
$chore = $this->getDatabase()->chores($choreId); $chore = $this->DB->chores($choreId);
$choreTrackedCount = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0 AND skipped = 0', $choreId)->count(); $choreTrackedCount = $this->DB->chores_log()->where('chore_id = :1 AND undone = 0 AND skipped = 0', $choreId)->count();
$choreLastTrackedTime = $this->getDatabase()->chores_log()->where('chore_id = :1 AND undone = 0 AND skipped = 0', $choreId)->max('tracked_time'); $choreLastTrackedTime = $this->DB->chores_log()->where('chore_id = :1 AND undone = 0 AND skipped = 0', $choreId)->max('tracked_time');
$nextExecutionTime = $this->getDatabase()->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time'); $nextExecutionTime = $this->DB->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time');
$averageExecutionFrequency = $this->getDatabase()->chores_execution_average_frequency()->where('chore_id', $choreId)->min('average_frequency_hours'); $averageExecutionFrequency = $this->DB->chores_execution_average_frequency()->where('chore_id', $choreId)->min('average_frequency_hours');
$lastChoreLogRow = $this->getDatabase()->chores_log()->where('chore_id = :1 AND tracked_time = :2 AND undone = 0', $choreId, $choreLastTrackedTime)->fetch(); $lastChoreLogRow = $this->DB->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))
{ {
@ -142,9 +142,9 @@ class ChoresService extends BaseService
public function GetCurrent() public function GetCurrent()
{ {
$users = $this->getUsersService()->GetUsersAsDto(); $users = UsersService::GetInstance()->GetUsersAsDto();
$chores = $this->getDatabase()->chores_current(); $chores = $this->DB->chores_current();
foreach ($chores as $chore) foreach ($chores as $chore)
{ {
if (!empty($chore->next_execution_assigned_to_user_id)) if (!empty($chore->next_execution_assigned_to_user_id))
@ -167,13 +167,13 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist'); throw new \Exception('Chore does not exist');
} }
$userRow = $this->getDatabase()->users()->where('id = :1', $doneBy)->fetch(); $userRow = $this->DB->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->getDatabase()->chores($choreId); $chore = $this->DB->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';
@ -187,8 +187,8 @@ class ChoresService extends BaseService
} }
} }
$scheduledExecutionTime = $this->getDatabase()->chores_current()->where('chore_id = :1', $chore->id)->fetch()->next_estimated_execution_time; $scheduledExecutionTime = $this->DB->chores_current()->where('chore_id = :1', $chore->id)->fetch()->next_estimated_execution_time;
$logRow = $this->getDatabase()->chores_log()->createRow([ $logRow = $this->DB->chores_log()->createRow([
'chore_id' => $choreId, 'chore_id' => $choreId,
'tracked_time' => $trackedTime, 'tracked_time' => $trackedTime,
'done_by_user_id' => $doneBy, 'done_by_user_id' => $doneBy,
@ -196,12 +196,12 @@ class ChoresService extends BaseService
'scheduled_execution_time' => $scheduledExecutionTime 'scheduled_execution_time' => $scheduledExecutionTime
]); ]);
$logRow->save(); $logRow->save();
$lastInsertId = $this->getDatabase()->lastInsertId(); $lastInsertId = $this->DB->lastInsertId();
if ($chore->consume_product_on_execution == 1 && !empty($chore->product_id)) if ($chore->consume_product_on_execution == 1 && !empty($chore->product_id))
{ {
$transactionId = uniqid(); $transactionId = uniqid();
$this->getStockService()->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', null, null, $transactionId, true); StockService::GetInstance()->ConsumeProduct($chore->product_id, $chore->product_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', null, null, $transactionId, true);
} }
if (!empty($chore->rescheduled_date)) if (!empty($chore->rescheduled_date))
@ -225,7 +225,7 @@ class ChoresService extends BaseService
public function UndoChoreExecution($executionId) public function UndoChoreExecution($executionId)
{ {
$logRow = $this->getDatabase()->chores_log()->where('id = :1 AND undone = 0', $executionId)->fetch(); $logRow = $this->DB->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');
@ -257,26 +257,26 @@ class ChoresService extends BaseService
throw new \Exception('$choreIdToKeep cannot equal $choreIdToRemove'); throw new \Exception('$choreIdToKeep cannot equal $choreIdToRemove');
} }
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction(); DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try try
{ {
$choreToKeep = $this->getDatabase()->chores($choreIdToKeep); $choreToKeep = $this->DB->chores($choreIdToKeep);
$choreToRemove = $this->getDatabase()->chores($choreIdToRemove); $choreToRemove = $this->DB->chores($choreIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE chores_log SET chore_id = ' . $choreIdToKeep . ' WHERE chore_id = ' . $choreIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE chores_log SET chore_id = ' . $choreIdToKeep . ' WHERE chore_id = ' . $choreIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('DELETE FROM chores WHERE id = ' . $choreIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('DELETE FROM chores WHERE id = ' . $choreIdToRemove);
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
$this->getDatabaseService()->GetDbConnectionRaw()->rollback(); DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex; throw $ex;
} }
$this->getDatabaseService()->GetDbConnectionRaw()->commit(); DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
} }
private function ChoreExists($choreId) private function ChoreExists($choreId)
{ {
$choreRow = $this->getDatabase()->chores()->where('id = :1', $choreId)->fetch(); $choreRow = $this->DB->chores()->where('id = :1', $choreId)->fetch();
return $choreRow !== null; return $choreRow !== null;
} }
} }

View File

@ -12,7 +12,9 @@ class DatabaseMigrationService extends BaseService
public function MigrateDatabase() public function MigrateDatabase()
{ {
$this->getDatabaseService()->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))"); define('GROCY_DATABASE_MIGRATIONS_RUNNING', true);
DatabaseService::GetInstance()->ExecuteDbStatement("CREATE TABLE IF NOT EXISTS migrations (migration INTEGER NOT NULL PRIMARY KEY UNIQUE, execution_time_timestamp DATETIME DEFAULT (datetime('now', 'localtime')))");
$migrationFiles = []; $migrationFiles = [];
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file) foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
@ -38,20 +40,20 @@ class DatabaseMigrationService extends BaseService
if ($migrationCounter > 0) if ($migrationCounter > 0)
{ {
$this->getDatabaseService()->ExecuteDbStatement('VACUUM'); DatabaseService::GetInstance()->ExecuteDbStatement('VACUUM');
} }
} }
private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile, int &$migrationCounter) private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile, int &$migrationCounter)
{ {
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); $rowCount = DatabaseService::GetInstance()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if ($rowCount == 0 || $migrationId == self::EMERGENCY_MIGRATION_ID || $migrationId == self::DOALWAYS_MIGRATION_ID) if ($rowCount == 0 || $migrationId == self::EMERGENCY_MIGRATION_ID || $migrationId == self::DOALWAYS_MIGRATION_ID)
{ {
include $phpFile; include $phpFile;
if ($migrationId != self::EMERGENCY_MIGRATION_ID && $migrationId != self::DOALWAYS_MIGRATION_ID) if ($migrationId != self::EMERGENCY_MIGRATION_ID && $migrationId != self::DOALWAYS_MIGRATION_ID)
{ {
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); DatabaseService::GetInstance()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
$migrationCounter++; $migrationCounter++;
} }
} }
@ -59,28 +61,28 @@ class DatabaseMigrationService extends BaseService
private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql, int &$migrationCounter) private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql, int &$migrationCounter)
{ {
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn(); $rowCount = DatabaseService::GetInstance()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = ' . $migrationId)->fetchColumn();
if ($rowCount == 0 || $migrationId == self::EMERGENCY_MIGRATION_ID || $migrationId == self::DOALWAYS_MIGRATION_ID) if ($rowCount == 0 || $migrationId == self::EMERGENCY_MIGRATION_ID || $migrationId == self::DOALWAYS_MIGRATION_ID)
{ {
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction(); DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try try
{ {
$this->getDatabaseService()->ExecuteDbStatement($sql); DatabaseService::GetInstance()->ExecuteDbStatement($sql);
if ($migrationId != self::EMERGENCY_MIGRATION_ID && $migrationId != self::DOALWAYS_MIGRATION_ID) if ($migrationId != self::EMERGENCY_MIGRATION_ID && $migrationId != self::DOALWAYS_MIGRATION_ID)
{ {
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); DatabaseService::GetInstance()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
$migrationCounter++; $migrationCounter++;
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
$this->getDatabaseService()->GetDbConnectionRaw()->rollback(); DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex; throw $ex;
} }
$this->getDatabaseService()->GetDbConnectionRaw()->commit(); DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
} }
} }
} }

View File

@ -122,7 +122,7 @@ class DatabaseService
touch($this->GetDbFilePath(), strtotime($dateTime)); touch($this->GetDbFilePath(), strtotime($dateTime));
} }
public static function getInstance() public static function GetInstance()
{ {
if (self::$instance == null) if (self::$instance == null)
{ {

View File

@ -4,22 +4,16 @@ namespace Grocy\Services;
class DemoDataGeneratorService extends BaseService class DemoDataGeneratorService extends BaseService
{ {
public function __construct()
{
$this->LocalizationService = new LocalizationService(GROCY_DEFAULT_LOCALE);
}
protected $LocalizationService;
private $LastSupermarketId = 1; private $LastSupermarketId = 1;
public function PopulateDemoData($skip = false) public function PopulateDemoData($skip = false)
{ {
$rowCount = $this->getDatabaseService()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn(); $rowCount = DatabaseService::GetInstance()->ExecuteDbQuery('SELECT COUNT(*) FROM migrations WHERE migration = -1')->fetchColumn();
if ($rowCount == 0) if ($rowCount == 0)
{ {
if ($skip) if ($skip)
{ {
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (-1);'); DatabaseService::GetInstance()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (-1);');
return; return;
} }
@ -225,7 +219,7 @@ class DemoDataGeneratorService extends BaseService
INSERT INTO migrations (migration) VALUES (-1); INSERT INTO migrations (migration) VALUES (-1);
"; ";
$this->getDatabaseService()->ExecuteDbStatement($sql); DatabaseService::GetInstance()->ExecuteDbStatement($sql);
$stockTransactionId = uniqid(); $stockTransactionId = uniqid();
$stockService = new StockService(); $stockService = new StockService();
@ -323,7 +317,7 @@ class DemoDataGeneratorService extends BaseService
$choresService = new ChoresService(); $choresService = new ChoresService();
for ($i = 1; $i <= 25; $i++) for ($i = 1; $i <= 25; $i++)
{ {
foreach ($this->getDatabase()->chores() as $chore) foreach ($this->DB->chores() as $chore)
{ {
$hours = $chore->period_interval; $hours = $chore->period_interval;
if ($chore->period_type == 'weekly') if ($chore->period_type == 'weekly')
@ -341,7 +335,7 @@ class DemoDataGeneratorService extends BaseService
} }
$choresService->TrackChore(1, date('Y-m-d'), array_rand([1, 2, 3, 4]) + 1); $choresService->TrackChore(1, date('Y-m-d'), array_rand([1, 2, 3, 4]) + 1);
$choresService->TrackChore(4, date('Y-m-d'), array_rand([1, 2, 3, 4]) + 1); $choresService->TrackChore(4, date('Y-m-d'), array_rand([1, 2, 3, 4]) + 1);
$this->getDatabaseService()->ExecuteDbStatement("UPDATE chores SET rescheduled_date = DATE(DATE('now', 'localtime'), '+10 days') WHERE id = 6"); DatabaseService::GetInstance()->ExecuteDbStatement("UPDATE chores SET rescheduled_date = DATE(DATE('now', 'localtime'), '+10 days') WHERE id = 6");
$batteriesService = new BatteriesService(); $batteriesService = new BatteriesService();
$batteriesService->TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-720 days'))); $batteriesService->TrackChargeCycle(1, date('Y-m-d H:i:s', strtotime('-720 days')));
@ -427,13 +421,13 @@ class DemoDataGeneratorService extends BaseService
private function __n_sql($number, string $singularForm, string $pluralForm) private function __n_sql($number, string $singularForm, string $pluralForm)
{ {
$localizedText = $this->getLocalizationService()->__n($number, $singularForm, $pluralForm); $localizedText = LocalizationService::GetInstance()->__n($number, $singularForm, $pluralForm);
return str_replace("'", "''", $localizedText); return str_replace("'", "''", $localizedText);
} }
private function __t_sql(string $text) private function __t_sql(string $text)
{ {
$localizedText = $this->getLocalizationService()->__t($text, null); $localizedText = LocalizationService::GetInstance()->__t($text, null);
return str_replace("'", "''", $localizedText); return str_replace("'", "''", $localizedText);
} }
} }

View File

@ -10,6 +10,8 @@ class FilesService extends BaseService
public function __construct() public function __construct()
{ {
parent::__construct();
$this->StoragePath = GROCY_DATAPATH . '/storage'; $this->StoragePath = GROCY_DATAPATH . '/storage';
if (!file_exists($this->StoragePath)) if (!file_exists($this->StoragePath))
{ {

View File

@ -6,12 +6,13 @@ use Gettext\Translation;
use Gettext\Translations; use Gettext\Translations;
use Gettext\Translator; use Gettext\Translator;
class LocalizationService class LocalizationService extends BaseService
{ {
public function __construct(string $culture) public function __construct(string $culture)
{ {
$this->Culture = $culture; parent::__construct();
$this->Culture = $culture;
$this->LoadLocalizations($culture); $this->LoadLocalizations($culture);
} }
@ -111,8 +112,20 @@ class LocalizationService
} }
} }
public static function getInstance(string $culture) public static function GetInstance(string $culture = '')
{ {
if (empty($culture))
{
if (defined('GROCY_LOCALE'))
{
$culture = GROCY_LOCALE;
}
else
{
$culture = GROCY_DEFAULT_LOCALE;
}
}
if (!in_array($culture, self::$instanceMap)) if (!in_array($culture, self::$instanceMap))
{ {
self::$instanceMap[$culture] = new self($culture); self::$instanceMap[$culture] = new self($culture);
@ -121,16 +134,6 @@ class LocalizationService
return self::$instanceMap[$culture]; return self::$instanceMap[$culture];
} }
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getdatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
private function LoadLocalizations() private function LoadLocalizations()
{ {
$culture = $this->Culture; $culture = $this->Culture;
@ -147,11 +150,7 @@ class LocalizationService
$this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/userfield_types.pot')); $this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/userfield_types.pot'));
$this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/permissions.pot')); $this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/permissions.pot'));
$this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/locales.pot')); $this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/locales.pot'));
$this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/demo_data.pot'));
if (GROCY_MODE !== 'production')
{
$this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/demo_data.pot'));
}
} }
$this->Po = Translations::fromPoFile(__DIR__ . "/../localization/$culture/strings.po"); $this->Po = Translations::fromPoFile(__DIR__ . "/../localization/$culture/strings.po");
@ -191,7 +190,8 @@ class LocalizationService
$this->Po = $this->Po->mergeWith(Translations::fromPoFile(__DIR__ . "/../localization/$culture/locales.po")); $this->Po = $this->Po->mergeWith(Translations::fromPoFile(__DIR__ . "/../localization/$culture/locales.po"));
} }
if (GROCY_MODE !== 'production' && file_exists(__DIR__ . "/../localization/$culture/demo_data.po")) // Load demo data localizations also during database migrations since e.g. default quantity units are created localized by that
if ((GROCY_MODE !== 'production' || defined('GROCY_DATABASE_MIGRATIONS_RUNNING')) && file_exists(__DIR__ . "/../localization/$culture/demo_data.po"))
{ {
$this->Po = $this->Po->mergeWith(Translations::fromPoFile(__DIR__ . "/../localization/$culture/demo_data.po")); $this->Po = $this->Po->mergeWith(Translations::fromPoFile(__DIR__ . "/../localization/$culture/demo_data.po"));
} }
@ -204,7 +204,7 @@ class LocalizationService
$quantityUnits = null; $quantityUnits = null;
try try
{ {
$quantityUnits = $this->getDatabase()->quantity_units()->where('active = 1')->fetchAll(); $quantityUnits = $this->DB->quantity_units()->where('active = 1')->fetchAll();
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {

View File

@ -13,7 +13,7 @@ class RecipesService extends BaseService
public function AddNotFulfilledProductsToShoppingList($recipeId, $excludedProductIds = null) public function AddNotFulfilledProductsToShoppingList($recipeId, $excludedProductIds = null)
{ {
$recipe = $this->getDataBase()->recipes($recipeId); $recipe = $this->DB->recipes($recipeId);
$recipePositions = $this->GetRecipesPosResolved(); $recipePositions = $this->GetRecipesPosResolved();
if ($excludedProductIds == null) if ($excludedProductIds == null)
@ -25,7 +25,7 @@ class RecipesService extends BaseService
{ {
if ($recipePosition->recipe_id == $recipeId && !in_array($recipePosition->product_id, $excludedProductIds)) if ($recipePosition->recipe_id == $recipeId && !in_array($recipePosition->product_id, $excludedProductIds))
{ {
$product = $this->getDataBase()->products($recipePosition->product_id); $product = $this->DB->products($recipePosition->product_id);
$toOrderAmount = round(($recipePosition->missing_amount - $recipePosition->amount_on_shopping_list), 2); $toOrderAmount = round(($recipePosition->missing_amount - $recipePosition->amount_on_shopping_list), 2);
$quId = $product->qu_id_purchase; $quId = $product->qu_id_purchase;
@ -39,7 +39,7 @@ class RecipesService extends BaseService
// => Do the unit conversion here (if any) // => Do the unit conversion here (if any)
if ($recipePosition->only_check_single_unit_in_stock == 1) if ($recipePosition->only_check_single_unit_in_stock == 1)
{ {
$conversion = $this->getDatabase()->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $recipePosition->product_id, $recipePosition->qu_id, $product->qu_id_stock)->fetch(); $conversion = $this->DB->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $recipePosition->product_id, $recipePosition->qu_id, $product->qu_id_stock)->fetch();
if ($conversion != null) if ($conversion != null)
{ {
$toOrderAmount = $toOrderAmount * $conversion->factor; $toOrderAmount = $toOrderAmount * $conversion->factor;
@ -54,7 +54,7 @@ class RecipesService extends BaseService
if ($toOrderAmount > 0) if ($toOrderAmount > 0)
{ {
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $recipePosition->product_id)->fetch(); $alreadyExistingEntry = $this->DB->shopping_list()->where('product_id', $recipePosition->product_id)->fetch();
if ($alreadyExistingEntry) if ($alreadyExistingEntry)
{ {
// Update // Update
@ -65,7 +65,7 @@ class RecipesService extends BaseService
else else
{ {
// Insert // Insert
$shoppinglistRow = $this->getDataBase()->shopping_list()->createRow([ $shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $recipePosition->product_id, 'product_id' => $recipePosition->product_id,
'amount' => $toOrderAmount, 'amount' => $toOrderAmount,
'qu_id' => $quId 'qu_id' => $quId
@ -85,9 +85,9 @@ class RecipesService extends BaseService
} }
$transactionId = uniqid(); $transactionId = uniqid();
$recipePositions = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll(); $recipePositions = $this->DB->recipes_pos_resolved()->where('recipe_id', $recipeId)->fetchAll();
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction(); DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try try
{ {
foreach ($recipePositions as $recipePosition) foreach ($recipePositions as $recipePosition)
@ -100,52 +100,52 @@ class RecipesService extends BaseService
$amount = $recipePosition->stock_amount; $amount = $recipePosition->stock_amount;
} }
$this->getStockService()->ConsumeProduct($recipePosition->product_id, $amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true, true); StockService::GetInstance()->ConsumeProduct($recipePosition->product_id, $amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true, true);
} }
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
$this->getDatabaseService()->GetDbConnectionRaw()->rollback(); DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex; throw $ex;
} }
$this->getDatabaseService()->GetDbConnectionRaw()->commit(); DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
$recipe = $this->getDatabase()->recipes()->where('id = :1', $recipeId)->fetch(); $recipe = $this->DB->recipes()->where('id = :1', $recipeId)->fetch();
$productId = $recipe->product_id; $productId = $recipe->product_id;
$amount = $recipe->desired_servings; $amount = $recipe->desired_servings;
if ($recipe->type == self::RECIPE_TYPE_MEALPLAN_SHADOW) if ($recipe->type == self::RECIPE_TYPE_MEALPLAN_SHADOW)
{ {
// Use "Produces product" of the original recipe // Use "Produces product" of the original recipe
$mealPlanEntry = $this->getDatabase()->meal_plan()->where('id = :1', explode('#', $recipe->name)[1])->fetch(); $mealPlanEntry = $this->DB->meal_plan()->where('id = :1', explode('#', $recipe->name)[1])->fetch();
$recipe = $this->getDatabase()->recipes()->where('id = :1', $mealPlanEntry->recipe_id)->fetch(); $recipe = $this->DB->recipes()->where('id = :1', $mealPlanEntry->recipe_id)->fetch();
$productId = $recipe->product_id; $productId = $recipe->product_id;
$amount = $mealPlanEntry->recipe_servings; $amount = $mealPlanEntry->recipe_servings;
} }
if (!empty($productId)) if (!empty($productId))
{ {
$product = $this->getDatabase()->products()->where('id = :1', $productId)->fetch(); $product = $this->DB->products()->where('id = :1', $productId)->fetch();
$recipeResolvedRow = $this->getDatabase()->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch(); $recipeResolvedRow = $this->DB->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch();
$this->getStockService()->AddProduct($productId, $amount, null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), $recipeResolvedRow->costs_per_serving, null, null, $dummyTransactionId, $product->default_stock_label_type, true, $recipe->name); StockService::GetInstance()->AddProduct($productId, $amount, null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), $recipeResolvedRow->costs_per_serving, null, null, $dummyTransactionId, $product->default_stock_label_type, true, $recipe->name);
} }
} }
public function GetRecipesPosResolved() public function GetRecipesPosResolved()
{ {
$sql = 'SELECT * FROM recipes_pos_resolved'; $sql = 'SELECT * FROM recipes_pos_resolved';
return $this->getDataBaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return DatabaseService::GetInstance()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetRecipesResolved($customWhere = null): Result public function GetRecipesResolved($customWhere = null): Result
{ {
if ($customWhere == null) if ($customWhere == null)
{ {
return $this->getDatabase()->recipes_resolved(); return $this->DB->recipes_resolved();
} }
else else
{ {
return $this->getDatabase()->recipes_resolved()->where($customWhere); return $this->DB->recipes_resolved()->where($customWhere);
} }
} }
@ -156,19 +156,19 @@ class RecipesService extends BaseService
throw new \Exception('Recipe does not exist'); throw new \Exception('Recipe does not exist');
} }
$newName = $this->getLocalizationService()->__t('Copy of %s', $this->getDataBase()->recipes($recipeId)->name); $newName = LocalizationService::GetInstance()->__t('Copy of %s', $this->DB->recipes($recipeId)->name);
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO recipes (name, description, picture_file_name, base_servings, desired_servings, not_check_shoppinglist, type, product_id) SELECT :new_name, description, picture_file_name, base_servings, desired_servings, not_check_shoppinglist, type, product_id FROM recipes WHERE id = :recipe_id', ['recipe_id' => $recipeId, 'new_name' => $newName]); DatabaseService::GetInstance()->ExecuteDbStatement('INSERT INTO recipes (name, description, picture_file_name, base_servings, desired_servings, not_check_shoppinglist, type, product_id) SELECT :new_name, description, picture_file_name, base_servings, desired_servings, not_check_shoppinglist, type, product_id FROM recipes WHERE id = :recipe_id', ['recipe_id' => $recipeId, 'new_name' => $newName]);
$lastInsertId = $this->getDatabase()->lastInsertId(); $lastInsertId = $this->DB->lastInsertId();
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO recipes_pos (recipe_id, product_id, amount, note, qu_id, only_check_single_unit_in_stock, ingredient_group, not_check_stock_fulfillment, variable_amount, price_factor) SELECT :last_insert_id, product_id, amount, note, qu_id, only_check_single_unit_in_stock, ingredient_group, not_check_stock_fulfillment, variable_amount, price_factor FROM recipes_pos WHERE recipe_id = :recipe_id', ['recipe_id' => $recipeId, 'last_insert_id' => $lastInsertId]); DatabaseService::GetInstance()->ExecuteDbStatement('INSERT INTO recipes_pos (recipe_id, product_id, amount, note, qu_id, only_check_single_unit_in_stock, ingredient_group, not_check_stock_fulfillment, variable_amount, price_factor) SELECT :last_insert_id, product_id, amount, note, qu_id, only_check_single_unit_in_stock, ingredient_group, not_check_stock_fulfillment, variable_amount, price_factor FROM recipes_pos WHERE recipe_id = :recipe_id', ['recipe_id' => $recipeId, 'last_insert_id' => $lastInsertId]);
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO recipes_nestings (recipe_id, includes_recipe_id, servings) SELECT :last_insert_id, includes_recipe_id, servings FROM recipes_nestings WHERE recipe_id = :recipe_id', ['recipe_id' => $recipeId, 'last_insert_id' => $lastInsertId]); DatabaseService::GetInstance()->ExecuteDbStatement('INSERT INTO recipes_nestings (recipe_id, includes_recipe_id, servings) SELECT :last_insert_id, includes_recipe_id, servings FROM recipes_nestings WHERE recipe_id = :recipe_id', ['recipe_id' => $recipeId, 'last_insert_id' => $lastInsertId]);
return $lastInsertId; return $lastInsertId;
} }
private function RecipeExists($recipeId) private function RecipeExists($recipeId)
{ {
$recipeRow = $this->getDataBase()->recipes()->where('id = :1', $recipeId)->fetch(); $recipeRow = $this->DB->recipes()->where('id = :1', $recipeId)->fetch();
return $recipeRow !== null; return $recipeRow !== null;
} }
} }

View File

@ -17,7 +17,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->getDatabase()->sessions()->createRow([ $sessionRow = $this->DB->sessions()->createRow([
'user_id' => $userId, 'user_id' => $userId,
'session_key' => $newSessionKey, 'session_key' => $newSessionKey,
'expires' => $expires 'expires' => $expires
@ -29,15 +29,15 @@ class SessionService extends BaseService
public function GetDefaultUser() public function GetDefaultUser()
{ {
return $this->getDatabase()->users()->orderBy('id')->limit(1)->fetch(); return $this->DB->users()->orderBy('id')->limit(1)->fetch();
} }
public function GetUserBySessionKey($sessionKey) public function GetUserBySessionKey($sessionKey)
{ {
$sessionRow = $this->getDatabase()->sessions()->where('session_key', $sessionKey)->fetch(); $sessionRow = $this->DB->sessions()->where('session_key', $sessionKey)->fetch();
if ($sessionRow !== null) if ($sessionRow !== null)
{ {
return $this->getDatabase()->users($sessionRow->user_id); return $this->DB->users($sessionRow->user_id);
} }
return null; return null;
@ -51,16 +51,16 @@ class SessionService extends BaseService
} }
else else
{ {
$sessionRow = $this->getDatabase()->sessions()->where('session_key = :1 AND expires > :2', $sessionKey, date('Y-m-d H:i:s', time()))->fetch(); $sessionRow = $this->DB->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->getDatabaseService()->GetDbChangedTime(); $dbModTime = DatabaseService::GetInstance()->GetDbChangedTime();
$sessionRow->update([ $sessionRow->update([
'last_used' => date('Y-m-d H:i:s', time()) 'last_used' => date('Y-m-d H:i:s', time())
]); ]);
$this->getDatabaseService()->SetDbChangedTime($dbModTime); DatabaseService::GetInstance()->SetDbChangedTime($dbModTime);
return true; return true;
} }
@ -73,7 +73,7 @@ class SessionService extends BaseService
public function RemoveSession($sessionKey) public function RemoveSession($sessionKey)
{ {
$this->getDatabase()->sessions()->where('session_key', $sessionKey)->delete(); $this->DB->sessions()->where('session_key', $sessionKey)->delete();
} }
private function GenerateSessionKey() private function GenerateSessionKey()

View File

@ -28,10 +28,10 @@ class StockService extends BaseService
$missingProducts = $this->GetMissingProducts(); $missingProducts = $this->GetMissingProducts();
foreach ($missingProducts as $missingProduct) foreach ($missingProducts as $missingProduct)
{ {
$product = $this->getDatabase()->products()->where('id', $missingProduct->id)->fetch(); $product = $this->DB->products()->where('id', $missingProduct->id)->fetch();
$amountToAdd = round($missingProduct->amount_missing, 2); $amountToAdd = round($missingProduct->amount_missing, 2);
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch(); $alreadyExistingEntry = $this->DB->shopping_list()->where('product_id', $missingProduct->id)->fetch();
if ($alreadyExistingEntry) if ($alreadyExistingEntry)
{ {
// Update // Update
@ -46,7 +46,7 @@ class StockService extends BaseService
else else
{ {
// Insert // Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([ $shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $missingProduct->id, 'product_id' => $missingProduct->id,
'amount' => $amountToAdd, 'amount' => $amountToAdd,
'shopping_list_id' => $listId, 'shopping_list_id' => $listId,
@ -67,12 +67,12 @@ class StockService extends BaseService
$overdueProducts = $this->GetDueProducts(-1); $overdueProducts = $this->GetDueProducts(-1);
foreach ($overdueProducts as $overdueProduct) foreach ($overdueProducts as $overdueProduct)
{ {
$product = $this->getDatabase()->products()->where('id', $overdueProduct->product_id)->fetch(); $product = $this->DB->products()->where('id', $overdueProduct->product_id)->fetch();
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $overdueProduct->product_id)->fetch(); $alreadyExistingEntry = $this->DB->shopping_list()->where('product_id', $overdueProduct->product_id)->fetch();
if (!$alreadyExistingEntry) if (!$alreadyExistingEntry)
{ {
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([ $shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $overdueProduct->product_id, 'product_id' => $overdueProduct->product_id,
'amount' => 1, 'amount' => 1,
'shopping_list_id' => $listId, 'shopping_list_id' => $listId,
@ -93,12 +93,12 @@ class StockService extends BaseService
$expiredProducts = $this->GetExpiredProducts(); $expiredProducts = $this->GetExpiredProducts();
foreach ($expiredProducts as $expiredProduct) foreach ($expiredProducts as $expiredProduct)
{ {
$product = $this->getDatabase()->products()->where('id', $expiredProduct->product_id)->fetch(); $product = $this->DB->products()->where('id', $expiredProduct->product_id)->fetch();
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $expiredProduct->product_id)->fetch(); $alreadyExistingEntry = $this->DB->shopping_list()->where('product_id', $expiredProduct->product_id)->fetch();
if (!$alreadyExistingEntry) if (!$alreadyExistingEntry)
{ {
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([ $shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $expiredProduct->product_id, 'product_id' => $expiredProduct->product_id,
'amount' => 1, 'amount' => 1,
'shopping_list_id' => $listId, 'shopping_list_id' => $listId,
@ -151,7 +151,7 @@ class StockService extends BaseService
} }
else else
{ {
$location = $this->getDatabase()->locations()->where('id', $locationId)->fetch(); $location = $this->DB->locations()->where('id', $locationId)->fetch();
} }
if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING && $locationId !== null && $location->is_freezer == 1 && $productDetails->product->default_best_before_days_after_freezing >= -1) if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING && $locationId !== null && $location->is_freezer == 1 && $productDetails->product->default_best_before_days_after_freezing >= -1)
@ -193,7 +193,7 @@ class StockService extends BaseService
for ($i = 1; $i <= $amount; $i++) for ($i = 1; $i <= $amount; $i++)
{ {
$stockId = uniqid('x'); $stockId = uniqid('x');
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->DB->stock_log()->createRow([
'product_id' => $productId, 'product_id' => $productId,
'amount' => 1, 'amount' => 1,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@ -209,7 +209,7 @@ class StockService extends BaseService
]); ]);
$logRow->save(); $logRow->save();
$stockRow = $this->getDatabase()->stock()->createRow([ $stockRow = $this->DB->stock()->createRow([
'product_id' => $productId, 'product_id' => $productId,
'amount' => 1, 'amount' => 1,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@ -233,7 +233,7 @@ class StockService extends BaseService
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
$webhookData['due_date'] = $this->getLocalizationService()->__t('DD') . ': ' . $bestBeforeDate; $webhookData['due_date'] = LocalizationService::GetInstance()->__t('DD') . ': ' . $bestBeforeDate;
} }
$runner = new WebhookRunner(); $runner = new WebhookRunner();
@ -246,7 +246,7 @@ class StockService extends BaseService
// No or single label => one stock entry // No or single label => one stock entry
$stockId = uniqid(); $stockId = uniqid();
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->DB->stock_log()->createRow([
'product_id' => $productId, 'product_id' => $productId,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@ -262,7 +262,7 @@ class StockService extends BaseService
]); ]);
$logRow->save(); $logRow->save();
$stockRow = $this->getDatabase()->stock()->createRow([ $stockRow = $this->DB->stock()->createRow([
'product_id' => $productId, 'product_id' => $productId,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@ -286,7 +286,7 @@ class StockService extends BaseService
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
$webhookData['due_date'] = $this->getLocalizationService()->__t('DD') . ': ' . $bestBeforeDate; $webhookData['due_date'] = LocalizationService::GetInstance()->__t('DD') . ': ' . $bestBeforeDate;
} }
$runner = new WebhookRunner(); $runner = new WebhookRunner();
@ -318,10 +318,10 @@ class StockService extends BaseService
if ($quId == -1) if ($quId == -1)
{ {
$quId = $this->getDatabase()->products($productId)->qu_id_purchase; $quId = $this->DB->products($productId)->qu_id_purchase;
} }
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch(); $alreadyExistingEntry = $this->DB->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch();
if ($alreadyExistingEntry) if ($alreadyExistingEntry)
{ {
// Update // Update
@ -334,7 +334,7 @@ class StockService extends BaseService
else else
{ {
// Insert // Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([ $shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $productId, 'product_id' => $productId,
'amount' => $amount, 'amount' => $amount,
'qu_id' => $quId, 'qu_id' => $quId,
@ -354,11 +354,11 @@ class StockService extends BaseService
if ($doneOnly) if ($doneOnly)
{ {
$this->getDatabase()->shopping_list()->where('shopping_list_id = :1 AND IFNULL(done, 0) = 1', $listId)->delete(); $this->DB->shopping_list()->where('shopping_list_id = :1 AND IFNULL(done, 0) = 1', $listId)->delete();
} }
else else
{ {
$this->getDatabase()->shopping_list()->where('shopping_list_id = :1', $listId)->delete(); $this->DB->shopping_list()->where('shopping_list_id = :1', $listId)->delete();
} }
} }
@ -437,8 +437,8 @@ class StockService extends BaseService
if ($allowSubproductSubstitution && $stockEntry->product_id != $productId) if ($allowSubproductSubstitution && $stockEntry->product_id != $productId)
{ {
// A sub product will be used -> use QU conversions // A sub product will be used -> use QU conversions
$subProduct = $this->getDatabase()->products($stockEntry->product_id); $subProduct = $this->DB->products($stockEntry->product_id);
$conversion = $this->getDatabase()->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $stockEntry->product_id, $productDetails->product->qu_id_stock, $subProduct->qu_id_stock)->fetch(); $conversion = $this->DB->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $stockEntry->product_id, $productDetails->product->qu_id_stock, $subProduct->qu_id_stock)->fetch();
if ($conversion != null) if ($conversion != null)
{ {
$amount = $amount * $conversion->factor; $amount = $amount * $conversion->factor;
@ -448,7 +448,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount) if ($amount >= $stockEntry->amount)
{ {
// Take the whole stock entry // Take the whole stock entry
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->DB->stock_log()->createRow([
'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,
@ -484,7 +484,7 @@ class StockService extends BaseService
// Stock entry amount is > than needed amount -> split the stock entry resp. update the amount // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->DB->stock_log()->createRow([
'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,
@ -512,9 +512,9 @@ class StockService extends BaseService
} }
} }
if (boolval($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount'))) if (boolval(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount')))
{ {
$this->AddMissingProductsToShoppingList($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id')); $this->AddMissingProductsToShoppingList(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id'));
} }
return $transactionId; return $transactionId;
@ -527,7 +527,7 @@ class StockService extends BaseService
public function EditStockEntry(int $stockRowId, float $amount, $bestBeforeDate, $locationId, $shoppingLocationId, $price, $open, $purchasedDate, $note = null) public function EditStockEntry(int $stockRowId, float $amount, $bestBeforeDate, $locationId, $shoppingLocationId, $price, $open, $purchasedDate, $note = null)
{ {
$stockRow = $this->getDatabase()->stock()->where('id = :1', $stockRowId)->fetch(); $stockRow = $this->DB->stock()->where('id = :1', $stockRowId)->fetch();
if ($stockRow === null) if ($stockRow === null)
{ {
throw new \Exception('Stock does not exist'); throw new \Exception('Stock does not exist');
@ -535,7 +535,7 @@ class StockService extends BaseService
$correlationId = uniqid(); $correlationId = uniqid();
$transactionId = uniqid(); $transactionId = uniqid();
$logOldRowForStockUpdate = $this->getDatabase()->stock_log()->createRow([ $logOldRowForStockUpdate = $this->DB->stock_log()->createRow([
'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,
@ -576,7 +576,7 @@ class StockService extends BaseService
'note' => $note 'note' => $note
]); ]);
$logNewRowForStockUpdate = $this->getDatabase()->stock_log()->createRow([ $logNewRowForStockUpdate = $this->DB->stock_log()->createRow([
'product_id' => $stockRow->product_id, 'product_id' => $stockRow->product_id,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $bestBeforeDate, 'best_before_date' => $bestBeforeDate,
@ -616,7 +616,7 @@ class StockService extends BaseService
// Lookup was successful // Lookup was successful
if ($addFoundProduct === true) if ($addFoundProduct === true)
{ {
if ($this->getDatabase()->products()->where('name = :1', $pluginOutput['name'])->fetch() !== null) if ($this->DB->products()->where('name = :1', $pluginOutput['name'])->fetch() !== null)
{ {
throw new \Exception('Product "' . $pluginOutput['name'] . '" already exists'); throw new \Exception('Product "' . $pluginOutput['name'] . '" already exists');
} }
@ -633,7 +633,7 @@ class StockService extends BaseService
if (preg_match('/^https?:\/\//', $pluginOutput['__image_url'])) if (preg_match('/^https?:\/\//', $pluginOutput['__image_url']))
{ {
$webClient = new Client(); $webClient = new Client();
$response = $webClient->request('GET', $pluginOutput['__image_url'], ['headers' => ['User-Agent' => 'Grocy/' . $this->getApplicationService()->GetInstalledVersion()->Version . ' (https://grocy.info)']]); $response = $webClient->request('GET', $pluginOutput['__image_url'], ['headers' => ['User-Agent' => 'Grocy/' . ApplicationService::GetInstance()->GetInstalledVersion()->Version . ' (https://grocy.info)']]);
$fileExtension = pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION); $fileExtension = pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION);
// Fallback to Content-Type header if file extension is missing // Fallback to Content-Type header if file extension is missing
@ -656,7 +656,7 @@ class StockService extends BaseService
if (!empty($fileExtension) && !empty($imageData)) if (!empty($fileExtension) && !empty($imageData))
{ {
$fileName = $pluginOutput['__barcode'] . '.' . $fileExtension; $fileName = $pluginOutput['__barcode'] . '.' . $fileExtension;
file_put_contents($this->getFilesService()->GetFilePath('productpictures', $fileName), $imageData); file_put_contents(FilesService::GetInstance()->GetFilePath('productpictures', $fileName), $imageData);
$productData['picture_file_name'] = $fileName; $productData['picture_file_name'] = $fileName;
} }
} }
@ -666,17 +666,17 @@ class StockService extends BaseService
} }
} }
$newProductRow = $this->getDatabase()->products()->createRow($productData); $newProductRow = $this->DB->products()->createRow($productData);
$newProductRow->save(); $newProductRow->save();
$this->getDatabase()->product_barcodes()->createRow([ $this->DB->product_barcodes()->createRow([
'product_id' => $newProductRow->id, 'product_id' => $newProductRow->id,
'barcode' => $pluginOutput['__barcode'] 'barcode' => $pluginOutput['__barcode']
])->save(); ])->save();
if ($pluginOutput['qu_id_stock'] != $pluginOutput['qu_id_purchase']) if ($pluginOutput['qu_id_stock'] != $pluginOutput['qu_id_purchase'])
{ {
$this->getDatabase()->quantity_unit_conversions()->createRow([ $this->DB->quantity_unit_conversions()->createRow([
'product_id' => $newProductRow->id, 'product_id' => $newProductRow->id,
'from_qu_id' => $pluginOutput['qu_id_purchase'], 'from_qu_id' => $pluginOutput['qu_id_purchase'],
'to_qu_id' => $pluginOutput['qu_id_stock'], 'to_qu_id' => $pluginOutput['qu_id_stock'],
@ -694,8 +694,8 @@ class StockService extends BaseService
public function GetCurrentStock($customWhere = '') public function GetCurrentStock($customWhere = '')
{ {
$sql = 'SELECT * FROM stock_current ' . $customWhere; $sql = 'SELECT * FROM stock_current ' . $customWhere;
$currentStockMapped = $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_OBJ); $currentStockMapped = DatabaseService::GetInstance()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_OBJ);
$relevantProducts = $this->getDatabase()->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)'); $relevantProducts = $this->DB->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)');
foreach ($relevantProducts as $product) foreach ($relevantProducts as $product)
{ {
@ -715,13 +715,13 @@ class StockService extends BaseService
} }
$sql = 'SELECT IFNULL(sclc.location_id, p.location_id) AS location_id, p.id AS product_id, IFNULL(sclc.amount, 0) AS amount, IFNULL(sclc.amount_opened, 0) AS amount_opened FROM products p ' . $leftJoin . ' JOIN stock_current_location_content sclc ON sclc.product_id = p.id WHERE p.active = 1 ORDER BY p.name'; $sql = 'SELECT IFNULL(sclc.location_id, p.location_id) AS location_id, p.id AS product_id, IFNULL(sclc.amount, 0) AS amount, IFNULL(sclc.amount_opened, 0) AS amount_opened FROM products p ' . $leftJoin . ' JOIN stock_current_location_content sclc ON sclc.product_id = p.id WHERE p.active = 1 ORDER BY p.name';
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return DatabaseService::GetInstance()->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->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ); return DatabaseService::GetInstance()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
} }
public function GetDueProducts(int $days = 5, bool $excludeOverdue = false) public function GetDueProducts(int $days = 5, bool $excludeOverdue = false)
@ -743,9 +743,9 @@ class StockService extends BaseService
public function GetMissingProducts() public function GetMissingProducts()
{ {
$missingProductsResponse = $this->getDatabaseService()->ExecuteDbQuery('SELECT * FROM stock_missing_products')->fetchAll(\PDO::FETCH_OBJ); $missingProductsResponse = DatabaseService::GetInstance()->ExecuteDbQuery('SELECT * FROM stock_missing_products')->fetchAll(\PDO::FETCH_OBJ);
$relevantProducts = $this->getDatabase()->products()->where('id IN (SELECT id FROM stock_missing_products)'); $relevantProducts = $this->DB->products()->where('id IN (SELECT id FROM stock_missing_products)');
foreach ($relevantProducts as $product) foreach ($relevantProducts as $product)
{ {
FindObjectInArrayByPropertyValue($missingProductsResponse, 'id', $product->id)->product = $product; FindObjectInArrayByPropertyValue($missingProductsResponse, 'id', $product->id)->product = $product;
@ -773,19 +773,19 @@ class StockService extends BaseService
$stockCurrentRow->is_aggregated_amount = 0; $stockCurrentRow->is_aggregated_amount = 0;
} }
$detailsRow = $this->getDatabase()->uihelper_product_details()->where('id', $productId)->fetch(); $detailsRow = $this->DB->uihelper_product_details()->where('id', $productId)->fetch();
$product = $this->getDatabase()->products($productId); $product = $this->DB->products($productId);
$productBarcodes = $this->getDatabase()->product_barcodes()->where('product_id', $productId)->fetchAll(); $productBarcodes = $this->DB->product_barcodes()->where('product_id', $productId)->fetchAll();
$quPurchase = $this->getDatabase()->quantity_units($product->qu_id_purchase); $quPurchase = $this->DB->quantity_units($product->qu_id_purchase);
$quStock = $this->getDatabase()->quantity_units($product->qu_id_stock); $quStock = $this->DB->quantity_units($product->qu_id_stock);
$quConsume = $this->getDatabase()->quantity_units($product->qu_id_consume); $quConsume = $this->DB->quantity_units($product->qu_id_consume);
$quPrice = $this->getDatabase()->quantity_units($product->qu_id_price); $quPrice = $this->DB->quantity_units($product->qu_id_price);
$location = $this->getDatabase()->locations($product->location_id); $location = $this->DB->locations($product->location_id);
$defaultConsumeLocation = null; $defaultConsumeLocation = null;
if (!empty($product->default_consume_location_id)) if (!empty($product->default_consume_location_id))
{ {
$defaultConsumeLocation = $this->getDatabase()->locations($product->default_consume_location_id); $defaultConsumeLocation = $this->DB->locations($product->default_consume_location_id);
} }
return [ return [
@ -833,7 +833,7 @@ class StockService extends BaseService
return $gc->GetId(); return $gc->GetId();
} }
$potentialProduct = $this->getDatabase()->product_barcodes()->where('barcode = :1 COLLATE NOCASE', $barcode)->fetch(); $potentialProduct = $this->DB->product_barcodes()->where('barcode = :1 COLLATE NOCASE', $barcode)->fetch();
if ($potentialProduct === null) if ($potentialProduct === null)
{ {
throw new \Exception("No product with barcode $barcode found"); throw new \Exception("No product with barcode $barcode found");
@ -850,9 +850,9 @@ class StockService extends BaseService
} }
$returnData = []; $returnData = [];
$shoppingLocations = $this->getDatabase()->shopping_locations(); $shoppingLocations = $this->DB->shopping_locations();
$rows = $this->getDatabase()->products_price_history()->where('product_id = :1', $productId)->orderBy('purchased_date', 'DESC'); $rows = $this->DB->products_price_history()->where('product_id = :1', $productId)->orderBy('purchased_date', 'DESC');
foreach ($rows as $row) foreach ($rows as $row)
{ {
$returnData[] = [ $returnData[] = [
@ -879,7 +879,7 @@ class StockService extends BaseService
$sqlWhereAndOpen = 'AND open = 0'; $sqlWhereAndOpen = 'AND open = 0';
} }
return $this->getDatabase()->stock_next_use()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen); return $this->DB->stock_next_use()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen);
} }
public function GetLocationStockEntries($locationId) public function GetLocationStockEntries($locationId)
@ -889,7 +889,7 @@ class StockService extends BaseService
throw new \Exception('Location does not exist'); throw new \Exception('Location does not exist');
} }
return $this->getDatabase()->stock()->where('location_id', $locationId); return $this->DB->stock()->where('location_id', $locationId);
} }
public function GetProductStockEntriesForLocation($productId, $locationId, $excludeOpened = false, $allowSubproductSubstitution = false) public function GetProductStockEntriesForLocation($productId, $locationId, $excludeOpened = false, $allowSubproductSubstitution = false)
@ -906,12 +906,12 @@ class StockService extends BaseService
$sqlWhereProductId = '(product_id IN (SELECT sub_product_id FROM products_resolved WHERE parent_product_id = ' . $productId . ') OR product_id = ' . $productId . ')'; $sqlWhereProductId = '(product_id IN (SELECT sub_product_id FROM products_resolved WHERE parent_product_id = ' . $productId . ') OR product_id = ' . $productId . ')';
} }
return $this->getDatabase()->stock_current_locations()->where($sqlWhereProductId); return $this->DB->stock_current_locations()->where($sqlWhereProductId);
} }
public function GetStockEntry($entryId) public function GetStockEntry($entryId)
{ {
return $this->getDatabase()->stock()->where('id', $entryId)->fetch(); return $this->DB->stock()->where('id', $entryId)->fetch();
} }
public function InventoryProduct(int $productId, float $newAmount, $bestBeforeDate, $locationId = null, $price = null, $shoppingLocationId = null, $purchasedDate = null, $stockLabelType = 0, $note = null) public function InventoryProduct(int $productId, float $newAmount, $bestBeforeDate, $locationId = null, $price = null, $shoppingLocationId = null, $purchasedDate = null, $stockLabelType = 0, $note = null)
@ -985,7 +985,7 @@ class StockService extends BaseService
throw new \Exception('Product does not exist or is inactive'); throw new \Exception('Product does not exist or is inactive');
} }
$product = $this->getDatabase()->products($productId); $product = $this->DB->products($productId);
if ($product->disable_open == 1) if ($product->disable_open == 1)
{ {
@ -1045,7 +1045,7 @@ class StockService extends BaseService
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
$webhookData['due_date'] = $this->getLocalizationService()->__t('DD') . ': ' . $newBestBeforeDate; $webhookData['due_date'] = LocalizationService::GetInstance()->__t('DD') . ': ' . $newBestBeforeDate;
} }
$runner = new WebhookRunner(); $runner = new WebhookRunner();
@ -1056,8 +1056,8 @@ class StockService extends BaseService
if ($allowSubproductSubstitution && $stockEntry->product_id != $productId) if ($allowSubproductSubstitution && $stockEntry->product_id != $productId)
{ {
// A sub product will be used -> use QU conversions // A sub product will be used -> use QU conversions
$subProduct = $this->getDatabase()->products($stockEntry->product_id); $subProduct = $this->DB->products($stockEntry->product_id);
$conversion = $this->getDatabase()->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $stockEntry->product_id, $product->qu_id_stock, $subProduct->qu_id_stock)->fetch(); $conversion = $this->DB->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $stockEntry->product_id, $product->qu_id_stock, $subProduct->qu_id_stock)->fetch();
if ($conversion != null) if ($conversion != null)
{ {
$amount = $amount * $conversion->factor; $amount = $amount * $conversion->factor;
@ -1067,7 +1067,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount) if ($amount >= $stockEntry->amount)
{ {
// Mark the whole stock entry as opened // Mark the whole stock entry as opened
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->DB->stock_log()->createRow([
'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,
@ -1097,7 +1097,7 @@ class StockService extends BaseService
// Stock entry amount is > than needed amount -> split the stock entry // Stock entry amount is > than needed amount -> split the stock entry
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$newStockRow = $this->getDatabase()->stock()->createRow([ $newStockRow = $this->DB->stock()->createRow([
'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,
@ -1110,7 +1110,7 @@ class StockService extends BaseService
]); ]);
$newStockRow->save(); $newStockRow->save();
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->DB->stock_log()->createRow([
'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,
@ -1147,9 +1147,9 @@ class StockService extends BaseService
} }
} }
if (boolval($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount'))) if (boolval(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount')))
{ {
$this->AddMissingProductsToShoppingList($this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id')); $this->AddMissingProductsToShoppingList(UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'shopping_list_auto_add_below_min_stock_amount_list_id'));
} }
return $transactionId; return $transactionId;
@ -1162,12 +1162,12 @@ class StockService extends BaseService
throw new \Exception('Shopping list does not exist'); throw new \Exception('Shopping list does not exist');
} }
$productRow = $this->getDatabase()->shopping_list()->where('product_id = :1', $productId)->fetch(); $productRow = $this->DB->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))
{ {
$decimals = $this->getUsersService()->GetUserSetting(GROCY_USER_ID, 'stock_decimal_places_amounts'); $decimals = UsersService::GetInstance()->GetUserSetting(GROCY_USER_ID, 'stock_decimal_places_amounts');
$newAmount = $productRow->amount - $amount; $newAmount = $productRow->amount - $amount;
if ($newAmount < floatval('0.' . str_repeat('0', $decimals - ($decimals <= 0 ? 0 : 1)) . '1')) if ($newAmount < floatval('0.' . str_repeat('0', $decimals - ($decimals <= 0 ? 0 : 1)) . '1'))
@ -1190,14 +1190,14 @@ class StockService extends BaseService
$result_product = []; $result_product = [];
$result_quantity = []; $result_quantity = [];
$rowsShoppingListProducts = $this->getDatabase()->uihelper_shopping_list()->where('shopping_list_id = :1', $listId)->fetchAll(); $rowsShoppingListProducts = $this->DB->uihelper_shopping_list()->where('shopping_list_id = :1', $listId)->fetchAll();
foreach ($rowsShoppingListProducts as $row) foreach ($rowsShoppingListProducts as $row)
{ {
$isValidProduct = ($row->product_id != null && $row->product_id != ''); $isValidProduct = ($row->product_id != null && $row->product_id != '');
if ($isValidProduct) if ($isValidProduct)
{ {
$product = $this->getDatabase()->products()->where('id = :1', $row->product_id)->fetch(); $product = $this->DB->products()->where('id = :1', $row->product_id)->fetch();
$conversion = $this->getDatabase()->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $product->id, $product->qu_id_stock, $row->qu_id)->fetch(); $conversion = $this->DB->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $product->id, $product->qu_id_stock, $row->qu_id)->fetch();
$factor = 1.0; $factor = 1.0;
if ($conversion != null) if ($conversion != null)
@ -1298,7 +1298,7 @@ class StockService extends BaseService
$amount = abs($amount - $productDetails->stock_amount - $productDetails->product->tare_weight); $amount = abs($amount - $productDetails->stock_amount - $productDetails->product->tare_weight);
} }
$productStockAmountAtFromLocation = $this->getDatabase()->stock()->where('product_id = :1 AND location_id = :2', $productId, $locationIdFrom)->sum('amount'); $productStockAmountAtFromLocation = $this->DB->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)
@ -1326,8 +1326,8 @@ class StockService extends BaseService
$newBestBeforeDate = $stockEntry->best_before_date; $newBestBeforeDate = $stockEntry->best_before_date;
if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING) if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING)
{ {
$locationFrom = $this->getDatabase()->locations()->where('id', $locationIdFrom)->fetch(); $locationFrom = $this->DB->locations()->where('id', $locationIdFrom)->fetch();
$locationTo = $this->getDatabase()->locations()->where('id', $locationIdTo)->fetch(); $locationTo = $this->DB->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 ($locationFrom->is_freezer == 0 && $locationTo->is_freezer == 1 && ($productDetails->product->default_best_before_days_after_freezing > 0 || $productDetails->product->default_best_before_days_after_freezing == -1)) if ($locationFrom->is_freezer == 0 && $locationTo->is_freezer == 1 && ($productDetails->product->default_best_before_days_after_freezing > 0 || $productDetails->product->default_best_before_days_after_freezing == -1))
@ -1359,7 +1359,7 @@ class StockService extends BaseService
if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
$webhookData['due_date'] = $this->getLocalizationService()->__t('DD') . ': ' . $newBestBeforeDate; $webhookData['due_date'] = LocalizationService::GetInstance()->__t('DD') . ': ' . $newBestBeforeDate;
} }
$runner = new WebhookRunner(); $runner = new WebhookRunner();
@ -1371,7 +1371,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount) if ($amount >= $stockEntry->amount)
{ {
// Take the whole stock entry // Take the whole stock entry
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([ $logRowForLocationFrom = $this->DB->stock_log()->createRow([
'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,
@ -1389,7 +1389,7 @@ class StockService extends BaseService
]); ]);
$logRowForLocationFrom->save(); $logRowForLocationFrom->save();
$logRowForLocationTo = $this->getDatabase()->stock_log()->createRow([ $logRowForLocationTo = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount, 'amount' => $stockEntry->amount,
'best_before_date' => $newBestBeforeDate, 'best_before_date' => $newBestBeforeDate,
@ -1419,7 +1419,7 @@ class StockService extends BaseService
// Stock entry amount is > than needed amount -> split the stock entry resp. update the amount // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([ $logRowForLocationFrom = $this->DB->stock_log()->createRow([
'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,
@ -1437,7 +1437,7 @@ class StockService extends BaseService
]); ]);
$logRowForLocationFrom->save(); $logRowForLocationFrom->save();
$logRowForLocationTo = $this->getDatabase()->stock_log()->createRow([ $logRowForLocationTo = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $newBestBeforeDate, 'best_before_date' => $newBestBeforeDate,
@ -1461,7 +1461,7 @@ class StockService extends BaseService
]); ]);
// The transferred amount gets into a new stock entry // The transferred amount gets into a new stock entry
$stockEntryNew = $this->getDatabase()->stock()->createRow([ $stockEntryNew = $this->DB->stock()->createRow([
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $amount, 'amount' => $amount,
'best_before_date' => $newBestBeforeDate, 'best_before_date' => $newBestBeforeDate,
@ -1485,7 +1485,7 @@ class StockService extends BaseService
public function UndoBooking($bookingId, $skipCorrelatedBookings = false) public function UndoBooking($bookingId, $skipCorrelatedBookings = false)
{ {
$logRow = $this->getDatabase()->stock_log()->where('id = :1 AND undone = 0', $bookingId)->fetch(); $logRow = $this->DB->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');
@ -1494,7 +1494,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->getDatabase()->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll(); $correlatedBookings = $this->DB->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);
@ -1503,7 +1503,7 @@ class StockService extends BaseService
return; return;
} }
$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; $hasSubsequentBookings = $this->DB->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');
@ -1512,7 +1512,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->getDatabase()->stock()->where('stock_id', $logRow->stock_id); $stockRows = $this->DB->stock()->where('stock_id', $logRow->stock_id);
$stockRows->delete(); $stockRows->delete();
// Update log entry // Update log entry
@ -1524,7 +1524,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->getDatabase()->stock()->createRow([ $stockRow = $this->DB->stock()->createRow([
'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,
@ -1547,7 +1547,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->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); $stockRow = $this->DB->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');
@ -1575,10 +1575,10 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_FROM) elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_FROM)
{ {
// Add corresponding amount back to stock // Add corresponding amount back to stock
$stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); $stockRow = $this->DB->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
if ($stockRow === null) if ($stockRow === null)
{ {
$stockRow = $this->getDatabase()->stock()->createRow([ $stockRow = $this->DB->stock()->createRow([
'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,
@ -1607,7 +1607,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 stock entry // Remove opened flag from corresponding stock entry
$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 = $this->DB->stock()->where('stock_id = :1 AND amount = :2 AND purchased_date = :3', $logRow->stock_id, $logRow->amount, $logRow->purchased_date)->limit(1);
$stockRows->update([ $stockRows->update([
'open' => 0, 'open' => 0,
'opened_date' => null, 'opened_date' => null,
@ -1631,7 +1631,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->getDatabase()->stock()->where('id = :1', $logRow->stock_row_id)->fetch(); $stockRow = $this->DB->stock()->where('id = :1', $logRow->stock_row_id)->fetch();
if ($stockRow == null) if ($stockRow == null)
{ {
@ -1670,7 +1670,7 @@ class StockService extends BaseService
public function UndoTransaction($transactionId) public function UndoTransaction($transactionId)
{ {
$transactionBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll(); $transactionBookings = $this->DB->stock_log()->where('undone = 0 AND transaction_id = :1', $transactionId)->orderBy('id', 'DESC')->fetchAll();
if (count($transactionBookings) === 0) if (count($transactionBookings) === 0)
{ {
@ -1700,50 +1700,50 @@ class StockService extends BaseService
throw new \Exception('$productIdToKeep cannot equal $productIdToRemove'); throw new \Exception('$productIdToKeep cannot equal $productIdToRemove');
} }
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction(); DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try try
{ {
$productToKeep = $this->getDatabase()->products($productIdToKeep); $productToKeep = $this->DB->products($productIdToKeep);
$productToRemove = $this->getDatabase()->products($productIdToRemove); $productToRemove = $this->DB->products($productIdToRemove);
$conversion = $this->getDatabase()->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $productToRemove->id, $productToRemove->qu_id_stock, $productToKeep->qu_id_stock)->fetch(); $conversion = $this->DB->cache__quantity_unit_conversions_resolved()->where('product_id = :1 AND from_qu_id = :2 AND to_qu_id = :3', $productToRemove->id, $productToRemove->qu_id_stock, $productToKeep->qu_id_stock)->fetch();
$factor = 1.0; $factor = 1.0;
if ($conversion != null) if ($conversion != null)
{ {
$factor = $conversion->factor; $factor = $conversion->factor;
} }
$this->getDatabaseService()->ExecuteDbStatement('UPDATE stock SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE stock SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE stock_log SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE stock_log SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE product_barcodes SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE product_barcodes SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE quantity_unit_conversions SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE quantity_unit_conversions SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE recipes_pos SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE recipes_pos SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE recipes SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE recipes SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE meal_plan SET product_id = ' . $productIdToKeep . ', product_amount = product_amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE meal_plan SET product_id = ' . $productIdToKeep . ', product_amount = product_amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE shopping_list SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE shopping_list SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('DELETE FROM products WHERE id = ' . $productIdToRemove); DatabaseService::GetInstance()->ExecuteDbStatement('DELETE FROM products WHERE id = ' . $productIdToRemove);
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
$this->getDatabaseService()->GetDbConnectionRaw()->rollback(); DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex; throw $ex;
} }
$this->getDatabaseService()->GetDbConnectionRaw()->commit(); DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
} }
public function CompactStockEntries($productId = null) public function CompactStockEntries($productId = null)
{ {
if ($productId == null) if ($productId == null)
{ {
$splittedStockEntries = $this->getDatabase()->stock_splits(); $splittedStockEntries = $this->DB->stock_splits();
} }
else else
{ {
$splittedStockEntries = $this->getDatabase()->stock_splits()->where('product_id = :1', $productId); $splittedStockEntries = $this->DB->stock_splits()->where('product_id = :1', $productId);
} }
foreach ($splittedStockEntries as $splittedStockEntry) foreach ($splittedStockEntries as $splittedStockEntry)
{ {
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction(); DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try try
{ {
$stockIds = explode(',', $splittedStockEntry->stock_id_group); $stockIds = explode(',', $splittedStockEntry->stock_id_group);
@ -1751,8 +1751,8 @@ class StockService extends BaseService
{ {
if ($stockId != $splittedStockEntry->stock_id_to_keep) if ($stockId != $splittedStockEntry->stock_id_to_keep)
{ {
$this->getDatabaseService()->ExecuteDbStatement('UPDATE stock SET stock_id = \'' . $splittedStockEntry->stock_id_to_keep . '\' WHERE stock_id = \'' . $stockId . '\''); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE stock SET stock_id = \'' . $splittedStockEntry->stock_id_to_keep . '\' WHERE stock_id = \'' . $stockId . '\'');
$this->getDatabaseService()->ExecuteDbStatement('UPDATE stock_log SET stock_id = \'' . $splittedStockEntry->stock_id_to_keep . '\' WHERE stock_id = \'' . $stockId . '\''); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE stock_log SET stock_id = \'' . $splittedStockEntry->stock_id_to_keep . '\' WHERE stock_id = \'' . $stockId . '\'');
} }
} }
@ -1761,20 +1761,20 @@ class StockService extends BaseService
{ {
if ($stockEntryId != $splittedStockEntry->id_to_keep) if ($stockEntryId != $splittedStockEntry->id_to_keep)
{ {
$this->getDatabaseService()->ExecuteDbStatement('DELETE FROM stock WHERE id = ' . $stockEntryId); DatabaseService::GetInstance()->ExecuteDbStatement('DELETE FROM stock WHERE id = ' . $stockEntryId);
} }
else else
{ {
$this->getDatabaseService()->ExecuteDbStatement('UPDATE stock SET amount = ' . $splittedStockEntry->total_amount . ' WHERE id = ' . $splittedStockEntry->id_to_keep); DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE stock SET amount = ' . $splittedStockEntry->total_amount . ' WHERE id = ' . $splittedStockEntry->id_to_keep);
} }
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
$this->getDatabaseService()->GetDbConnectionRaw()->rollback(); DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex; throw $ex;
} }
$this->getDatabaseService()->GetDbConnectionRaw()->commit(); DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
} }
} }
@ -1792,12 +1792,12 @@ class StockService extends BaseService
if (file_exists($userPluginPath)) if (file_exists($userPluginPath))
{ {
require_once $userPluginPath; require_once $userPluginPath;
return new $pluginName($this->getDatabase()->locations()->where('active = 1')->fetchAll(), $this->getDatabase()->quantity_units()->where('active = 1')->fetchAll(), $this->getUsersService()->GetUserSettings(GROCY_USER_ID)); return new $pluginName($this->DB->locations()->where('active = 1')->fetchAll(), $this->DB->quantity_units()->where('active = 1')->fetchAll(), UsersService::GetInstance()->GetUserSettings(GROCY_USER_ID));
} }
elseif (file_exists($standardPluginPath)) elseif (file_exists($standardPluginPath))
{ {
require_once $standardPluginPath; require_once $standardPluginPath;
return new $pluginName($this->getDatabase()->locations()->where('active = 1')->fetchAll(), $this->getDatabase()->quantity_units()->where('active = 1')->fetchAll(), $this->getUsersService()->GetUserSettings(GROCY_USER_ID)); return new $pluginName($this->DB->locations()->where('active = 1')->fetchAll(), $this->DB->quantity_units()->where('active = 1')->fetchAll(), UsersService::GetInstance()->GetUserSettings(GROCY_USER_ID));
} }
else else
{ {
@ -1807,19 +1807,19 @@ class StockService extends BaseService
private function LocationExists($locationId) private function LocationExists($locationId)
{ {
$locationRow = $this->getDatabase()->locations()->where('id = :1', $locationId)->where('active = 1')->fetch(); $locationRow = $this->DB->locations()->where('id = :1', $locationId)->where('active = 1')->fetch();
return $locationRow !== null; return $locationRow !== null;
} }
private function ProductExists($productId) private function ProductExists($productId)
{ {
$productRow = $this->getDatabase()->products()->where('id = :1 and active = 1', $productId)->fetch(); $productRow = $this->DB->products()->where('id = :1 and active = 1', $productId)->fetch();
return $productRow !== null; return $productRow !== null;
} }
private function ShoppingListExists($listId) private function ShoppingListExists($listId)
{ {
$shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch(); $shoppingListRow = $this->DB->shopping_lists()->where('id = :1', $listId)->fetch();
return $shoppingListRow !== null; return $shoppingListRow !== null;
} }
} }

View File

@ -8,10 +8,10 @@ class TasksService extends BaseService
{ {
public function GetCurrent(): Result public function GetCurrent(): Result
{ {
$users = $this->getUsersService()->GetUsersAsDto(); $users = UsersService::GetInstance()->GetUsersAsDto();
$categories = $this->getDatabase()->task_categories()->where('active = 1'); $categories = $this->DB->task_categories()->where('active = 1');
$tasks = $this->getDatabase()->tasks_current(); $tasks = $this->DB->tasks_current();
foreach ($tasks as $task) foreach ($tasks as $task)
{ {
if (!empty($task->assigned_to_user_id)) if (!empty($task->assigned_to_user_id))
@ -43,7 +43,7 @@ class TasksService extends BaseService
throw new \Exception('Task does not exist'); throw new \Exception('Task does not exist');
} }
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch(); $taskRow = $this->DB->tasks()->where('id = :1', $taskId)->fetch();
$taskRow->update([ $taskRow->update([
'done' => 1, 'done' => 1,
'done_timestamp' => $doneTime 'done_timestamp' => $doneTime
@ -59,7 +59,7 @@ class TasksService extends BaseService
throw new \Exception('Task does not exist'); throw new \Exception('Task does not exist');
} }
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch(); $taskRow = $this->DB->tasks()->where('id = :1', $taskId)->fetch();
$taskRow->update([ $taskRow->update([
'done' => 0, 'done' => 0,
'done_timestamp' => null 'done_timestamp' => null
@ -70,7 +70,7 @@ class TasksService extends BaseService
private function TaskExists($taskId) private function TaskExists($taskId)
{ {
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch(); $taskRow = $this->DB->tasks()->where('id = :1', $taskId)->fetch();
return $taskRow !== null; return $taskRow !== null;
} }
} }

View File

@ -23,7 +23,7 @@ class UserfieldsService extends BaseService
public function GetAllFields() public function GetAllFields()
{ {
return $this->getDatabase()->userfields()->orderBy('name', 'COLLATE NOCASE')->fetchAll(); return $this->DB->userfields()->orderBy('name', 'COLLATE NOCASE')->fetchAll();
} }
public function GetAllValues($entity) public function GetAllValues($entity)
@ -34,16 +34,16 @@ class UserfieldsService extends BaseService
} }
$userfields = $this->GetFields($entity); $userfields = $this->GetFields($entity);
return $this->getDatabase()->userfield_values_resolved()->where('entity', $entity)->orderBy('name', 'COLLATE NOCASE')->fetchAll(); return $this->DB->userfield_values_resolved()->where('entity', $entity)->orderBy('name', 'COLLATE NOCASE')->fetchAll();
} }
public function GetEntities() public function GetEntities()
{ {
$exposedDefaultEntities = $this->getOpenApiSpec()->components->schemas->ExposedEntity->enum; $exposedDefaultEntities = $this->GetOpenApispec()->components->schemas->ExposedEntity->enum;
$userEntities = []; $userEntities = [];
$specialEntities = ['users']; $specialEntities = ['users'];
foreach ($this->getDatabase()->userentities()->orderBy('name', 'COLLATE NOCASE') as $userentity) foreach ($this->DB->userentities()->orderBy('name', 'COLLATE NOCASE') as $userentity)
{ {
$userEntities[] = 'userentity-' . $userentity->name; $userEntities[] = 'userentity-' . $userentity->name;
} }
@ -55,7 +55,7 @@ class UserfieldsService extends BaseService
public function GetField($fieldId) public function GetField($fieldId)
{ {
return $this->getDatabase()->userfields($fieldId); return $this->DB->userfields($fieldId);
} }
public function GetFieldTypes() public function GetFieldTypes()
@ -70,7 +70,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->getDatabase()->userfields()->where('entity', $entity)->orderBy('sort_number')->orderBy('name', 'COLLATE NOCASE')->fetchAll(); return $this->DB->userfields()->where('entity', $entity)->orderBy('sort_number')->orderBy('name', 'COLLATE NOCASE')->fetchAll();
} }
public function GetValues($entity, $objectId) public function GetValues($entity, $objectId)
@ -81,7 +81,7 @@ class UserfieldsService extends BaseService
} }
$userfields = $this->GetFields($entity); $userfields = $this->GetFields($entity);
$userfieldValues = $this->getDatabase()->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name', 'COLLATE NOCASE')->fetchAll(); $userfieldValues = $this->DB->userfield_values_resolved()->where('entity = :1 AND object_id = :2', $entity, $objectId)->orderBy('name', 'COLLATE NOCASE')->fetchAll();
$userfieldKeyValuePairs = []; $userfieldKeyValuePairs = [];
foreach ($userfields as $userfield) foreach ($userfields as $userfield)
@ -109,7 +109,7 @@ class UserfieldsService extends BaseService
foreach ($userfields as $key => $value) foreach ($userfields as $key => $value)
{ {
$fieldRow = $this->getDatabase()->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch(); $fieldRow = $this->DB->userfields()->where('entity = :1 AND name = :2', $entity, $key)->fetch();
if ($fieldRow === null) if ($fieldRow === null)
{ {
@ -118,27 +118,25 @@ class UserfieldsService extends BaseService
$fieldId = $fieldRow->id; $fieldId = $fieldRow->id;
$alreadyExistingEntry = $this->getDatabase()->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch(); $alreadyExistingEntry = $this->DB->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch();
if ($alreadyExistingEntry) if ($alreadyExistingEntry) // Update
{ // Update {$alreadyExistingEntry->update([
$alreadyExistingEntry->update([ 'value' => $value
'value' => $value ]);
]);
} }
else else // Insert
{ // Insert {$newRow = $this->DB->userfield_values()->createRow([
$newRow = $this->getDatabase()->userfield_values()->createRow([ 'field_id' => $fieldId,
'field_id' => $fieldId, 'object_id' => $objectId,
'object_id' => $objectId, 'value' => $value
'value' => $value ]);
]);
$newRow->save(); $newRow->save();
} }
} }
} }
protected function getOpenApispec() protected function GetOpenApispec()
{ {
if ($this->OpenApiSpec == null) if ($this->OpenApiSpec == null)
{ {

View File

@ -8,7 +8,7 @@ class UsersService extends BaseService
{ {
public function CreateUser(string $username, ?string $firstName, ?string $lastName, string $password, ?string $pictureFileName = null) public function CreateUser(string $username, ?string $firstName, ?string $lastName, string $password, ?string $pictureFileName = null)
{ {
$newUserRow = $this->getDatabase()->users()->createRow([ $newUserRow = $this->DB->users()->createRow([
'username' => $username, 'username' => $username,
'first_name' => $firstName, 'first_name' => $firstName,
'last_name' => $lastName, 'last_name' => $lastName,
@ -18,7 +18,7 @@ class UsersService extends BaseService
$newUserRow = $newUserRow->save(); $newUserRow = $newUserRow->save();
$permList = []; $permList = [];
foreach ($this->getDatabase()->permission_hierarchy()->where('name', GROCY_DEFAULT_PERMISSIONS)->fetchAll() as $perm) foreach ($this->DB->permission_hierarchy()->where('name', GROCY_DEFAULT_PERMISSIONS)->fetchAll() as $perm)
{ {
$permList[] = [ $permList[] = [
'user_id' => $newUserRow->id, 'user_id' => $newUserRow->id,
@ -26,14 +26,14 @@ class UsersService extends BaseService
]; ];
} }
$this->getDatabase()->user_permissions()->insert($permList); $this->DB->user_permissions()->insert($permList);
return $newUserRow; return $newUserRow;
} }
public function DeleteUser($userId) public function DeleteUser($userId)
{ {
$row = $this->getDatabase()->users($userId); $row = $this->DB->users($userId);
$row->delete(); $row->delete();
} }
@ -44,7 +44,7 @@ class UsersService extends BaseService
throw new \Exception('User does not exist'); throw new \Exception('User does not exist');
} }
$user = $this->getDatabase()->users($userId); $user = $this->DB->users($userId);
if ($password == null || empty($password)) if ($password == null || empty($password))
{ {
@ -81,7 +81,7 @@ class UsersService extends BaseService
} }
$value = null; $value = null;
$settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); $settingRow = $this->DB->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
if ($settingRow !== null) if ($settingRow !== null)
{ {
$value = $settingRow->value; $value = $settingRow->value;
@ -103,7 +103,7 @@ class UsersService extends BaseService
public function GetUserSettings($userId) public function GetUserSettings($userId)
{ {
$settings = []; $settings = [];
$settingRows = $this->getDatabase()->user_settings()->where('user_id = :1', $userId)->fetchAll(); $settingRows = $this->DB->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;
@ -116,7 +116,7 @@ class UsersService extends BaseService
public function GetUsersAsDto(): Result public function GetUsersAsDto(): Result
{ {
return $this->getDatabase()->users_dto(); return $this->DB->users_dto();
} }
public function SetUserSetting($userId, $settingKey, $settingValue) public function SetUserSetting($userId, $settingKey, $settingValue)
@ -127,7 +127,7 @@ class UsersService extends BaseService
} }
self::$UserSettingsCache[$userId][$settingKey] = $settingValue; self::$UserSettingsCache[$userId][$settingKey] = $settingValue;
$settingRow = $this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch(); $settingRow = $this->DB->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->fetch();
if ($settingRow !== null) if ($settingRow !== null)
{ {
$settingRow->update([ $settingRow->update([
@ -137,7 +137,7 @@ class UsersService extends BaseService
} }
else else
{ {
$settingRow = $this->getDatabase()->user_settings()->createRow([ $settingRow = $this->DB->user_settings()->createRow([
'user_id' => $userId, 'user_id' => $userId,
'key' => $settingKey, 'key' => $settingKey,
'value' => $settingValue 'value' => $settingValue
@ -154,12 +154,12 @@ class UsersService extends BaseService
} }
unset(self::$UserSettingsCache[$userId][$settingKey]); unset(self::$UserSettingsCache[$userId][$settingKey]);
$this->getDatabase()->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->delete(); $this->DB->user_settings()->where('user_id = :1 AND key = :2', $userId, $settingKey)->delete();
} }
private function UserExists($userId) private function UserExists($userId)
{ {
$userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch(); $userRow = $this->DB->users()->where('id = :1', $userId)->fetch();
return $userRow !== null; return $userRow !== null;
} }
} }