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
use Grocy\Services\DatabaseService;
use Grocy\Services\StockService;
$PRODUCTS = [3, 4, 5, 6, 7, 8];
@ -11,11 +12,11 @@ $days = -1;
while ($i <= 500)
{
$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());
$transactionId2 = $this->getStockService()->ConsumeProduct($productId, 1, false, StockService::TRANSACTION_TYPE_CONSUME);
$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 = 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'");
$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 = '$transactionId1'");
DatabaseService::GetInstance()->ExecuteDbStatement("UPDATE stock_log SET row_created_timestamp = DATETIME(row_created_timestamp, '$days days') WHERE transaction_id = '$transactionId2'");
$days--;
$i++;

View File

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

View File

@ -2,7 +2,9 @@
// 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"
$adminUserRow = $db->users()->where('username', 'admin')->fetch();

View File

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

View File

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

View File

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

View File

@ -1,7 +1,8 @@
<?php
namespace Grocy\Controllers;
namespace Grocy\Controllers\Api;
use Grocy\Services\CalendarService;
use Grocy\Services\ApiKeyService;
use Eluceo\iCal\Domain\Entity\Calendar;
use Eluceo\iCal\Domain\Entity\Event;
@ -20,7 +21,7 @@ class CalendarApiController extends BaseApiController
{
try
{
$events = $this->getCalendarService()->GetEvents();
$events = CalendarService::GetInstance()->GetEvents();
$minDate = null;
$maxDate = null;
@ -95,7 +96,7 @@ class CalendarApiController extends BaseApiController
try
{
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)

View File

@ -1,10 +1,11 @@
<?php
namespace Grocy\Controllers;
namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User;
use Grocy\Helpers\WebhookRunner;
use Grocy\Helpers\Grocycode;
use Grocy\Services\ChoresService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
@ -25,15 +26,15 @@ class ChoresApiController extends BaseApiController
if ($choreId === null)
{
$chores = $this->getDatabase()->chores();
$chores = $this->DB->chores();
foreach ($chores as $chore)
{
$this->getChoresService()->CalculateNextExecutionAssignment($chore->id);
ChoresService::GetInstance()->CalculateNextExecutionAssignment($chore->id);
}
}
else
{
$this->getChoresService()->CalculateNextExecutionAssignment($choreId);
ChoresService::GetInstance()->CalculateNextExecutionAssignment($choreId);
}
return $this->EmptyApiResponse($response);
@ -48,7 +49,7 @@ class ChoresApiController extends BaseApiController
{
try
{
return $this->ApiResponse($response, $this->getChoresService()->GetChoreDetails($args['choreId']));
return $this->ApiResponse($response, ChoresService::GetInstance()->GetChoreDetails($args['choreId']));
}
catch (\Exception $ex)
{
@ -58,7 +59,7 @@ class ChoresApiController extends BaseApiController
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)
@ -67,7 +68,7 @@ class ChoresApiController extends BaseApiController
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');
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)
{
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);
return $this->ApiResponse($response, $this->getDatabase()->chores_log($choreExecutionId));
$choreExecutionId = ChoresService::GetInstance()->TrackChore($args['choreId'], $trackedTime, $doneBy, $skipped);
return $this->ApiResponse($response, $this->DB->chores_log($choreExecutionId));
}
catch (\Exception $ex)
{
@ -105,9 +106,9 @@ class ChoresApiController extends BaseApiController
{
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);
}
catch (\Exception $ex)
@ -120,7 +121,7 @@ class ChoresApiController extends BaseApiController
{
try
{
$choreDetails = (object)$this->getChoresService()->GetChoreDetails($args['choreId']);
$choreDetails = (object)ChoresService::GetInstance()->GetChoreDetails($args['choreId']);
$webhookData = array_merge([
'chore' => $choreDetails->chore->name,
@ -143,7 +144,7 @@ class ChoresApiController extends BaseApiController
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
{
@ -152,7 +153,7 @@ class ChoresApiController extends BaseApiController
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);
}
catch (\Exception $ex)

View File

@ -1,6 +1,6 @@
<?php
namespace Grocy\Controllers;
namespace Grocy\Controllers\Api;
use Grocy\Services\FilesService;
use Psr\Http\Message\ResponseInterface as Response;
@ -14,7 +14,7 @@ class FilesApiController extends BaseApiController
{
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');
}
@ -28,7 +28,7 @@ class FilesApiController extends BaseApiController
throw new \Exception('Invalid filename');
}
$this->getFilesService()->DeleteFile($args['group'], $fileName);
FilesService::GetInstance()->DeleteFile($args['group'], $fileName);
return $this->EmptyApiResponse($response);
}
@ -42,13 +42,13 @@ class FilesApiController extends BaseApiController
{
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');
}
$fileName = $this->checkFileName($args['fileName']);
$filePath = $this->getFilePath($args['group'], $fileName, $request->getQueryParams());
$fileName = $this->CheckFileName($args['fileName']);
$filePath = $this->GetFilePath($args['group'], $fileName, $request->getQueryParams());
if (file_exists($filePath))
{
@ -72,14 +72,14 @@ class FilesApiController extends BaseApiController
{
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');
}
$fileInfo = explode('_', $args['fileName']);
$fileName = $this->checkFileName($fileInfo[1]);
$filePath = $this->getFilePath($args['group'], base64_decode($fileInfo[0]), $request->getQueryParams());
$fileName = $this->CheckFileName($fileInfo[1]);
$filePath = $this->GetFilePath($args['group'], base64_decode($fileInfo[0]), $request->getQueryParams());
if (file_exists($filePath))
{
@ -103,14 +103,14 @@ class FilesApiController extends BaseApiController
{
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');
}
$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)
{
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)))
{
@ -153,7 +153,7 @@ class FilesApiController extends BaseApiController
return $fileName;
}
protected function getFilePath(string $group, string $fileName, array $queryParams = [])
protected function GetFilePath(string $group, string $fileName, array $queryParams = [])
{
$forceServeAs = null;
if (isset($queryParams['force_serve_as']) && !empty($queryParams['force_serve_as']))
@ -175,11 +175,11 @@ class FilesApiController extends BaseApiController
$bestFitWidth = $queryParams['best_fit_width'];
}
$filePath = $this->getFilesService()->DownscaleImage($group, $fileName, $bestFitHeight, $bestFitWidth);
$filePath = FilesService::GetInstance()->DownscaleImage($group, $fileName, $bestFitHeight, $bestFitWidth);
}
else
{
$filePath = $this->getFilesService()->GetFilePath($group, $fileName);
$filePath = FilesService::GetInstance()->GetFilePath($group, $fileName);
}
return $filePath;

View File

@ -1,8 +1,11 @@
<?php
namespace Grocy\Controllers;
namespace Grocy\Controllers\Api;
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\ServerRequestInterface as Request;
@ -12,30 +15,30 @@ class GenericEntityApiController extends BaseApiController
{
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')
{
User::checkPermission($request, User::PERMISSION_RECIPES);
User::CheckPermission($request, User::PERMISSION_RECIPES);
}
elseif ($args['entity'] == 'meal_plan')
{
User::checkPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
User::CheckPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
}
elseif ($args['entity'] == 'equipment')
{
User::checkPermission($request, User::PERMISSION_EQUIPMENT);
User::CheckPermission($request, User::PERMISSION_EQUIPMENT);
}
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->IsEntityWithEditRequiresAdmin($args['entity']))
{
User::checkPermission($request, User::PERMISSION_ADMIN);
User::CheckPermission($request, User::PERMISSION_ADMIN);
}
$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)');
}
$newRow = $this->getDatabase()->{$args['entity']}()->createRow($requestBody);
$newRow = $this->DB->{$args['entity']}()->createRow($requestBody);
$newRow->save();
$newObjectId = $this->getDatabase()->lastInsertId();
$newObjectId = $this->DB->lastInsertId();
// 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, [
@ -76,19 +79,19 @@ class GenericEntityApiController extends BaseApiController
{
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')
{
User::checkPermission($request, User::PERMISSION_RECIPES);
User::CheckPermission($request, User::PERMISSION_RECIPES);
}
elseif ($args['entity'] == 'meal_plan')
{
User::checkPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
User::CheckPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
}
elseif ($args['entity'] == 'equipment')
{
User::checkPermission($request, User::PERMISSION_EQUIPMENT);
User::CheckPermission($request, User::PERMISSION_EQUIPMENT);
}
elseif ($args['entity'] == 'api_keys')
{
@ -96,17 +99,17 @@ class GenericEntityApiController extends BaseApiController
}
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->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)
{
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')
{
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')
{
User::checkPermission($request, User::PERMISSION_RECIPES);
User::CheckPermission($request, User::PERMISSION_RECIPES);
}
elseif ($args['entity'] == 'meal_plan')
{
User::checkPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
User::CheckPermission($request, User::PERMISSION_RECIPES_MEALPLAN);
}
elseif ($args['entity'] == 'equipment')
{
User::checkPermission($request, User::PERMISSION_EQUIPMENT);
User::CheckPermission($request, User::PERMISSION_EQUIPMENT);
}
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->IsEntityWithEditRequiresAdmin($args['entity']))
{
User::checkPermission($request, User::PERMISSION_ADMIN);
User::CheckPermission($request, User::PERMISSION_ADMIN);
}
$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)');
}
$row = $this->getDatabase()->{$args['entity']}($args['objectId']);
$row = $this->DB->{$args['entity']}($args['objectId']);
if ($row == null)
{
return $this->GenericErrorResponse($response, 'Object not found', 400);
@ -170,9 +173,9 @@ class GenericEntityApiController extends BaseApiController
$row->update($requestBody);
// 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);
@ -195,7 +198,7 @@ class GenericEntityApiController extends BaseApiController
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)
{
return $this->GenericErrorResponse($response, 'Object not found', 404);
@ -207,7 +210,7 @@ class GenericEntityApiController extends BaseApiController
{
$referencingId = $object->stock_id;
}
$userfields = $this->getUserfieldsService()->GetValues($args['entity'], $referencingId);
$userfields = UserfieldsService::GetInstance()->GetValues($args['entity'], $referencingId);
if (count($userfields) === 0)
{
$userfields = null;
@ -224,12 +227,12 @@ class GenericEntityApiController extends BaseApiController
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)
{
$allUserfieldValues = $this->getUserfieldsService()->GetAllValues($args['entity']);
$allUserfieldValues = UserfieldsService::GetInstance()->GetAllValues($args['entity']);
foreach ($objects as $object)
{
@ -265,7 +268,7 @@ class GenericEntityApiController extends BaseApiController
{
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)
{
@ -275,7 +278,7 @@ class GenericEntityApiController extends BaseApiController
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);
@ -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)');
}
$this->getUserfieldsService()->SetValues($args['entity'], $args['objectId'], $requestBody);
UserfieldsService::GetInstance()->SetValues($args['entity'], $args['objectId'], $requestBody);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -297,26 +300,26 @@ class GenericEntityApiController extends BaseApiController
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)
{
return in_array($entity, $this->getOpenApiSpec()->components->schemas->ExposedEntityNoListing->enum);
return in_array($entity, $this->GetOpenApispec()->components->schemas->ExposedEntityNoListing->enum);
}
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)
{
return in_array($entity, $this->getOpenApiSpec()->components->schemas->ExposedEntityNoDelete->enum);
return in_array($entity, $this->GetOpenApispec()->components->schemas->ExposedEntityNoDelete->enum);
}
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
namespace Grocy\Controllers;
namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User;
use Grocy\Services\ApiKeyService;
use Grocy\Services\ApplicationService;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
@ -17,15 +19,15 @@ class OpenApiController extends BaseApiController
$selectedKeyId = $request->getQueryParams()['key'];
}
$apiKeys = $this->getDatabase()->api_keys();
if (!User::hasPermissions(User::PERMISSION_ADMIN))
$apiKeys = $this->DB->api_keys();
if (!User::HasPermissions(User::PERMISSION_ADMIN))
{
$apiKeys = $apiKeys->where('user_id', GROCY_USER_ID);
}
return $this->renderPage($response, 'manageapikeys', [
return $this->RenderPage($response, 'manageapikeys', [
'apiKeys' => $apiKeys,
'users' => $this->getDatabase()->users(),
'users' => $this->DB->users(),
'selectedKeyId' => $selectedKeyId
]);
}
@ -38,16 +40,16 @@ class OpenApiController extends BaseApiController
$description = $request->getQueryParams()['description'];
}
$newApiKey = $this->getApiKeyService()->CreateApiKey(ApiKeyService::API_KEY_TYPE_DEFAULT, $description);
$newApiKeyId = $this->getApiKeyService()->GetApiKeyId($newApiKey);
$newApiKey = ApiKeyService::GetInstance()->CreateApiKey(ApiKeyService::API_KEY_TYPE_DEFAULT, $description);
$newApiKeyId = ApiKeyService::GetInstance()->GetApiKeyId($newApiKey);
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl("/manageapikeys?key=$newApiKeyId"));
}
public function DocumentationSpec(Request $request, Response $response, array $args)
{
$spec = $this->getOpenApiSpec();
$spec = $this->GetOpenApispec();
$applicationService = $this->getApplicationService();
$applicationService = ApplicationService::GetInstance();
$versionInfo = $applicationService->GetInstalledVersion();
$spec->info->version = $versionInfo->Version;
$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;
;
foreach ($this->getUserfieldsService()->GetEntities() as $userEntity)
foreach (UserfieldsService::GetInstance()->GetEntities() as $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)
{
return $this->render($response, 'openapiui');
return $this->Render($response, 'openapiui');
}
}

View File

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

View File

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

View File

@ -1,8 +1,9 @@
<?php
namespace Grocy\Controllers;
namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User;
use Grocy\Services\LocalizationService;
use Grocy\Services\StockService;
use Grocy\Helpers\WebhookRunner;
use Grocy\Helpers\Grocycode;
@ -13,7 +14,7 @@ class StockApiController extends BaseApiController
{
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
{
@ -26,7 +27,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']);
}
$this->getStockService()->AddMissingProductsToShoppingList($listId);
StockService::GetInstance()->AddMissingProductsToShoppingList($listId);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -37,7 +38,7 @@ class StockApiController extends BaseApiController
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
{
@ -50,7 +51,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']);
}
$this->getStockService()->AddOverdueProductsToShoppingList($listId);
StockService::GetInstance()->AddOverdueProductsToShoppingList($listId);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -61,7 +62,7 @@ class StockApiController extends BaseApiController
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
{
@ -74,7 +75,7 @@ class StockApiController extends BaseApiController
$listId = intval($requestBody['list_id']);
}
$this->getStockService()->AddExpiredProductsToShoppingList($listId);
StockService::GetInstance()->AddExpiredProductsToShoppingList($listId);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -85,7 +86,7 @@ class StockApiController extends BaseApiController
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);
@ -149,7 +150,7 @@ class StockApiController extends BaseApiController
$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;
return $this->StockTransactions($request, $response, $args);
@ -164,7 +165,7 @@ class StockApiController extends BaseApiController
{
try
{
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
$args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
return $this->AddProduct($request, $response, $args);
}
catch (\Exception $ex)
@ -175,7 +176,7 @@ class StockApiController extends BaseApiController
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
{
@ -217,7 +218,7 @@ class StockApiController extends BaseApiController
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);
}
catch (\Exception $ex)
@ -228,7 +229,7 @@ class StockApiController extends BaseApiController
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
{
@ -246,7 +247,7 @@ class StockApiController extends BaseApiController
$doneOnly = boolval($requestBody['done_only']);
}
$this->getStockService()->ClearShoppingList($listId, $doneOnly);
StockService::GetInstance()->ClearShoppingList($listId, $doneOnly);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -257,7 +258,7 @@ class StockApiController extends BaseApiController
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);
@ -316,7 +317,7 @@ class StockApiController extends BaseApiController
}
$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;
return $this->StockTransactions($request, $response, $args);
}
@ -330,7 +331,7 @@ class StockApiController extends BaseApiController
{
try
{
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
$args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
if (Grocycode::Validate($args['barcode']))
{
@ -353,7 +354,7 @@ class StockApiController extends BaseApiController
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)
@ -365,10 +366,10 @@ class StockApiController extends BaseApiController
$nextXDays = $request->getQueryParams()['due_soon_days'];
}
$dueProducts = $this->getStockService()->GetDueProducts($nextXDays, true);
$overdueProducts = $this->getStockService()->GetDueProducts(-1);
$expiredProducts = $this->getStockService()->GetExpiredProducts();
$missingProducts = $this->getStockService()->GetMissingProducts();
$dueProducts = StockService::GetInstance()->GetDueProducts($nextXDays, true);
$overdueProducts = StockService::GetInstance()->GetDueProducts(-1);
$expiredProducts = StockService::GetInstance()->GetExpiredProducts();
$missingProducts = StockService::GetInstance()->GetMissingProducts();
return $this->ApiResponse($response, [
'due_products' => $dueProducts,
'overdue_products' => $overdueProducts,
@ -379,7 +380,7 @@ class StockApiController extends BaseApiController
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);
@ -425,7 +426,7 @@ class StockApiController extends BaseApiController
$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;
return $this->StockTransactions($request, $response, $args);
}
@ -437,7 +438,7 @@ class StockApiController extends BaseApiController
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
{
@ -447,7 +448,7 @@ class StockApiController extends BaseApiController
$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)
{
@ -457,7 +458,7 @@ class StockApiController extends BaseApiController
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);
@ -515,7 +516,7 @@ class StockApiController extends BaseApiController
$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;
return $this->StockTransactions($request, $response, $args);
}
@ -529,7 +530,7 @@ class StockApiController extends BaseApiController
{
try
{
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
$args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
return $this->InventoryProduct($request, $response, $args);
}
catch (\Exception $ex)
@ -540,7 +541,7 @@ class StockApiController extends BaseApiController
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);
@ -569,7 +570,7 @@ class StockApiController extends BaseApiController
}
$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;
return $this->StockTransactions($request, $response, $args);
}
@ -583,7 +584,7 @@ class StockApiController extends BaseApiController
{
try
{
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
$args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
if (Grocycode::Validate($args['barcode']))
{
@ -608,7 +609,7 @@ class StockApiController extends BaseApiController
{
try
{
return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($args['productId']));
return $this->ApiResponse($response, StockService::GetInstance()->GetProductDetails($args['productId']));
}
catch (\Exception $ex)
{
@ -620,8 +621,8 @@ class StockApiController extends BaseApiController
{
try
{
$productId = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
return $this->ApiResponse($response, $this->getStockService()->GetProductDetails($productId));
$productId = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
return $this->ApiResponse($response, StockService::GetInstance()->GetProductDetails($productId));
}
catch (\Exception $ex)
{
@ -633,7 +634,7 @@ class StockApiController extends BaseApiController
{
try
{
return $this->ApiResponse($response, $this->getStockService()->GetProductPriceHistory($args['productId']));
return $this->ApiResponse($response, StockService::GetInstance()->GetProductPriceHistory($args['productId']));
}
catch (\Exception $ex)
{
@ -649,12 +650,12 @@ class StockApiController extends BaseApiController
$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)
{
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)
@ -665,14 +666,14 @@ class StockApiController extends BaseApiController
$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)
{
try
{
$productDetails = (object)$this->getStockService()->GetProductDetails($args['productId']);
$productDetails = (object)StockService::GetInstance()->GetProductDetails($args['productId']);
$webhookData = array_merge([
'product' => $productDetails->product->name,
@ -697,8 +698,8 @@ class StockApiController extends BaseApiController
{
try
{
$stockEntry = $this->getDatabase()->stock()->where('id', $args['entryId'])->fetch();
$productDetails = (object)$this->getStockService()->GetProductDetails($stockEntry->product_id);
$stockEntry = $this->DB->stock()->where('id', $args['entryId'])->fetch();
$productDetails = (object)StockService::GetInstance()->GetProductDetails($stockEntry->product_id);
$webhookData = array_merge([
'product' => $productDetails->product->name,
@ -709,7 +710,7 @@ class StockApiController extends BaseApiController
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)
@ -727,7 +728,7 @@ class StockApiController extends BaseApiController
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
{
@ -757,7 +758,7 @@ class StockApiController extends BaseApiController
throw new \Exception('No product id was supplied');
}
$this->getStockService()->RemoveProductFromShoppingList($productId, $amount, $listId);
StockService::GetInstance()->RemoveProductFromShoppingList($productId, $amount, $listId);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -770,7 +771,7 @@ class StockApiController extends BaseApiController
{
try
{
$stockLogRow = $this->getDatabase()->stock_log($args['bookingId']);
$stockLogRow = $this->DB->stock_log($args['bookingId']);
if ($stockLogRow === null)
{
@ -787,14 +788,14 @@ class StockApiController extends BaseApiController
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)
{
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)
{
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)
{
User::checkPermission($request, User::PERMISSION_STOCK_TRANSFER);
User::CheckPermission($request, User::PERMISSION_STOCK_TRANSFER);
$requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -843,7 +844,7 @@ class StockApiController extends BaseApiController
$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;
return $this->StockTransactions($request, $response, $args);
}
@ -857,7 +858,7 @@ class StockApiController extends BaseApiController
{
try
{
$args['productId'] = $this->getStockService()->GetProductIdFromBarcode($args['barcode']);
$args['productId'] = StockService::GetInstance()->GetProductIdFromBarcode($args['barcode']);
if (Grocycode::Validate($args['barcode']))
{
@ -880,11 +881,11 @@ class StockApiController extends BaseApiController
public function UndoBooking(Request $request, Response $response, array $args)
{
User::checkPermission($request, User::PERMISSION_STOCK_EDIT);
User::CheckPermission($request, User::PERMISSION_STOCK_EDIT);
try
{
$this->ApiResponse($response, $this->getStockService()->UndoBooking($args['bookingId']));
$this->ApiResponse($response, StockService::GetInstance()->UndoBooking($args['bookingId']));
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -895,11 +896,11 @@ class StockApiController extends BaseApiController
public function UndoTransaction(Request $request, Response $response, array $args)
{
User::checkPermission($request, User::PERMISSION_STOCK_EDIT);
User::CheckPermission($request, User::PERMISSION_STOCK_EDIT);
try
{
$this->ApiResponse($response, $this->getStockService()->UndoTransaction($args['transactionId']));
$this->ApiResponse($response, StockService::GetInstance()->UndoTransaction($args['transactionId']));
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -910,7 +911,7 @@ class StockApiController extends BaseApiController
public function MergeProducts(Request $request, Response $response, array $args)
{
User::checkPermission($request, User::PERMISSION_STOCK_EDIT);
User::CheckPermission($request, User::PERMISSION_STOCK_EDIT);
try
{
@ -919,7 +920,7 @@ class StockApiController extends BaseApiController
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);
}
catch (\Exception $ex)

View File

@ -1,7 +1,10 @@
<?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\ServerRequestInterface as Request;
@ -37,13 +40,13 @@ class SystemApiController extends BaseApiController
public function GetDbChangedTime(Request $request, Response $response, array $args)
{
return $this->ApiResponse($response, [
'changed_time' => $this->getDatabaseService()->GetDbChangedTime()
'changed_time' => DatabaseService::GetInstance()->GetDbChangedTime()
]);
}
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)
@ -62,7 +65,7 @@ class SystemApiController extends BaseApiController
$offset = $params['offset'];
}
return $this->ApiResponse($response, $this->getApplicationService()->GetSystemTime($offset));
return $this->ApiResponse($response, ApplicationService::GetInstance()->GetSystemTime($offset));
}
catch (\Exception $ex)
{
@ -78,7 +81,7 @@ class SystemApiController extends BaseApiController
{
$requestBody = $this->GetParsedAndFilteredRequestBody($request);
$this->getLocalizationService()->CheckAndAddMissingTranslationToPot($requestBody['text']);
LocalizationService::GetInstance()->CheckAndAddMissingTranslationToPot($requestBody['text']);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -90,6 +93,6 @@ class SystemApiController extends BaseApiController
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
namespace Grocy\Controllers;
namespace Grocy\Controllers\Api;
use Grocy\Controllers\Users\User;
use Grocy\Services\TasksService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
@ -10,12 +11,12 @@ class TasksApiController extends BaseApiController
{
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)
{
User::checkPermission($request, User::PERMISSION_TASKS_MARK_COMPLETED);
User::CheckPermission($request, User::PERMISSION_TASKS_MARK_COMPLETED);
$requestBody = $this->GetParsedAndFilteredRequestBody($request);
@ -28,7 +29,7 @@ class TasksApiController extends BaseApiController
$doneTime = $requestBody['done_time'];
}
$this->getTasksService()->MarkTaskAsCompleted($args['taskId'], $doneTime);
TasksService::GetInstance()->MarkTaskAsCompleted($args['taskId'], $doneTime);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)
@ -39,11 +40,11 @@ class TasksApiController extends BaseApiController
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
{
$this->getTasksService()->UndoTask($args['taskId']);
TasksService::GetInstance()->UndoTask($args['taskId']);
return $this->EmptyApiResponse($response);
}
catch (\Exception $ex)

View File

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

View File

@ -3,20 +3,9 @@
namespace Grocy\Controllers;
use Grocy\Controllers\Users\User;
use Grocy\Services\ApiKeyService;
use Grocy\Services\ApplicationService;
use Grocy\Services\BatteriesService;
use Grocy\Services\CalendarService;
use Grocy\Services\ChoresService;
use Grocy\Services\DatabaseService;
use Grocy\Services\FilesService;
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 DI\Container;
@ -26,104 +15,21 @@ class BaseController
{
$this->AppContainer = $container;
$this->View = $container->get('view');
$this->DB = DatabaseService::GetInstance()->GetDbConnection();
}
protected $AppContainer;
protected $View;
protected $DB;
protected function getApiKeyService()
{
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 = [])
protected function Render($response, $viewName, $data = [])
{
$container = $this->AppContainer;
$versionInfo = $this->getApplicationService()->GetInstalledVersion();
$versionInfo = ApplicationService::GetInstance()->GetInstalledVersion();
$this->View->set('version', $versionInfo->Version);
$localizationService = $this->getLocalizationService();
$localizationService = LocalizationService::GetInstance();
$this->View->set('__t', function (string $text, ...$placeholderValues) use ($localizationService)
{
return $localizationService->__t($text, $placeholderValues);
@ -169,7 +75,7 @@ class BaseController
{
$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)
{
$defaultMinAmount = 1;
@ -183,15 +89,15 @@ class BaseController
$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
{
$usersService = $this->getUsersService();
$usersService = UsersService::GetInstance();
if (defined('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...
}
return $this->render($response, $viewName, $data);
return $this->Render($response, $viewName, $data);
}
}

View File

@ -3,6 +3,9 @@
namespace Grocy\Controllers;
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\ServerRequestInterface as Request;
@ -14,40 +17,40 @@ class BatteriesController extends BaseController
{
if (isset($request->getQueryParams()['include_disabled']))
{
$batteries = $this->getDatabase()->batteries()->orderBy('name', 'COLLATE NOCASE');
$batteries = $this->DB->batteries()->orderBy('name', 'COLLATE NOCASE');
}
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,
'userfields' => $this->getUserfieldsService()->GetFields('batteries'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries')
'userfields' => UserfieldsService::GetInstance()->GetFields('batteries'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('batteries')
]);
}
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)
{
if ($args['batteryId'] == 'new')
{
return $this->renderPage($response, 'batteryform', [
return $this->RenderPage($response, 'batteryform', [
'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('batteries')
'userfields' => UserfieldsService::GetInstance()->GetFields('batteries')
]);
}
else
{
return $this->renderPage($response, 'batteryform', [
'battery' => $this->getDatabase()->batteries($args['batteryId']),
return $this->RenderPage($response, 'batteryform', [
'battery' => $this->DB->batteries($args['batteryId']),
'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";
}
return $this->renderPage($response, 'batteriesjournal', [
'chargeCycles' => $this->getDatabase()->battery_charge_cycles()->where($where)->orderBy('tracked_time', 'DESC'),
'batteries' => $this->getDatabase()->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('battery_charge_cycles'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('battery_charge_cycles')
return $this->RenderPage($response, 'batteriesjournal', [
'chargeCycles' => $this->DB->battery_charge_cycles()->where($where)->orderBy('tracked_time', 'DESC'),
'batteries' => $this->DB->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => UserfieldsService::GetInstance()->GetFields('battery_charge_cycles'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('battery_charge_cycles')
]);
}
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'];
$batteries = $this->getDatabase()->batteries()->where('active = 1');
$currentBatteries = $this->getBatteriesService()->GetCurrent();
$batteries = $this->DB->batteries()->where('active = 1');
$currentBatteries = BatteriesService::GetInstance()->GetCurrent();
foreach ($currentBatteries as $currentBattery)
{
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,
'current' => $currentBatteries,
'nextXDays' => $nextXDays,
'userfields' => $this->getUserfieldsService()->GetFields('batteries'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('batteries')
'userfields' => UserfieldsService::GetInstance()->GetFields('batteries'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('batteries')
]);
}
public function TrackChargeCycle(Request $request, Response $response, array $args)
{
return $this->renderPage($response, 'batterytracking', [
'batteries' => $this->getDatabase()->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => $this->getUserfieldsService()->GetFields('battery_charge_cycles')
return $this->RenderPage($response, 'batterytracking', [
'batteries' => $this->DB->batteries()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'userfields' => UserfieldsService::GetInstance()->GetFields('battery_charge_cycles')
]);
}

View File

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

View File

@ -3,6 +3,9 @@
namespace Grocy\Controllers;
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\ServerRequestInterface as Request;
@ -12,30 +15,30 @@ class ChoresController extends BaseController
public function ChoreEditForm(Request $request, Response $response, array $args)
{
$usersService = $this->getUsersService();
$usersService = UsersService::GetInstance();
$users = $usersService->GetUsersAsDto();
if ($args['choreId'] == 'new')
{
return $this->renderPage($response, 'choreform', [
return $this->RenderPage($response, 'choreform', [
'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'),
'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'),
'users' => $users,
'products' => $this->getDatabase()->products()->orderBy('name', 'COLLATE NOCASE')
'products' => $this->DB->products()->orderBy('name', 'COLLATE NOCASE')
]);
}
else
{
return $this->renderPage($response, 'choreform', [
'chore' => $this->getDatabase()->chores($args['choreId']),
return $this->RenderPage($response, 'choreform', [
'chore' => $this->DB->chores($args['choreId']),
'periodTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_PERIOD_TYPE_'),
'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'assignmentTypes' => GetClassConstants('\Grocy\Services\ChoresService', 'CHORE_ASSIGNMENT_TYPE_'),
'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']))
{
$chores = $this->getDatabase()->chores()->orderBy('name', 'COLLATE NOCASE');
$chores = $this->DB->chores()->orderBy('name', 'COLLATE NOCASE');
}
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,
'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores')
'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('chores')
]);
}
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)
@ -82,22 +85,22 @@ class ChoresController extends BaseController
$where .= " AND chore_id = $choreId";
}
return $this->renderPage($response, 'choresjournal', [
'choresLog' => $this->getDatabase()->chores_log()->where($where)->orderBy('tracked_time', 'DESC'),
'chores' => $this->getDatabase()->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('chores_log'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores_log')
return $this->RenderPage($response, 'choresjournal', [
'choresLog' => $this->DB->chores_log()->where($where)->orderBy('tracked_time', 'DESC'),
'chores' => $this->DB->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->DB->users()->orderBy('username'),
'userfields' => UserfieldsService::GetInstance()->GetFields('chores_log'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('chores_log')
]);
}
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'];
$chores = $this->getDatabase()->chores()->orderBy('name', 'COLLATE NOCASE');
$currentChores = $this->getChoresService()->GetCurrent();
$chores = $this->DB->chores()->orderBy('name', 'COLLATE NOCASE');
$currentChores = ChoresService::GetInstance()->GetCurrent();
foreach ($currentChores as $currentChore)
{
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,
'currentChores' => $currentChores,
'nextXDays' => $nextXDays,
'userfields' => $this->getUserfieldsService()->GetFields('chores'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('chores'),
'userfields' => UserfieldsService::GetInstance()->GetFields('chores'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('chores'),
'users' => $usersService->GetUsersAsDto()
]);
}
public function TrackChoreExecution(Request $request, Response $response, array $args)
{
return $this->renderPage($response, 'choretracking', [
'chores' => $this->getDatabase()->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('chores_log'),
return $this->RenderPage($response, 'choretracking', [
'chores' => $this->DB->chores()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->DB->users()->orderBy('username'),
'userfields' => UserfieldsService::GetInstance()->GetFields('chores_log'),
]);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,6 +2,9 @@
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\ServerRequestInterface as Request;
@ -9,16 +12,16 @@ class TasksController extends BaseController
{
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'];
if (isset($request->getQueryParams()['include_done']))
{
$tasks = $this->getDatabase()->tasks()->orderBy('name', 'COLLATE NOCASE');
$tasks = $this->DB->tasks()->orderBy('name', 'COLLATE NOCASE');
}
else
{
$tasks = $this->getTasksService()->GetCurrent();
$tasks = TasksService::GetInstance()->GetCurrent();
}
foreach ($tasks as $task)
@ -41,13 +44,13 @@ class TasksController extends BaseController
}
}
return $this->renderPage($response, 'tasks', [
return $this->RenderPage($response, 'tasks', [
'tasks' => $tasks,
'nextXDays' => $nextXDays,
'taskCategories' => $this->getDatabase()->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users(),
'userfields' => $this->getUserfieldsService()->GetFields('tasks'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('tasks')
'taskCategories' => $this->DB->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->DB->users(),
'userfields' => UserfieldsService::GetInstance()->GetFields('tasks'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('tasks')
]);
}
@ -55,17 +58,17 @@ class TasksController extends BaseController
{
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
{
$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,
'userfields' => $this->getUserfieldsService()->GetFields('task_categories'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('task_categories')
'userfields' => UserfieldsService::GetInstance()->GetFields('task_categories'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('task_categories')
]);
}
@ -73,17 +76,17 @@ class TasksController extends BaseController
{
if ($args['categoryId'] == 'new')
{
return $this->renderPage($response, 'taskcategoryform', [
return $this->RenderPage($response, 'taskcategoryform', [
'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('task_categories')
'userfields' => UserfieldsService::GetInstance()->GetFields('task_categories')
]);
}
else
{
return $this->renderPage($response, 'taskcategoryform', [
'category' => $this->getDatabase()->task_categories($args['categoryId']),
return $this->RenderPage($response, 'taskcategoryform', [
'category' => $this->DB->task_categories($args['categoryId']),
'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')
{
return $this->renderPage($response, 'taskform', [
return $this->RenderPage($response, 'taskform', [
'mode' => 'create',
'taskCategories' => $this->getDatabase()->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('tasks')
'taskCategories' => $this->DB->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->DB->users()->orderBy('username'),
'userfields' => UserfieldsService::GetInstance()->GetFields('tasks')
]);
}
else
{
return $this->renderPage($response, 'taskform', [
'task' => $this->getDatabase()->tasks($args['taskId']),
return $this->RenderPage($response, 'taskform', [
'task' => $this->DB->tasks($args['taskId']),
'mode' => 'edit',
'taskCategories' => $this->getDatabase()->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->getDatabase()->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('tasks')
'taskCategories' => $this->DB->task_categories()->where('active = 1')->orderBy('name', 'COLLATE NOCASE'),
'users' => $this->DB->users()->orderBy('username'),
'userfields' => UserfieldsService::GetInstance()->GetFields('tasks')
]);
}
}
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()
{
$this->db = DatabaseService::getInstance()->GetDbConnection();
$this->DB = DatabaseService::GetInstance()->GetDbConnection();
}
protected $db;
protected $DB;
public static function PermissionList()
{
$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();
if (!$user->hasPermission($permission))
if (!$user->HasPermission($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();
foreach ($permissions as $permission)
{
if (!$user->hasPermission($permission))
if (!$user->HasPermission($permission))
{
return false;
}
@ -85,8 +85,8 @@ class User
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;
use Grocy\Controllers\Users\User;
use Grocy\Services\UserfieldsService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
@ -10,10 +11,10 @@ class UsersController extends BaseController
{
public function PermissionList(Request $request, Response $response, array $args)
{
User::checkPermission($request, User::PERMISSION_USERS_READ);
return $this->renderPage($response, 'userpermissions', [
'user' => $this->getDatabase()->users($args['userId']),
'permissions' => $this->getDatabase()->uihelper_user_permissions()
User::CheckPermission($request, User::PERMISSION_USERS_READ);
return $this->RenderPage($response, 'userpermissions', [
'user' => $this->DB->users($args['userId']),
'permissions' => $this->DB->uihelper_user_permissions()
->where('parent IS NULL')->where('user_id', $args['userId'])
]);
}
@ -22,35 +23,35 @@ class UsersController extends BaseController
{
if ($args['userId'] == 'new')
{
User::checkPermission($request, User::PERMISSION_USERS_CREATE);
return $this->renderPage($response, 'userform', [
User::CheckPermission($request, User::PERMISSION_USERS_CREATE);
return $this->RenderPage($response, 'userform', [
'mode' => 'create',
'userfields' => $this->getUserfieldsService()->GetFields('users')
'userfields' => UserfieldsService::GetInstance()->GetFields('users')
]);
}
else
{
if ($args['userId'] == GROCY_USER_ID)
{
User::checkPermission($request, User::PERMISSION_USERS_EDIT_SELF);
User::CheckPermission($request, User::PERMISSION_USERS_EDIT_SELF);
}
else
{
User::checkPermission($request, User::PERMISSION_USERS_EDIT);
User::CheckPermission($request, User::PERMISSION_USERS_EDIT);
}
return $this->renderPage($response, 'userform', [
'user' => $this->getDatabase()->users($args['userId']),
return $this->RenderPage($response, 'userform', [
'user' => $this->DB->users($args['userId']),
'mode' => 'edit',
'userfields' => $this->getUserfieldsService()->GetFields('users'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('users')
'userfields' => UserfieldsService::GetInstance()->GetFields('users'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('users')
]);
}
}
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)
{
if ($item == '.' || $item == '..')
@ -65,11 +66,11 @@ class UsersController extends BaseController
public function UsersList(Request $request, Response $response, array $args)
{
User::checkPermission($request, User::PERMISSION_USERS_READ);
return $this->renderPage($response, 'users', [
'users' => $this->getDatabase()->users()->orderBy('username'),
'userfields' => $this->getUserfieldsService()->GetFields('users'),
'userfieldValues' => $this->getUserfieldsService()->GetAllValues('users')
User::CheckPermission($request, User::PERMISSION_USERS_READ);
return $this->RenderPage($response, 'users', [
'users' => $this->DB->users()->orderBy('username'),
'userfields' => UserfieldsService::GetInstance()->GetFields('users'),
'userfieldValues' => UserfieldsService::GetInstance()->GetAllValues('users')
]);
}
}

View File

@ -17,7 +17,7 @@ class SlimBladeView
protected $CachePath;
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);
$renderer = new Blade($this->ViewPaths, $this->CachePath, null);

View File

@ -3,8 +3,6 @@
namespace Grocy\Helpers;
use GuzzleHttp\Client;
use GuzzleHttp\ExceptionRequestException;
use Psr\Http\Message\ResponseInterface;
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)
{
$sessionService = SessionService::getInstance();
$sessionService = SessionService::GetInstance();
$user = $sessionService->GetDefaultUser();
define('GROCY_AUTHENTICATED', true);

View File

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

View File

@ -29,7 +29,7 @@ class DefaultAuthMiddleware extends AuthMiddleware
{
if (isset($postParams['username']) && isset($postParams['password']))
{
$db = DatabaseService::getInstance()->GetDbConnection();
$db = DatabaseService::GetInstance()->GetDbConnection();
$user = $db->users()->where('username', $postParams['username'])->fetch();
$inputPassword = $postParams['password'];
@ -37,7 +37,7 @@ class DefaultAuthMiddleware extends AuthMiddleware
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);
if (password_needs_rehash($user->password, PASSWORD_ARGON2ID))

View File

@ -75,14 +75,14 @@ class LdapAuthMiddleware extends AuthMiddleware
{
ldap_close($connect);
$db = DatabaseService::getInstance()->GetDbConnection();
$db = DatabaseService::GetInstance()->GetDbConnection();
$user = $db->users()->where('username', $ldapUidAttribute)->fetch();
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);
return true;

View File

@ -20,7 +20,7 @@ class LocaleMiddleware extends BaseMiddleware
{
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 (in_array($locale, scandir(__DIR__ . '/../localization')))

View File

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

View File

@ -9,7 +9,7 @@ class SessionAuthMiddleware extends AuthMiddleware
{
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]))
{

View File

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

View File

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

View File

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

View File

@ -2,4 +2,6 @@
// 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
use Grocy\Services\DatabaseService;
// 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
// 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)
{
$this->getDatabaseService()->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('UPDATE products SET treat_opened_as_out_of_stock = 0');
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
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
$db = $this->getDatabaseService();
$db = DatabaseService::GetInstance();
$sql = 'SELECT s1.id
FROM stock s1

View File

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

View File

@ -1,28 +1,28 @@
<?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\CalendarApiController;
use Grocy\Controllers\CalendarController;
use Grocy\Controllers\ChoresApiController;
use Grocy\Controllers\ChoresController;
use Grocy\Controllers\EquipmentController;
use Grocy\Controllers\FilesApiController;
use Grocy\Controllers\GenericEntityApiController;
use Grocy\Controllers\GenericEntityController;
use Grocy\Controllers\LoginController;
use Grocy\Controllers\OpenApiController;
use Grocy\Controllers\PrintApiController;
use Grocy\Controllers\RecipesApiController;
use Grocy\Controllers\RecipesController;
use Grocy\Controllers\StockApiController;
use Grocy\Controllers\StockController;
use Grocy\Controllers\StockReportsController;
use Grocy\Controllers\SystemApiController;
use Grocy\Controllers\SystemController;
use Grocy\Controllers\TasksApiController;
use Grocy\Controllers\TasksController;
use Grocy\Controllers\UsersApiController;
use Grocy\Controllers\UsersController;
use Grocy\Middleware\CorsMiddleware;
use Grocy\Middleware\JsonMiddleware;

View File

@ -11,7 +11,7 @@ class ApiKeyService extends BaseService
{
$newApiKey = $this->GenerateApiKey();
$apiKeyRow = $this->getDatabase()->api_keys()->createRow([
$apiKeyRow = $this->DB->api_keys()->createRow([
'api_key' => $newApiKey,
'user_id' => GROCY_USER_ID,
'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)
{
$apiKey = $this->getDatabase()->api_keys()->where('api_key', $apiKey)->fetch();
$apiKey = $this->DB->api_keys()->where('api_key', $apiKey)->fetch();
return $apiKey->id;
}
@ -39,7 +39,7 @@ class ApiKeyService extends BaseService
}
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)
{
@ -54,11 +54,11 @@ class ApiKeyService extends BaseService
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)
{
return $this->getDatabase()->users($apiKeyRow->user_id);
return $this->DB->users($apiKeyRow->user_id);
}
return null;
@ -72,17 +72,17 @@ class ApiKeyService extends BaseService
}
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)
{
// This should not change the database file modification time as this is used
// to determine if REALLY something has changed
$dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$dbModTime = DatabaseService::GetInstance()->GetDbChangedTime();
$apiKeyRow->update([
'last_used' => date('Y-m-d H:i:s', time())
]);
$this->getDatabaseService()->SetDbChangedTime($dbModTime);
DatabaseService::GetInstance()->SetDbChangedTime($dbModTime);
return true;
}
@ -95,7 +95,7 @@ class ApiKeyService extends BaseService
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()

View File

@ -69,7 +69,7 @@ class ApplicationService extends BaseService
'grocy_version' => $this->GetInstalledVersion(),
'php_version' => phpversion(),
'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'),
'client' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown'
];

View File

@ -4,76 +4,22 @@ namespace Grocy\Services;
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();
if (!isset(self::$instances[$className]))
if (!isset(self::$Instances[$className]))
{
self::$instances[$className] = new $className();
self::$Instances[$className] = new $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();
return self::$Instances[$className];
}
}

View File

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

View File

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

View File

@ -23,7 +23,7 @@ class ChoresService extends BaseService
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))
{
@ -31,11 +31,11 @@ class ChoresService extends BaseService
}
else
{
$choreLastTrackedTime = $this->getDatabase()->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();
$choreLastTrackedTime = $this->DB->chores_log()->where('chore_id = :1 AND undone = 0', $choreId)->max('tracked_time');
$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;
$users = $this->getUsersService()->GetUsersAsDto();
$users = UsersService::GetInstance()->GetUsersAsDto();
$assignedUsers = [];
foreach ($users as $user)
{
@ -88,7 +88,7 @@ class ChoresService extends BaseService
}
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)
{
$nextExecutionUserId = $row->user_id;
@ -108,15 +108,15 @@ class ChoresService extends BaseService
throw new \Exception('Chore does not exist');
}
$users = $this->getUsersService()->GetUsersAsDto();
$users = UsersService::GetInstance()->GetUsersAsDto();
$chore = $this->getDatabase()->chores($choreId);
$choreTrackedCount = $this->getDatabase()->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');
$nextExecutionTime = $this->getDatabase()->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');
$chore = $this->DB->chores($choreId);
$choreTrackedCount = $this->DB->chores_log()->where('chore_id = :1 AND undone = 0 AND skipped = 0', $choreId)->count();
$choreLastTrackedTime = $this->DB->chores_log()->where('chore_id = :1 AND undone = 0 AND skipped = 0', $choreId)->max('tracked_time');
$nextExecutionTime = $this->DB->chores_current()->where('chore_id', $choreId)->min('next_estimated_execution_time');
$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;
if ($lastChoreLogRow !== null && !empty($lastChoreLogRow))
{
@ -142,9 +142,9 @@ class ChoresService extends BaseService
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)
{
if (!empty($chore->next_execution_assigned_to_user_id))
@ -167,13 +167,13 @@ class ChoresService extends BaseService
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)
{
throw new \Exception('User does not exist');
}
$chore = $this->getDatabase()->chores($choreId);
$chore = $this->DB->chores($choreId);
if ($chore->track_date_only == 1)
{
$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;
$logRow = $this->getDatabase()->chores_log()->createRow([
$scheduledExecutionTime = $this->DB->chores_current()->where('chore_id = :1', $chore->id)->fetch()->next_estimated_execution_time;
$logRow = $this->DB->chores_log()->createRow([
'chore_id' => $choreId,
'tracked_time' => $trackedTime,
'done_by_user_id' => $doneBy,
@ -196,12 +196,12 @@ class ChoresService extends BaseService
'scheduled_execution_time' => $scheduledExecutionTime
]);
$logRow->save();
$lastInsertId = $this->getDatabase()->lastInsertId();
$lastInsertId = $this->DB->lastInsertId();
if ($chore->consume_product_on_execution == 1 && !empty($chore->product_id))
{
$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))
@ -225,7 +225,7 @@ class ChoresService extends BaseService
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)
{
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');
}
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction();
DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try
{
$choreToKeep = $this->getDatabase()->chores($choreIdToKeep);
$choreToRemove = $this->getDatabase()->chores($choreIdToRemove);
$choreToKeep = $this->DB->chores($choreIdToKeep);
$choreToRemove = $this->DB->chores($choreIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('UPDATE chores_log SET chore_id = ' . $choreIdToKeep . ' WHERE chore_id = ' . $choreIdToRemove);
$this->getDatabaseService()->ExecuteDbStatement('DELETE FROM chores WHERE id = ' . $choreIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE chores_log SET chore_id = ' . $choreIdToKeep . ' WHERE chore_id = ' . $choreIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('DELETE FROM chores WHERE id = ' . $choreIdToRemove);
}
catch (\Exception $ex)
{
$this->getDatabaseService()->GetDbConnectionRaw()->rollback();
DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex;
}
$this->getDatabaseService()->GetDbConnectionRaw()->commit();
DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
}
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;
}
}

View File

@ -12,7 +12,9 @@ class DatabaseMigrationService extends BaseService
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 = [];
foreach (new \FilesystemIterator(__DIR__ . '/../migrations') as $file)
@ -38,20 +40,20 @@ class DatabaseMigrationService extends BaseService
if ($migrationCounter > 0)
{
$this->getDatabaseService()->ExecuteDbStatement('VACUUM');
DatabaseService::GetInstance()->ExecuteDbStatement('VACUUM');
}
}
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)
{
include $phpFile;
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++;
}
}
@ -59,28 +61,28 @@ class DatabaseMigrationService extends BaseService
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)
{
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction();
DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try
{
$this->getDatabaseService()->ExecuteDbStatement($sql);
DatabaseService::GetInstance()->ExecuteDbStatement($sql);
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++;
}
}
catch (\Exception $ex)
{
$this->getDatabaseService()->GetDbConnectionRaw()->rollback();
DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex;
}
$this->getDatabaseService()->GetDbConnectionRaw()->commit();
DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
}
}
}

View File

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

View File

@ -4,22 +4,16 @@ namespace Grocy\Services;
class DemoDataGeneratorService extends BaseService
{
public function __construct()
{
$this->LocalizationService = new LocalizationService(GROCY_DEFAULT_LOCALE);
}
protected $LocalizationService;
private $LastSupermarketId = 1;
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 ($skip)
{
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (-1);');
DatabaseService::GetInstance()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (-1);');
return;
}
@ -225,7 +219,7 @@ class DemoDataGeneratorService extends BaseService
INSERT INTO migrations (migration) VALUES (-1);
";
$this->getDatabaseService()->ExecuteDbStatement($sql);
DatabaseService::GetInstance()->ExecuteDbStatement($sql);
$stockTransactionId = uniqid();
$stockService = new StockService();
@ -323,7 +317,7 @@ class DemoDataGeneratorService extends BaseService
$choresService = new ChoresService();
for ($i = 1; $i <= 25; $i++)
{
foreach ($this->getDatabase()->chores() as $chore)
foreach ($this->DB->chores() as $chore)
{
$hours = $chore->period_interval;
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(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->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)
{
$localizedText = $this->getLocalizationService()->__n($number, $singularForm, $pluralForm);
$localizedText = LocalizationService::GetInstance()->__n($number, $singularForm, $pluralForm);
return str_replace("'", "''", $localizedText);
}
private function __t_sql(string $text)
{
$localizedText = $this->getLocalizationService()->__t($text, null);
$localizedText = LocalizationService::GetInstance()->__t($text, null);
return str_replace("'", "''", $localizedText);
}
}

View File

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

View File

@ -6,12 +6,13 @@ use Gettext\Translation;
use Gettext\Translations;
use Gettext\Translator;
class LocalizationService
class LocalizationService extends BaseService
{
public function __construct(string $culture)
{
$this->Culture = $culture;
parent::__construct();
$this->Culture = $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))
{
self::$instanceMap[$culture] = new self($culture);
@ -121,16 +134,6 @@ class LocalizationService
return self::$instanceMap[$culture];
}
protected function getDatabaseService()
{
return DatabaseService::getInstance();
}
protected function getdatabase()
{
return $this->getDatabaseService()->GetDbConnection();
}
private function LoadLocalizations()
{
$culture = $this->Culture;
@ -147,12 +150,8 @@ class LocalizationService
$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/locales.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");
@ -191,7 +190,8 @@ class LocalizationService
$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"));
}
@ -204,7 +204,7 @@ class LocalizationService
$quantityUnits = null;
try
{
$quantityUnits = $this->getDatabase()->quantity_units()->where('active = 1')->fetchAll();
$quantityUnits = $this->DB->quantity_units()->where('active = 1')->fetchAll();
}
catch (\Exception $ex)
{

View File

@ -13,7 +13,7 @@ class RecipesService extends BaseService
public function AddNotFulfilledProductsToShoppingList($recipeId, $excludedProductIds = null)
{
$recipe = $this->getDataBase()->recipes($recipeId);
$recipe = $this->DB->recipes($recipeId);
$recipePositions = $this->GetRecipesPosResolved();
if ($excludedProductIds == null)
@ -25,7 +25,7 @@ class RecipesService extends BaseService
{
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);
$quId = $product->qu_id_purchase;
@ -39,7 +39,7 @@ class RecipesService extends BaseService
// => Do the unit conversion here (if any)
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)
{
$toOrderAmount = $toOrderAmount * $conversion->factor;
@ -54,7 +54,7 @@ class RecipesService extends BaseService
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)
{
// Update
@ -65,7 +65,7 @@ class RecipesService extends BaseService
else
{
// Insert
$shoppinglistRow = $this->getDataBase()->shopping_list()->createRow([
$shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $recipePosition->product_id,
'amount' => $toOrderAmount,
'qu_id' => $quId
@ -85,9 +85,9 @@ class RecipesService extends BaseService
}
$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
{
foreach ($recipePositions as $recipePosition)
@ -100,52 +100,52 @@ class RecipesService extends BaseService
$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)
{
$this->getDatabaseService()->GetDbConnectionRaw()->rollback();
DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
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;
$amount = $recipe->desired_servings;
if ($recipe->type == self::RECIPE_TYPE_MEALPLAN_SHADOW)
{
// Use "Produces product" of the original recipe
$mealPlanEntry = $this->getDatabase()->meal_plan()->where('id = :1', explode('#', $recipe->name)[1])->fetch();
$recipe = $this->getDatabase()->recipes()->where('id = :1', $mealPlanEntry->recipe_id)->fetch();
$mealPlanEntry = $this->DB->meal_plan()->where('id = :1', explode('#', $recipe->name)[1])->fetch();
$recipe = $this->DB->recipes()->where('id = :1', $mealPlanEntry->recipe_id)->fetch();
$productId = $recipe->product_id;
$amount = $mealPlanEntry->recipe_servings;
}
if (!empty($productId))
{
$product = $this->getDatabase()->products()->where('id = :1', $productId)->fetch();
$recipeResolvedRow = $this->getDatabase()->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);
$product = $this->DB->products()->where('id = :1', $productId)->fetch();
$recipeResolvedRow = $this->DB->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch();
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()
{
$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
{
if ($customWhere == null)
{
return $this->getDatabase()->recipes_resolved();
return $this->DB->recipes_resolved();
}
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');
}
$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]);
$lastInsertId = $this->getDatabase()->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]);
$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 (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->DB->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]);
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;
}
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;
}
}

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
}
$sessionRow = $this->getDatabase()->sessions()->createRow([
$sessionRow = $this->DB->sessions()->createRow([
'user_id' => $userId,
'session_key' => $newSessionKey,
'expires' => $expires
@ -29,15 +29,15 @@ class SessionService extends BaseService
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)
{
$sessionRow = $this->getDatabase()->sessions()->where('session_key', $sessionKey)->fetch();
$sessionRow = $this->DB->sessions()->where('session_key', $sessionKey)->fetch();
if ($sessionRow !== null)
{
return $this->getDatabase()->users($sessionRow->user_id);
return $this->DB->users($sessionRow->user_id);
}
return null;
@ -51,16 +51,16 @@ class SessionService extends BaseService
}
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)
{
// This should not change the database file modification time as this is used
// to determine if REALLY something has changed
$dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$dbModTime = DatabaseService::GetInstance()->GetDbChangedTime();
$sessionRow->update([
'last_used' => date('Y-m-d H:i:s', time())
]);
$this->getDatabaseService()->SetDbChangedTime($dbModTime);
DatabaseService::GetInstance()->SetDbChangedTime($dbModTime);
return true;
}
@ -73,7 +73,7 @@ class SessionService extends BaseService
public function RemoveSession($sessionKey)
{
$this->getDatabase()->sessions()->where('session_key', $sessionKey)->delete();
$this->DB->sessions()->where('session_key', $sessionKey)->delete();
}
private function GenerateSessionKey()

View File

@ -28,10 +28,10 @@ class StockService extends BaseService
$missingProducts = $this->GetMissingProducts();
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);
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch();
$alreadyExistingEntry = $this->DB->shopping_list()->where('product_id', $missingProduct->id)->fetch();
if ($alreadyExistingEntry)
{
// Update
@ -46,7 +46,7 @@ class StockService extends BaseService
else
{
// Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
$shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $missingProduct->id,
'amount' => $amountToAdd,
'shopping_list_id' => $listId,
@ -67,12 +67,12 @@ class StockService extends BaseService
$overdueProducts = $this->GetDueProducts(-1);
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)
{
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
$shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $overdueProduct->product_id,
'amount' => 1,
'shopping_list_id' => $listId,
@ -93,12 +93,12 @@ class StockService extends BaseService
$expiredProducts = $this->GetExpiredProducts();
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)
{
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
$shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $expiredProduct->product_id,
'amount' => 1,
'shopping_list_id' => $listId,
@ -151,7 +151,7 @@ class StockService extends BaseService
}
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)
@ -193,7 +193,7 @@ class StockService extends BaseService
for ($i = 1; $i <= $amount; $i++)
{
$stockId = uniqid('x');
$logRow = $this->getDatabase()->stock_log()->createRow([
$logRow = $this->DB->stock_log()->createRow([
'product_id' => $productId,
'amount' => 1,
'best_before_date' => $bestBeforeDate,
@ -209,7 +209,7 @@ class StockService extends BaseService
]);
$logRow->save();
$stockRow = $this->getDatabase()->stock()->createRow([
$stockRow = $this->DB->stock()->createRow([
'product_id' => $productId,
'amount' => 1,
'best_before_date' => $bestBeforeDate,
@ -233,7 +233,7 @@ class StockService extends BaseService
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();
@ -246,7 +246,7 @@ class StockService extends BaseService
// No or single label => one stock entry
$stockId = uniqid();
$logRow = $this->getDatabase()->stock_log()->createRow([
$logRow = $this->DB->stock_log()->createRow([
'product_id' => $productId,
'amount' => $amount,
'best_before_date' => $bestBeforeDate,
@ -262,7 +262,7 @@ class StockService extends BaseService
]);
$logRow->save();
$stockRow = $this->getDatabase()->stock()->createRow([
$stockRow = $this->DB->stock()->createRow([
'product_id' => $productId,
'amount' => $amount,
'best_before_date' => $bestBeforeDate,
@ -286,7 +286,7 @@ class StockService extends BaseService
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();
@ -318,10 +318,10 @@ class StockService extends BaseService
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)
{
// Update
@ -334,7 +334,7 @@ class StockService extends BaseService
else
{
// Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
$shoppinglistRow = $this->DB->shopping_list()->createRow([
'product_id' => $productId,
'amount' => $amount,
'qu_id' => $quId,
@ -354,11 +354,11 @@ class StockService extends BaseService
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
{
$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)
{
// A sub product will be used -> use QU conversions
$subProduct = $this->getDatabase()->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();
$subProduct = $this->DB->products($stockEntry->product_id);
$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)
{
$amount = $amount * $conversion->factor;
@ -448,7 +448,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount)
{
// Take the whole stock entry
$logRow = $this->getDatabase()->stock_log()->createRow([
$logRow = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1,
'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
$restStockAmount = $stockEntry->amount - $amount;
$logRow = $this->getDatabase()->stock_log()->createRow([
$logRow = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $amount * -1,
'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;
@ -527,7 +527,7 @@ class StockService extends BaseService
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)
{
throw new \Exception('Stock does not exist');
@ -535,7 +535,7 @@ class StockService extends BaseService
$correlationId = uniqid();
$transactionId = uniqid();
$logOldRowForStockUpdate = $this->getDatabase()->stock_log()->createRow([
$logOldRowForStockUpdate = $this->DB->stock_log()->createRow([
'product_id' => $stockRow->product_id,
'amount' => $stockRow->amount,
'best_before_date' => $stockRow->best_before_date,
@ -576,7 +576,7 @@ class StockService extends BaseService
'note' => $note
]);
$logNewRowForStockUpdate = $this->getDatabase()->stock_log()->createRow([
$logNewRowForStockUpdate = $this->DB->stock_log()->createRow([
'product_id' => $stockRow->product_id,
'amount' => $amount,
'best_before_date' => $bestBeforeDate,
@ -616,7 +616,7 @@ class StockService extends BaseService
// Lookup was successful
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');
}
@ -633,7 +633,7 @@ class StockService extends BaseService
if (preg_match('/^https?:\/\//', $pluginOutput['__image_url']))
{
$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);
// Fallback to Content-Type header if file extension is missing
@ -656,7 +656,7 @@ class StockService extends BaseService
if (!empty($fileExtension) && !empty($imageData))
{
$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;
}
}
@ -666,17 +666,17 @@ class StockService extends BaseService
}
}
$newProductRow = $this->getDatabase()->products()->createRow($productData);
$newProductRow = $this->DB->products()->createRow($productData);
$newProductRow->save();
$this->getDatabase()->product_barcodes()->createRow([
$this->DB->product_barcodes()->createRow([
'product_id' => $newProductRow->id,
'barcode' => $pluginOutput['__barcode']
])->save();
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,
'from_qu_id' => $pluginOutput['qu_id_purchase'],
'to_qu_id' => $pluginOutput['qu_id_stock'],
@ -694,8 +694,8 @@ class StockService extends BaseService
public function GetCurrentStock($customWhere = '')
{
$sql = 'SELECT * FROM stock_current ' . $customWhere;
$currentStockMapped = $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_OBJ);
$relevantProducts = $this->getDatabase()->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)');
$currentStockMapped = DatabaseService::GetInstance()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_GROUP | \PDO::FETCH_OBJ);
$relevantProducts = $this->DB->products()->where('id IN (SELECT product_id FROM (' . $sql . ') x)');
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';
return $this->getDatabaseService()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
return DatabaseService::GetInstance()->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
public function GetCurrentStockLocations()
{
$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)
@ -743,9 +743,9 @@ class StockService extends BaseService
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)
{
FindObjectInArrayByPropertyValue($missingProductsResponse, 'id', $product->id)->product = $product;
@ -773,19 +773,19 @@ class StockService extends BaseService
$stockCurrentRow->is_aggregated_amount = 0;
}
$detailsRow = $this->getDatabase()->uihelper_product_details()->where('id', $productId)->fetch();
$product = $this->getDatabase()->products($productId);
$productBarcodes = $this->getDatabase()->product_barcodes()->where('product_id', $productId)->fetchAll();
$quPurchase = $this->getDatabase()->quantity_units($product->qu_id_purchase);
$quStock = $this->getDatabase()->quantity_units($product->qu_id_stock);
$quConsume = $this->getDatabase()->quantity_units($product->qu_id_consume);
$quPrice = $this->getDatabase()->quantity_units($product->qu_id_price);
$location = $this->getDatabase()->locations($product->location_id);
$detailsRow = $this->DB->uihelper_product_details()->where('id', $productId)->fetch();
$product = $this->DB->products($productId);
$productBarcodes = $this->DB->product_barcodes()->where('product_id', $productId)->fetchAll();
$quPurchase = $this->DB->quantity_units($product->qu_id_purchase);
$quStock = $this->DB->quantity_units($product->qu_id_stock);
$quConsume = $this->DB->quantity_units($product->qu_id_consume);
$quPrice = $this->DB->quantity_units($product->qu_id_price);
$location = $this->DB->locations($product->location_id);
$defaultConsumeLocation = null;
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 [
@ -833,7 +833,7 @@ class StockService extends BaseService
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)
{
throw new \Exception("No product with barcode $barcode found");
@ -850,9 +850,9 @@ class StockService extends BaseService
}
$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)
{
$returnData[] = [
@ -879,7 +879,7 @@ class StockService extends BaseService
$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)
@ -889,7 +889,7 @@ class StockService extends BaseService
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)
@ -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 . ')';
}
return $this->getDatabase()->stock_current_locations()->where($sqlWhereProductId);
return $this->DB->stock_current_locations()->where($sqlWhereProductId);
}
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)
@ -985,7 +985,7 @@ class StockService extends BaseService
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)
{
@ -1045,7 +1045,7 @@ class StockService extends BaseService
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();
@ -1056,8 +1056,8 @@ class StockService extends BaseService
if ($allowSubproductSubstitution && $stockEntry->product_id != $productId)
{
// A sub product will be used -> use QU conversions
$subProduct = $this->getDatabase()->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();
$subProduct = $this->DB->products($stockEntry->product_id);
$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)
{
$amount = $amount * $conversion->factor;
@ -1067,7 +1067,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount)
{
// Mark the whole stock entry as opened
$logRow = $this->getDatabase()->stock_log()->createRow([
$logRow = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount,
'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
$restStockAmount = $stockEntry->amount - $amount;
$newStockRow = $this->getDatabase()->stock()->createRow([
$newStockRow = $this->DB->stock()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $restStockAmount,
'best_before_date' => $stockEntry->best_before_date,
@ -1110,7 +1110,7 @@ class StockService extends BaseService
]);
$newStockRow->save();
$logRow = $this->getDatabase()->stock_log()->createRow([
$logRow = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $amount,
'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;
@ -1162,12 +1162,12 @@ class StockService extends BaseService
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 ($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;
if ($newAmount < floatval('0.' . str_repeat('0', $decimals - ($decimals <= 0 ? 0 : 1)) . '1'))
@ -1190,14 +1190,14 @@ class StockService extends BaseService
$result_product = [];
$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)
{
$isValidProduct = ($row->product_id != null && $row->product_id != '');
if ($isValidProduct)
{
$product = $this->getDatabase()->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();
$product = $this->DB->products()->where('id = :1', $row->product_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;
if ($conversion != null)
@ -1298,7 +1298,7 @@ class StockService extends BaseService
$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);
if ($amount > $productStockAmountAtFromLocation)
@ -1326,8 +1326,8 @@ class StockService extends BaseService
$newBestBeforeDate = $stockEntry->best_before_date;
if (GROCY_FEATURE_FLAG_STOCK_PRODUCT_FREEZING)
{
$locationFrom = $this->getDatabase()->locations()->where('id', $locationIdFrom)->fetch();
$locationTo = $this->getDatabase()->locations()->where('id', $locationIdTo)->fetch();
$locationFrom = $this->DB->locations()->where('id', $locationIdFrom)->fetch();
$locationTo = $this->DB->locations()->where('id', $locationIdTo)->fetch();
// 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))
@ -1359,7 +1359,7 @@ class StockService extends BaseService
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();
@ -1371,7 +1371,7 @@ class StockService extends BaseService
if ($amount >= $stockEntry->amount)
{
// Take the whole stock entry
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([
$logRowForLocationFrom = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1,
'best_before_date' => $stockEntry->best_before_date,
@ -1389,7 +1389,7 @@ class StockService extends BaseService
]);
$logRowForLocationFrom->save();
$logRowForLocationTo = $this->getDatabase()->stock_log()->createRow([
$logRowForLocationTo = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount,
'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
$restStockAmount = $stockEntry->amount - $amount;
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([
$logRowForLocationFrom = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $amount * -1,
'best_before_date' => $stockEntry->best_before_date,
@ -1437,7 +1437,7 @@ class StockService extends BaseService
]);
$logRowForLocationFrom->save();
$logRowForLocationTo = $this->getDatabase()->stock_log()->createRow([
$logRowForLocationTo = $this->DB->stock_log()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $amount,
'best_before_date' => $newBestBeforeDate,
@ -1461,7 +1461,7 @@ class StockService extends BaseService
]);
// The transferred amount gets into a new stock entry
$stockEntryNew = $this->getDatabase()->stock()->createRow([
$stockEntryNew = $this->DB->stock()->createRow([
'product_id' => $stockEntry->product_id,
'amount' => $amount,
'best_before_date' => $newBestBeforeDate,
@ -1485,7 +1485,7 @@ class StockService extends BaseService
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)
{
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
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)
{
$this->UndoBooking($correlatedBooking->id, true);
@ -1503,7 +1503,7 @@ class StockService extends BaseService
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)
{
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))
{
// 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();
// 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))
{
// Add corresponding amount back to stock
$stockRow = $this->getDatabase()->stock()->createRow([
$stockRow = $this->DB->stock()->createRow([
'product_id' => $logRow->product_id,
'amount' => $logRow->amount * -1,
'best_before_date' => $logRow->best_before_date,
@ -1547,7 +1547,7 @@ class StockService extends BaseService
}
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)
{
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)
{
// 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)
{
$stockRow = $this->getDatabase()->stock()->createRow([
$stockRow = $this->DB->stock()->createRow([
'product_id' => $logRow->product_id,
'amount' => $logRow->amount * -1,
'best_before_date' => $logRow->best_before_date,
@ -1607,7 +1607,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_PRODUCT_OPENED)
{
// 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([
'open' => 0,
'opened_date' => null,
@ -1631,7 +1631,7 @@ class StockService extends BaseService
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_STOCK_EDIT_OLD)
{
// 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)
{
@ -1670,7 +1670,7 @@ class StockService extends BaseService
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)
{
@ -1700,50 +1700,50 @@ class StockService extends BaseService
throw new \Exception('$productIdToKeep cannot equal $productIdToRemove');
}
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction();
DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try
{
$productToKeep = $this->getDatabase()->products($productIdToKeep);
$productToRemove = $this->getDatabase()->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();
$productToKeep = $this->DB->products($productIdToKeep);
$productToRemove = $this->DB->products($productIdToRemove);
$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;
if ($conversion != null)
{
$factor = $conversion->factor;
}
$this->getDatabaseService()->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);
$this->getDatabaseService()->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);
$this->getDatabaseService()->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);
$this->getDatabaseService()->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);
$this->getDatabaseService()->ExecuteDbStatement('DELETE FROM products WHERE id = ' . $productIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE stock 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);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE product_barcodes SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE quantity_unit_conversions SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE recipes_pos SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE recipes SET product_id = ' . $productIdToKeep . ' WHERE product_id = ' . $productIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE meal_plan SET product_id = ' . $productIdToKeep . ', product_amount = product_amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('UPDATE shopping_list SET product_id = ' . $productIdToKeep . ', amount = amount * ' . $factor . ' WHERE product_id = ' . $productIdToRemove);
DatabaseService::GetInstance()->ExecuteDbStatement('DELETE FROM products WHERE id = ' . $productIdToRemove);
}
catch (\Exception $ex)
{
$this->getDatabaseService()->GetDbConnectionRaw()->rollback();
DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex;
}
$this->getDatabaseService()->GetDbConnectionRaw()->commit();
DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
}
public function CompactStockEntries($productId = null)
{
if ($productId == null)
{
$splittedStockEntries = $this->getDatabase()->stock_splits();
$splittedStockEntries = $this->DB->stock_splits();
}
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)
{
$this->getDatabaseService()->GetDbConnectionRaw()->beginTransaction();
DatabaseService::GetInstance()->GetDbConnectionRaw()->beginTransaction();
try
{
$stockIds = explode(',', $splittedStockEntry->stock_id_group);
@ -1751,8 +1751,8 @@ class StockService extends BaseService
{
if ($stockId != $splittedStockEntry->stock_id_to_keep)
{
$this->getDatabaseService()->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 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)
{
$this->getDatabaseService()->ExecuteDbStatement('DELETE FROM stock WHERE id = ' . $stockEntryId);
DatabaseService::GetInstance()->ExecuteDbStatement('DELETE FROM stock WHERE id = ' . $stockEntryId);
}
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)
{
$this->getDatabaseService()->GetDbConnectionRaw()->rollback();
DatabaseService::GetInstance()->GetDbConnectionRaw()->rollback();
throw $ex;
}
$this->getDatabaseService()->GetDbConnectionRaw()->commit();
DatabaseService::GetInstance()->GetDbConnectionRaw()->commit();
}
}
@ -1792,12 +1792,12 @@ class StockService extends BaseService
if (file_exists($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))
{
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
{
@ -1807,19 +1807,19 @@ class StockService extends BaseService
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;
}
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;
}
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;
}
}

View File

@ -8,10 +8,10 @@ class TasksService extends BaseService
{
public function GetCurrent(): Result
{
$users = $this->getUsersService()->GetUsersAsDto();
$categories = $this->getDatabase()->task_categories()->where('active = 1');
$users = UsersService::GetInstance()->GetUsersAsDto();
$categories = $this->DB->task_categories()->where('active = 1');
$tasks = $this->getDatabase()->tasks_current();
$tasks = $this->DB->tasks_current();
foreach ($tasks as $task)
{
if (!empty($task->assigned_to_user_id))
@ -43,7 +43,7 @@ class TasksService extends BaseService
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([
'done' => 1,
'done_timestamp' => $doneTime
@ -59,7 +59,7 @@ class TasksService extends BaseService
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([
'done' => 0,
'done_timestamp' => null
@ -70,7 +70,7 @@ class TasksService extends BaseService
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;
}
}

View File

@ -23,7 +23,7 @@ class UserfieldsService extends BaseService
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)
@ -34,16 +34,16 @@ class UserfieldsService extends BaseService
}
$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()
{
$exposedDefaultEntities = $this->getOpenApiSpec()->components->schemas->ExposedEntity->enum;
$exposedDefaultEntities = $this->GetOpenApispec()->components->schemas->ExposedEntity->enum;
$userEntities = [];
$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;
}
@ -55,7 +55,7 @@ class UserfieldsService extends BaseService
public function GetField($fieldId)
{
return $this->getDatabase()->userfields($fieldId);
return $this->DB->userfields($fieldId);
}
public function GetFieldTypes()
@ -70,7 +70,7 @@ class UserfieldsService extends BaseService
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)
@ -81,7 +81,7 @@ class UserfieldsService extends BaseService
}
$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 = [];
foreach ($userfields as $userfield)
@ -109,7 +109,7 @@ class UserfieldsService extends BaseService
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)
{
@ -118,17 +118,15 @@ class UserfieldsService extends BaseService
$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)
{ // Update
$alreadyExistingEntry->update([
if ($alreadyExistingEntry) // Update
{$alreadyExistingEntry->update([
'value' => $value
]);
}
else
{ // Insert
$newRow = $this->getDatabase()->userfield_values()->createRow([
else // Insert
{$newRow = $this->DB->userfield_values()->createRow([
'field_id' => $fieldId,
'object_id' => $objectId,
'value' => $value
@ -138,7 +136,7 @@ class UserfieldsService extends BaseService
}
}
protected function getOpenApispec()
protected function GetOpenApispec()
{
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)
{
$newUserRow = $this->getDatabase()->users()->createRow([
$newUserRow = $this->DB->users()->createRow([
'username' => $username,
'first_name' => $firstName,
'last_name' => $lastName,
@ -18,7 +18,7 @@ class UsersService extends BaseService
$newUserRow = $newUserRow->save();
$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[] = [
'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;
}
public function DeleteUser($userId)
{
$row = $this->getDatabase()->users($userId);
$row = $this->DB->users($userId);
$row->delete();
}
@ -44,7 +44,7 @@ class UsersService extends BaseService
throw new \Exception('User does not exist');
}
$user = $this->getDatabase()->users($userId);
$user = $this->DB->users($userId);
if ($password == null || empty($password))
{
@ -81,7 +81,7 @@ class UsersService extends BaseService
}
$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)
{
$value = $settingRow->value;
@ -103,7 +103,7 @@ class UsersService extends BaseService
public function GetUserSettings($userId)
{
$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)
{
$settings[$settingRow->key] = $settingRow->value;
@ -116,7 +116,7 @@ class UsersService extends BaseService
public function GetUsersAsDto(): Result
{
return $this->getDatabase()->users_dto();
return $this->DB->users_dto();
}
public function SetUserSetting($userId, $settingKey, $settingValue)
@ -127,7 +127,7 @@ class UsersService extends BaseService
}
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)
{
$settingRow->update([
@ -137,7 +137,7 @@ class UsersService extends BaseService
}
else
{
$settingRow = $this->getDatabase()->user_settings()->createRow([
$settingRow = $this->DB->user_settings()->createRow([
'user_id' => $userId,
'key' => $settingKey,
'value' => $settingValue
@ -154,12 +154,12 @@ class UsersService extends BaseService
}
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)
{
$userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch();
$userRow = $this->DB->users()->where('id = :1', $userId)->fetch();
return $userRow !== null;
}
}