Applied PHP-CS-Fixer rules

This commit is contained in:
Bernd Bestel 2020-09-01 21:29:47 +02:00
parent 3da8904cba
commit 836bcc82e5
No known key found for this signature in database
GPG Key ID: 71BD34C0D4891300
56 changed files with 150 additions and 467 deletions

12
app.php
View File

@ -38,20 +38,16 @@ AppFactory::setContainer(new DI\Container());
$app = AppFactory::create(); $app = AppFactory::create();
$container = $app->getContainer(); $container = $app->getContainer();
$container->set('view', function (Container $container) $container->set('view', function (Container $container) {
{
return new Slim\Views\Blade(__DIR__ . '/views', GROCY_DATAPATH . '/viewcache'); return new Slim\Views\Blade(__DIR__ . '/views', GROCY_DATAPATH . '/viewcache');
}); });
$container->set('LoginControllerInstance', function (Container $container) $container->set('LoginControllerInstance', function (Container $container) {
{
return new LoginController($container, 'grocy_session'); return new LoginController($container, 'grocy_session');
}); });
$container->set('UrlManager', function (Container $container) $container->set('UrlManager', function (Container $container) {
{
return new UrlManager(GROCY_BASE_URL); return new UrlManager(GROCY_BASE_URL);
}); });
$container->set('ApiKeyHeaderName', function (Container $container) $container->set('ApiKeyHeaderName', function (Container $container) {
{
return 'GROCY-API-KEY'; return 'GROCY-API-KEY';
}); });

View File

@ -44,22 +44,31 @@ class BaseApiController extends BaseController
protected function queryData(Result $data, array $query) protected function queryData(Result $data, array $query)
{ {
if (isset($query['query'])) if (isset($query['query']))
{
$data = $this->filter($data, $query['query']); $data = $this->filter($data, $query['query']);
}
if (isset($query['limit'])) if (isset($query['limit']))
{
$data = $data->limit(intval($query['limit']), intval($query['offset'] ?? 0)); $data = $data->limit(intval($query['limit']), intval($query['offset'] ?? 0));
}
if (isset($query['order'])) if (isset($query['order']))
{
$data = $data->orderBy($query['order']); $data = $data->orderBy($query['order']);
}
return $data; return $data;
} }
protected function filter(Result $data, array $query): Result protected function filter(Result $data, array $query): Result
{ {
foreach ($query as $q) { foreach ($query as $q)
$matches = array(); {
preg_match('/(?P<field>' . self::PATTERN_FIELD . ')' $matches = [];
preg_match(
'/(?P<field>' . self::PATTERN_FIELD . ')'
. '(?P<op>' . self::PATTERN_OPERATOR . ')' . '(?P<op>' . self::PATTERN_OPERATOR . ')'
. '(?P<value>' . self::PATTERN_VALUE . ')/', . '(?P<value>' . self::PATTERN_VALUE . ')/',
$q, $matches $q,
$matches
); );
error_log(var_export($matches, true)); error_log(var_export($matches, true));
switch ($matches['op']) { switch ($matches['op']) {
@ -106,5 +115,4 @@ class BaseApiController extends BaseController
return $this->OpenApiSpec; return $this->OpenApiSpec;
} }
} }

View File

@ -112,18 +112,15 @@ class BaseController
$this->View->set('releaseDate', $versionInfo->ReleaseDate); $this->View->set('releaseDate', $versionInfo->ReleaseDate);
$localizationService = $this->getLocalizationService(); $localizationService = $this->getLocalizationService();
$this->View->set('__t', function (string $text, ...$placeholderValues) use ($localizationService) $this->View->set('__t', function (string $text, ...$placeholderValues) use ($localizationService) {
{
return $localizationService->__t($text, $placeholderValues); return $localizationService->__t($text, $placeholderValues);
}); });
$this->View->set('__n', function ($number, $singularForm, $pluralForm) use ($localizationService) $this->View->set('__n', function ($number, $singularForm, $pluralForm) use ($localizationService) {
{
return $localizationService->__n($number, $singularForm, $pluralForm); return $localizationService->__n($number, $singularForm, $pluralForm);
}); });
$this->View->set('GettextPo', $localizationService->GetPoAsJsonString()); $this->View->set('GettextPo', $localizationService->GetPoAsJsonString());
$this->View->set('U', function ($relativePath, $isResource = false) use ($container) $this->View->set('U', function ($relativePath, $isResource = false) use ($container) {
{
return $container->get('UrlManager')->ConstructUrl($relativePath, $isResource); return $container->get('UrlManager')->ConstructUrl($relativePath, $isResource);
}); });
@ -144,7 +141,6 @@ class BaseController
{ {
unset($constants[$constant]); unset($constants[$constant]);
} }
} }
$this->View->set('featureFlags', $constants); $this->View->set('featureFlags', $constants);
@ -172,7 +168,6 @@ class BaseController
{ {
$this->View->set('userSettings', null); $this->View->set('userSettings', null);
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
@ -181,5 +176,4 @@ class BaseController
return $this->render($response, $page, $data); return $this->render($response, $page, $data);
} }
} }

View File

@ -16,7 +16,6 @@ class BatteriesApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -46,7 +45,6 @@ class BatteriesApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function UndoChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UndoChargeCycle(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -62,12 +60,10 @@ class BatteriesApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -35,7 +35,6 @@ class BatteriesController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('batteries') 'userfields' => $this->getUserfieldsService()->GetFields('batteries')
]); ]);
} }
} }
public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Journal(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -71,5 +70,4 @@ class BatteriesController extends BaseController
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -47,7 +47,6 @@ class CalendarApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function IcalSharingLink(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function IcalSharingLink(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -62,12 +61,10 @@ class CalendarApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -27,7 +27,6 @@ class ChoresApiController extends BaseApiController
{ {
$this->getChoresService()->CalculateNextExecutionAssignment($chore->id); $this->getChoresService()->CalculateNextExecutionAssignment($chore->id);
} }
} }
else else
{ {
@ -40,7 +39,6 @@ class ChoresApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ChoreDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ChoreDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -53,7 +51,6 @@ class ChoresApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Current(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -95,7 +92,6 @@ class ChoresApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function UndoChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UndoChoreExecution(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -111,12 +107,10 @@ class ChoresApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -32,7 +32,6 @@ class ChoresController extends BaseController
'products' => $this->getDatabase()->products()->orderBy('name') 'products' => $this->getDatabase()->products()->orderBy('name')
]); ]);
} }
} }
public function ChoresList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ChoresList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -85,5 +84,4 @@ class ChoresController extends BaseController
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -23,7 +23,6 @@ class EquipmentController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('equipment') 'userfields' => $this->getUserfieldsService()->GetFields('equipment')
]); ]);
} }
} }
public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function Overview(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -39,5 +38,4 @@ class EquipmentController extends BaseController
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -73,5 +73,4 @@ class ExceptionController extends BaseApiController
'exception' => $exception 'exception' => $exception
]); ]);
} }
} }

View File

@ -33,7 +33,6 @@ class FilesApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ServeFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ServeFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -55,13 +54,11 @@ class FilesApiController extends BaseApiController
{ {
throw new HttpNotFoundException($request, 'File not found'); throw new HttpNotFoundException($request, 'File not found');
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
throw new HttpNotFoundException($request, $ex->getMessage(), $ex); throw new HttpNotFoundException($request, $ex->getMessage(), $ex);
} }
} }
public function ShowFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ShowFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -84,13 +81,11 @@ class FilesApiController extends BaseApiController
{ {
throw new HttpNotFoundException($request, 'File not found'); throw new HttpNotFoundException($request, 'File not found');
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
throw new HttpNotFoundException($request, $ex->getMessage(), $ex); throw new HttpNotFoundException($request, $ex->getMessage(), $ex);
} }
} }
public function UploadFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UploadFile(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -108,7 +103,6 @@ class FilesApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
@ -175,5 +169,4 @@ class FilesApiController extends BaseApiController
return $filePath; return $filePath;
} }
} }

View File

@ -34,13 +34,11 @@ class GenericEntityApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
else else
{ {
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed'); return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
} }
} }
public function DeleteObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function DeleteObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -59,7 +57,6 @@ class GenericEntityApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function EditObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function EditObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -87,13 +84,11 @@ class GenericEntityApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
else else
{ {
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed'); return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
} }
} }
public function GetObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetObject(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -123,7 +118,6 @@ class GenericEntityApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed'); return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
} }
} }
public function GetObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -143,7 +137,6 @@ class GenericEntityApiController extends BaseApiController
{ {
$userfieldKeyValuePairs[$userfield->name] = $userfield->value; $userfieldKeyValuePairs[$userfield->name] = $userfield->value;
} }
} }
$object->userfields = $userfieldKeyValuePairs; $object->userfields = $userfieldKeyValuePairs;
@ -157,7 +150,6 @@ class GenericEntityApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed'); return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
} }
} }
public function GetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -170,7 +162,6 @@ class GenericEntityApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function SearchObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function SearchObjects(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -187,13 +178,11 @@ class GenericEntityApiController extends BaseApiController
throw new HttpBadRequestException($request, $ex->getMessage(), $ex); throw new HttpBadRequestException($request, $ex->getMessage(), $ex);
//return $this->GenericErrorResponse($response, 'The given entity has no field "name"', $ex); //return $this->GenericErrorResponse($response, 'The given entity has no field "name"', $ex);
} }
} }
else else
{ {
return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed'); return $this->GenericErrorResponse($response, 'Entity does not exist or is not exposed');
} }
} }
public function SetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function SetUserfields(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -216,7 +205,6 @@ class GenericEntityApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
@ -233,5 +221,4 @@ class GenericEntityApiController extends BaseApiController
{ {
return in_array($entity, $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum); return in_array($entity, $this->getOpenApiSpec()->components->internalSchemas->ExposedEntity->enum);
} }
} }

View File

@ -26,7 +26,6 @@ class GenericEntityController extends BaseController
'userentity' => $this->getDatabase()->userentities($args['userentityId']) 'userentity' => $this->getDatabase()->userentities($args['userentityId'])
]); ]);
} }
} }
public function UserfieldEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserfieldEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -48,7 +47,6 @@ class GenericEntityController extends BaseController
'entities' => $this->getUserfieldsService()->GetEntities() 'entities' => $this->getUserfieldsService()->GetEntities()
]); ]);
} }
} }
public function UserfieldsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserfieldsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -80,7 +78,6 @@ class GenericEntityController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName']) 'userfields' => $this->getUserfieldsService()->GetFields('userentity-' . $args['userentityName'])
]); ]);
} }
} }
public function UserobjectsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserobjectsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -99,5 +96,4 @@ class GenericEntityController extends BaseController
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -37,7 +37,7 @@ class LoginController extends BaseController
$sessionKey = $this->getSessionService()->CreateSession($user->id, $stayLoggedInPermanently); $sessionKey = $this->getSessionService()->CreateSession($user->id, $stayLoggedInPermanently);
setcookie($this->SessionCookieName, $sessionKey, PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX >> 32); setcookie($this->SessionCookieName, $sessionKey, PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX >> 32);
// Cookie expires never, but session validity is up to SessionService // Cookie expires never, but session validity is up to SessionService
if (password_needs_rehash($user->password, PASSWORD_DEFAULT)) if (password_needs_rehash($user->password, PASSWORD_DEFAULT))
{ {
@ -52,13 +52,11 @@ class LoginController extends BaseController
{ {
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true')); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true'));
} }
} }
else else
{ {
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true')); return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true'));
} }
} }
public function __construct(\DI\Container $container, string $sessionCookieName) public function __construct(\DI\Container $container, string $sessionCookieName)
@ -66,5 +64,4 @@ class LoginController extends BaseController
parent::__construct($container); parent::__construct($container);
$this->SessionCookieName = $sessionCookieName; $this->SessionCookieName = $sessionCookieName;
} }
} }

View File

@ -35,7 +35,6 @@ class RecipesApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function GetRecipeFulfillment(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetRecipeFulfillment(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -57,18 +56,15 @@ class RecipesApiController extends BaseApiController
{ {
return $this->ApiResponse($response, $recipeResolved); return $this->ApiResponse($response, $recipeResolved);
} }
} }
catch (\Exception $ex) catch (\Exception $ex)
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -70,7 +70,6 @@ class RecipesController extends BaseController
$selectedRecipe = $recipe; $selectedRecipe = $recipe;
break; break;
} }
} }
$selectedRecipePositionsResolved = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $selectedRecipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC'); $selectedRecipePositionsResolved = $this->getDatabase()->recipes_pos_resolved()->where('recipe_id = :1 AND is_nested_recipe_pos = 0', $selectedRecipe->id)->orderBy('ingredient_group', 'ASC', 'product_group', 'ASC');
@ -160,7 +159,6 @@ class RecipesController extends BaseController
'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved() 'quantityUnitConversionsResolved' => $this->getDatabase()->quantity_unit_conversions_resolved()
]); ]);
} }
} }
public function RecipesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function RecipesSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -172,5 +170,4 @@ class RecipesController extends BaseController
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -29,7 +29,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function AddProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function AddProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -99,7 +98,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function AddProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function AddProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -113,7 +111,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function AddProductToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function AddProductToShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -161,7 +158,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ClearShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ClearShoppingList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -186,7 +182,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ConsumeProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ConsumeProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -266,7 +261,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function CurrentStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function CurrentStock(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -346,7 +340,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ExternalBarcodeLookup(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ExternalBarcodeLookup(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -368,7 +361,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function InventoryProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function InventoryProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -424,7 +416,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function InventoryProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function InventoryProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -438,7 +429,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function OpenProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function OpenProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -473,7 +463,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function OpenProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function OpenProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -487,7 +476,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ProductBarcodeDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductBarcodeDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -500,7 +488,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ProductDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductDetails(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -513,7 +500,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ProductDetailsByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductDetailsByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -527,7 +513,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ProductPriceHistory(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductPriceHistory(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -540,7 +525,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ProductStockEntries(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductStockEntries(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -599,7 +583,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function StockBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function StockBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -619,7 +602,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function StockEntry(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function StockEntry(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -644,7 +626,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function TransferProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TransferProduct(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -689,7 +670,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function TransferProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TransferProductByBarcode(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -703,7 +683,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function UndoBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UndoBooking(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -719,7 +698,6 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function UndoTransaction(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UndoTransaction(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -735,12 +713,10 @@ class StockApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -67,7 +67,6 @@ class StockController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('locations') 'userfields' => $this->getUserfieldsService()->GetFields('locations')
]); ]);
} }
} }
public function LocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function LocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -122,7 +121,6 @@ class StockController extends BaseController
'shoppinglocations' => $this->getDatabase()->shopping_locations()->orderBy('name') 'shoppinglocations' => $this->getDatabase()->shopping_locations()->orderBy('name')
]); ]);
} }
} }
public function ProductEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -159,7 +157,6 @@ class StockController extends BaseController
'quConversions' => $this->getDatabase()->quantity_unit_conversions() 'quConversions' => $this->getDatabase()->quantity_unit_conversions()
]); ]);
} }
} }
public function ProductGroupEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductGroupEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -179,7 +176,6 @@ class StockController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('product_groups') 'userfields' => $this->getUserfieldsService()->GetFields('product_groups')
]); ]);
} }
} }
public function ProductGroupsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ProductGroupsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -254,7 +250,6 @@ class StockController extends BaseController
'defaultQuUnit' => $defaultQuUnit 'defaultQuUnit' => $defaultQuUnit
]); ]);
} }
} }
public function QuantityUnitEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function QuantityUnitEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -282,7 +277,6 @@ class StockController extends BaseController
'quantityUnits' => $this->getDatabase()->quantity_units() 'quantityUnits' => $this->getDatabase()->quantity_units()
]); ]);
} }
} }
public function QuantityUnitPluralFormTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function QuantityUnitPluralFormTesting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -338,7 +332,6 @@ class StockController extends BaseController
'mode' => 'edit' 'mode' => 'edit'
]); ]);
} }
} }
public function ShoppingListItemEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ShoppingListItemEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -360,7 +353,6 @@ class StockController extends BaseController
'mode' => 'edit' 'mode' => 'edit'
]); ]);
} }
} }
public function ShoppingListSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ShoppingListSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -385,7 +377,6 @@ class StockController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('shopping_locations') 'userfields' => $this->getUserfieldsService()->GetFields('shopping_locations')
]); ]);
} }
} }
public function ShoppingLocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ShoppingLocationsList(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -451,5 +442,4 @@ class StockController extends BaseController
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -11,10 +11,7 @@ class SystemApiController extends BaseApiController
$constants = get_defined_constants(); $constants = get_defined_constants();
// Some GROCY_* constants are not really config settings and therefore should not be exposed // Some GROCY_* constants are not really config settings and therefore should not be exposed
unset($constants['GROCY_AUTHENTICATED']); unset($constants['GROCY_AUTHENTICATED'], $constants['GROCY_DATAPATH'], $constants['GROCY_IS_EMBEDDED_INSTALL'], $constants['GROCY_USER_ID']);
unset($constants['GROCY_DATAPATH']);
unset($constants['GROCY_IS_EMBEDDED_INSTALL']);
unset($constants['GROCY_USER_ID']);
$returnArray = []; $returnArray = [];
@ -24,7 +21,6 @@ class SystemApiController extends BaseApiController
{ {
$returnArray[substr($constant, 6)] = $value; $returnArray[substr($constant, 6)] = $value;
} }
} }
return $this->ApiResponse($response, $returnArray); return $this->ApiResponse($response, $returnArray);
@ -33,7 +29,6 @@ class SystemApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function GetDbChangedTime(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetDbChangedTime(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -63,14 +58,11 @@ class SystemApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -59,37 +59,37 @@ class SystemController extends BaseController
$entryPage = 'stock'; $entryPage = 'stock';
} }
// Stock // Stock
if ($entryPage === 'stock' && constant('GROCY_FEATURE_FLAG_STOCK')) if ($entryPage === 'stock' && constant('GROCY_FEATURE_FLAG_STOCK'))
{ {
return '/stockoverview'; return '/stockoverview';
} }
// Shoppinglist // Shoppinglist
if ($entryPage === 'shoppinglist' && constant('GROCY_FEATURE_FLAG_SHOPPINGLIST')) if ($entryPage === 'shoppinglist' && constant('GROCY_FEATURE_FLAG_SHOPPINGLIST'))
{ {
return '/shoppinglist'; return '/shoppinglist';
} }
// Recipes // Recipes
if ($entryPage === 'recipes' && constant('GROCY_FEATURE_FLAG_RECIPES')) if ($entryPage === 'recipes' && constant('GROCY_FEATURE_FLAG_RECIPES'))
{ {
return '/recipes'; return '/recipes';
} }
// Chores // Chores
if ($entryPage === 'chores' && constant('GROCY_FEATURE_FLAG_CHORES')) if ($entryPage === 'chores' && constant('GROCY_FEATURE_FLAG_CHORES'))
{ {
return '/choresoverview'; return '/choresoverview';
} }
// Tasks // Tasks
if ($entryPage === 'tasks' && constant('GROCY_FEATURE_FLAG_TASKS')) if ($entryPage === 'tasks' && constant('GROCY_FEATURE_FLAG_TASKS'))
{ {
return '/tasks'; return '/tasks';
} }
// Batteries // Batteries
if ($entryPage === 'batteries' && constant('GROCY_FEATURE_FLAG_BATTERIES')) if ($entryPage === 'batteries' && constant('GROCY_FEATURE_FLAG_BATTERIES'))
{ {
return '/batteriesoverview'; return '/batteriesoverview';
@ -100,13 +100,13 @@ class SystemController extends BaseController
return '/equipment'; return '/equipment';
} }
// Calendar // Calendar
if ($entryPage === 'calendar' && constant('GROCY_FEATURE_FLAG_CALENDAR')) if ($entryPage === 'calendar' && constant('GROCY_FEATURE_FLAG_CALENDAR'))
{ {
return '/calendar'; return '/calendar';
} }
// Meal Plan // Meal Plan
if ($entryPage === 'mealplan' && constant('GROCY_FEATURE_FLAG_RECIPES')) if ($entryPage === 'mealplan' && constant('GROCY_FEATURE_FLAG_RECIPES'))
{ {
return '/mealplan'; return '/mealplan';
@ -114,5 +114,4 @@ class SystemController extends BaseController
return '/about'; return '/about';
} }
} }

View File

@ -33,7 +33,6 @@ class TasksApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function UndoTask(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UndoTask(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -49,12 +48,10 @@ class TasksApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -54,7 +54,6 @@ class TasksController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('task_categories') 'userfields' => $this->getUserfieldsService()->GetFields('task_categories')
]); ]);
} }
} }
public function TaskEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TaskEditForm(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -78,7 +77,6 @@ class TasksController extends BaseController
'userfields' => $this->getUserfieldsService()->GetFields('tasks') 'userfields' => $this->getUserfieldsService()->GetFields('tasks')
]); ]);
} }
} }
public function TasksSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function TasksSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -90,5 +88,4 @@ class TasksController extends BaseController
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -10,17 +10,13 @@ class User
const PERMISSION_ADMIN = 'ADMIN'; const PERMISSION_ADMIN = 'ADMIN';
const PERMISSION_BATTERIES = 'BATTERIES'; const PERMISSION_BATTERIES = 'BATTERIES';
const PERMISSION_BATTERIES_TRACK_CHARGE_CYCLE = 'BATTERIES_TRACK_CHARGE_CYCLE'; const PERMISSION_BATTERIES_TRACK_CHARGE_CYCLE = 'BATTERIES_TRACK_CHARGE_CYCLE';
const PERMISSION_BATTERIES_UNDO_CHARGE_CYCLE = 'BATTERIES_UNDO_CHARGE_CYCLE'; const PERMISSION_BATTERIES_UNDO_CHARGE_CYCLE = 'BATTERIES_UNDO_CHARGE_CYCLE';
const PERMISSION_CALENDAR = 'CALENDAR'; const PERMISSION_CALENDAR = 'CALENDAR';
const PERMISSION_CHORES = 'CHORES'; const PERMISSION_CHORES = 'CHORES';
const PERMISSION_CHORE_TRACK_EXECUTION = 'CHORE_TRACK_EXECUTION'; const PERMISSION_CHORE_TRACK_EXECUTION = 'CHORE_TRACK_EXECUTION';
const PERMISSION_CHORE_UNDO_EXECUTION = 'CHORE_UNDO_EXECUTION'; const PERMISSION_CHORE_UNDO_EXECUTION = 'CHORE_UNDO_EXECUTION';
const PERMISSION_EQUIPMENT = 'EQUIPMENT'; const PERMISSION_EQUIPMENT = 'EQUIPMENT';
@ -28,43 +24,28 @@ class User
const PERMISSION_MASTER_DATA_EDIT = 'MASTER_DATA_EDIT'; const PERMISSION_MASTER_DATA_EDIT = 'MASTER_DATA_EDIT';
const PERMISSION_RECIPES = 'RECIPES'; const PERMISSION_RECIPES = 'RECIPES';
const PERMISSION_RECIPES_MEALPLAN = 'RECIPES_MEALPLAN'; const PERMISSION_RECIPES_MEALPLAN = 'RECIPES_MEALPLAN';
const PERMISSION_SHOPPINGLIST = 'SHOPPINGLIST'; const PERMISSION_SHOPPINGLIST = 'SHOPPINGLIST';
const PERMISSION_SHOPPINGLIST_ITEMS_ADD = 'SHOPPINGLIST_ITEMS_ADD'; const PERMISSION_SHOPPINGLIST_ITEMS_ADD = 'SHOPPINGLIST_ITEMS_ADD';
const PERMISSION_SHOPPINGLIST_ITEMS_DELETE = 'SHOPPINGLIST_ITEMS_DELETE'; const PERMISSION_SHOPPINGLIST_ITEMS_DELETE = 'SHOPPINGLIST_ITEMS_DELETE';
const PERMISSION_STOCK = 'STOCK'; const PERMISSION_STOCK = 'STOCK';
const PERMISSION_STOCK_CONSUME = 'STOCK_CONSUME'; const PERMISSION_STOCK_CONSUME = 'STOCK_CONSUME';
const PERMISSION_STOCK_EDIT = 'STOCK_EDIT'; const PERMISSION_STOCK_EDIT = 'STOCK_EDIT';
const PERMISSION_STOCK_INVENTORY = 'STOCK_INVENTORY'; const PERMISSION_STOCK_INVENTORY = 'STOCK_INVENTORY';
const PERMISSION_STOCK_OPEN = 'STOCK_OPEN'; const PERMISSION_STOCK_OPEN = 'STOCK_OPEN';
const PERMISSION_STOCK_PURCHASE = 'STOCK_PURCHASE'; const PERMISSION_STOCK_PURCHASE = 'STOCK_PURCHASE';
const PERMISSION_STOCK_TRANSFER = 'STOCK_TRANSFER'; const PERMISSION_STOCK_TRANSFER = 'STOCK_TRANSFER';
const PERMISSION_TASKS = 'TASKS'; const PERMISSION_TASKS = 'TASKS';
const PERMISSION_TASKS_MARK_COMPLETED = 'TASKS_MARK_COMPLETED'; const PERMISSION_TASKS_MARK_COMPLETED = 'TASKS_MARK_COMPLETED';
const PERMISSION_TASKS_UNDO_EXECUTION = 'TASKS_UNDO_EXECUTION'; const PERMISSION_TASKS_UNDO_EXECUTION = 'TASKS_UNDO_EXECUTION';
const PERMISSION_USERS = 'USERS'; const PERMISSION_USERS = 'USERS';
const PERMISSION_USERS_CREATE = 'USERS_CREATE'; const PERMISSION_USERS_CREATE = 'USERS_CREATE';
const PERMISSION_USERS_EDIT = 'USERS_EDIT'; const PERMISSION_USERS_EDIT = 'USERS_EDIT';
const PERMISSION_USERS_EDIT_SELF = 'USERS_EDIT_SELF'; const PERMISSION_USERS_EDIT_SELF = 'USERS_EDIT_SELF';
const PERMISSION_USERS_READ = 'USERS_READ'; const PERMISSION_USERS_READ = 'USERS_READ';
/** /**
@ -81,10 +62,9 @@ class User
public function __construct() public function __construct()
{ {
$this->db = DatabaseService::getInstance()->GetDbConnection(); $this->db = DatabaseService::getInstance()->GetDbConnection();
} }
public static function checkPermission($request, string...$permissions): void public static function checkPermission($request, string ...$permissions): void
{ {
$user = new self(); $user = new self();
@ -94,9 +74,7 @@ class User
{ {
throw new PermissionMissingException($request, $permission); throw new PermissionMissingException($request, $permission);
} }
} }
} }
public function getPermissionList() public function getPermissionList()
@ -106,14 +84,14 @@ class User
public function hasPermission(string $permission): bool public function hasPermission(string $permission): bool
{ {
// global $PERMISSION_CACHE; // global $PERMISSION_CACHE;
// if(isset($PERMISSION_CACHE[$permission])) // if(isset($PERMISSION_CACHE[$permission]))
// return $PERMISSION_CACHE[$permission]; // return $PERMISSION_CACHE[$permission];
return $this->getPermissions()->where('permission_name', $permission)->fetch() !== null; return $this->getPermissions()->where('permission_name', $permission)->fetch() !== null;
} }
public static function hasPermissions(string...$permissions) public static function hasPermissions(string ...$permissions)
{ {
$user = new self(); $user = new self();
@ -123,7 +101,6 @@ class User
{ {
return false; return false;
} }
} }
return true; return true;
@ -133,5 +110,4 @@ class User
{ {
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

@ -8,7 +8,8 @@ class UsersApiController extends BaseApiController
{ {
public function AddPermission(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function AddPermission(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try { try
{
User::checkPermission($request, User::PERMISSION_ADMIN); User::checkPermission($request, User::PERMISSION_ADMIN);
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
@ -26,7 +27,6 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function CreateUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function CreateUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -48,7 +48,6 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function DeleteUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function DeleteUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -63,7 +62,6 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function EditUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function EditUser(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -88,7 +86,6 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function GetUserSetting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetUserSetting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -102,7 +99,6 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function GetUserSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetUserSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -115,7 +111,6 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function GetUsers(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function GetUsers(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -129,15 +124,16 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function ListPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function ListPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try { try
{
User::checkPermission($request, User::PERMISSION_ADMIN); User::checkPermission($request, User::PERMISSION_ADMIN);
return $this->ApiResponse($response, return $this->ApiResponse(
$response,
$this->getDatabase()->user_permissions()->where($args['userId']) $this->getDatabase()->user_permissions()->where($args['userId'])
); );
} }
@ -149,12 +145,12 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function SetPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function SetPermissions(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
try { try
{
User::checkPermission($request, User::PERMISSION_ADMIN); User::checkPermission($request, User::PERMISSION_ADMIN);
$requestBody = $request->getParsedBody(); $requestBody = $request->getParsedBody();
$db = $this->getDatabase(); $db = $this->getDatabase();
@ -184,7 +180,6 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function SetUserSetting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function SetUserSetting(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@ -200,12 +195,10 @@ class UsersApiController extends BaseApiController
{ {
return $this->GenericErrorResponse($response, $ex->getMessage()); return $this->GenericErrorResponse($response, $ex->getMessage());
} }
} }
public function __construct(\DI\Container $container) public function __construct(\DI\Container $container)
{ {
parent::__construct($container); parent::__construct($container);
} }
} }

View File

@ -41,14 +41,12 @@ class UsersController extends BaseController
'mode' => 'edit' 'mode' => 'edit'
]); ]);
} }
} }
public function UserSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args) public function UserSettings(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{ {
return $this->renderPage($response, 'usersettings', [ return $this->renderPage($response, 'usersettings', [
'languages' => array_filter(scandir(__DIR__ . '/../localization'), function ($item) 'languages' => array_filter(scandir(__DIR__ . '/../localization'), function ($item) {
{
if ($item == '.' || $item == '..') if ($item == '.' || $item == '..')
{ {
return false; return false;
@ -56,7 +54,6 @@ class UsersController extends BaseController
return is_dir(__DIR__ . '/../localization/' . $item); return is_dir(__DIR__ . '/../localization/' . $item);
}) })
]); ]);
} }
@ -67,5 +64,4 @@ class UsersController extends BaseController
'users' => $this->getDatabase()->users()->orderBy('username') 'users' => $this->getDatabase()->users()->orderBy('username')
]); ]);
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
use \Grocy\Helpers\BaseBarcodeLookupPlugin; use Grocy\Helpers\BaseBarcodeLookupPlugin;
/* /*
This class must extend BaseBarcodeLookupPlugin (in namespace \Grocy\Helpers) This class must extend BaseBarcodeLookupPlugin (in namespace \Grocy\Helpers)
@ -55,24 +55,24 @@ class DemoBarcodeLookupPlugin extends BaseBarcodeLookupPlugin
*/ */
protected function ExecuteLookup($barcode) protected function ExecuteLookup($barcode)
{ {
if ($barcode === 'x') // Demonstration when nothing is found if ($barcode === 'x')
{ { // Demonstration when nothing is found
return null; return null;
} }
elseif ($barcode === 'e') // Demonstration when an error occurred elseif ($barcode === 'e')
{ { // Demonstration when an error occurred
throw new \Exception('This is the error message from the plugin...'); throw new \Exception('This is the error message from the plugin...');
} }
else else
{ {
return array( return [
'name' => 'LookedUpProduct_' . RandomString(5), 'name' => 'LookedUpProduct_' . RandomString(5),
'location_id' => $this->Locations[0]->id, 'location_id' => $this->Locations[0]->id,
'qu_id_purchase' => $this->QuantityUnits[0]->id, 'qu_id_purchase' => $this->QuantityUnits[0]->id,
'qu_id_stock' => $this->QuantityUnits[0]->id, 'qu_id_stock' => $this->QuantityUnits[0]->id,
'qu_factor_purchase_to_stock' => 1, 'qu_factor_purchase_to_stock' => 1,
'barcode' => $barcode 'barcode' => $barcode
); ];
} }
} }
} }

View File

@ -17,14 +17,14 @@ abstract class BaseBarcodeLookupPlugin
return $pluginOutput; return $pluginOutput;
} }
// Plugin must return an associative array // Plugin must return an associative array
if (!is_array($pluginOutput)) if (!is_array($pluginOutput))
{ {
throw new \Exception('Plugin output must be an associative array'); throw new \Exception('Plugin output must be an associative array');
} }
if (!IsAssociativeArray($pluginOutput)) // $pluginOutput is at least an indexed array here if (!IsAssociativeArray($pluginOutput))
{ { // $pluginOutput is at least an indexed array here
throw new \Exception('Plugin output must be an associative array'); throw new \Exception('Plugin output must be an associative array');
} }
@ -44,10 +44,9 @@ abstract class BaseBarcodeLookupPlugin
{ {
throw new \Exception("Plugin output does not provide needed property $prop"); throw new \Exception("Plugin output does not provide needed property $prop");
} }
} }
// $pluginOutput contains all needed properties here // $pluginOutput contains all needed properties here
// Check referenced entity ids are valid // Check referenced entity ids are valid
$locationId = $pluginOutput['location_id']; $locationId = $pluginOutput['location_id'];

View File

@ -24,7 +24,6 @@ class PrerequisiteChecker
{ {
throw new ERequirementNotMet('/vendor/autoload.php not found. Have you run Composer?'); throw new ERequirementNotMet('/vendor/autoload.php not found. Have you run Composer?');
} }
} }
private function checkForConfigDistFile() private function checkForConfigDistFile()
@ -33,7 +32,6 @@ class PrerequisiteChecker
{ {
throw new ERequirementNotMet('config-dist.php not found. Please do not remove this file.'); throw new ERequirementNotMet('config-dist.php not found. Please do not remove this file.');
} }
} }
private function checkForConfigFile() private function checkForConfigFile()
@ -42,7 +40,6 @@ class PrerequisiteChecker
{ {
throw new ERequirementNotMet('config.php in data directory (' . GROCY_DATAPATH . ') not found. Have you copied config-dist.php to the data directory and renamed it to config.php?'); throw new ERequirementNotMet('config.php in data directory (' . GROCY_DATAPATH . ') not found. Have you copied config-dist.php to the data directory and renamed it to config.php?');
} }
} }
private function checkForPhpExtensions() private function checkForPhpExtensions()
@ -55,9 +52,7 @@ class PrerequisiteChecker
{ {
throw new ERequirementNotMet("PHP module '{$extension}' not installed, but required."); throw new ERequirementNotMet("PHP module '{$extension}' not installed, but required.");
} }
} }
} }
private function checkForSqliteVersion() private function checkForSqliteVersion()
@ -68,7 +63,6 @@ class PrerequisiteChecker
{ {
throw new ERequirementNotMet('SQLite ' . REQUIRED_SQLITE_VERSION . ' is required, however you are running ' . $sqliteVersion); throw new ERequirementNotMet('SQLite ' . REQUIRED_SQLITE_VERSION . ' is required, however you are running ' . $sqliteVersion);
} }
} }
private function getSqlVersionAsString() private function getSqlVersionAsString()
@ -76,5 +70,4 @@ class PrerequisiteChecker
$dbh = new PDO('sqlite::memory:'); $dbh = new PDO('sqlite::memory:');
return $dbh->query('select sqlite_version()')->fetch()[0]; return $dbh->query('select sqlite_version()')->fetch()[0];
} }
} }

View File

@ -12,11 +12,10 @@ class UrlManager
{ {
return rtrim($this->BasePath, '/') . $relativePath; return rtrim($this->BasePath, '/') . $relativePath;
} }
else // Is not a resource and URL rewriting is disabled else
{ { // Is not a resource and URL rewriting is disabled
return rtrim($this->BasePath, '/') . '/index.php' . $relativePath; return rtrim($this->BasePath, '/') . '/index.php' . $relativePath;
} }
} }
public function __construct(string $basePath) public function __construct(string $basePath)
@ -29,7 +28,6 @@ class UrlManager
{ {
$this->BasePath = $basePath; $this->BasePath = $basePath;
} }
} }
private function GetBaseUrl() private function GetBaseUrl()
@ -41,5 +39,4 @@ class UrlManager
return (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]"; return (isset($_SERVER['HTTPS']) ? 'https' : 'http') . "://$_SERVER[HTTP_HOST]";
} }
} }

View File

@ -9,7 +9,6 @@ function FindObjectInArrayByPropertyValue($array, $propertyName, $propertyValue)
{ {
return $object; return $object;
} }
} }
return null; return null;
@ -25,7 +24,7 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
{ {
case '==': case '==':
if ($object-> {$propertyName} if ($object->{$propertyName}
== $propertyValue) == $propertyValue)
{ {
$returnArray[] = $object; $returnArray[] = $object;
@ -34,7 +33,7 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
break; break;
case '>': case '>':
if ($object-> {$propertyName} if ($object->{$propertyName}
> $propertyValue) > $propertyValue)
{ {
$returnArray[] = $object; $returnArray[] = $object;
@ -43,7 +42,7 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
break; break;
case '<': case '<':
if ($object-> {$propertyName} if ($object->{$propertyName}
< $propertyValue) < $propertyValue)
{ {
$returnArray[] = $object; $returnArray[] = $object;
@ -51,7 +50,6 @@ function FindAllObjectsInArrayByPropertyValue($array, $propertyName, $propertyVa
break; break;
} }
} }
return $returnArray; return $returnArray;
@ -90,7 +88,6 @@ function FindAllItemsInArrayByValue($array, $value, $operator = '==')
break; break;
} }
} }
return $returnArray; return $returnArray;
@ -122,7 +119,6 @@ function GetClassConstants($className, $prefix = null)
$matchingKeys = preg_grep('!^' . $prefix . '!', array_keys($constants)); $matchingKeys = preg_grep('!^' . $prefix . '!', array_keys($constants));
return array_intersect_key($constants, array_flip($matchingKeys)); return array_intersect_key($constants, array_flip($matchingKeys));
} }
} }
function RandomString($length, $allowedChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') function RandomString($length, $allowedChars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
@ -188,17 +184,15 @@ function Setting(string $name, $value)
{ {
define('GROCY_' . $name, ExternalSettingValue(file_get_contents($settingOverrideFile))); define('GROCY_' . $name, ExternalSettingValue(file_get_contents($settingOverrideFile)));
} }
elseif (getenv('GROCY_' . $name) !== false) // An environment variable with the same name and prefix GROCY_ overwrites the given setting elseif (getenv('GROCY_' . $name) !== false)
{ { // An environment variable with the same name and prefix GROCY_ overwrites the given setting
define('GROCY_' . $name, ExternalSettingValue(getenv('GROCY_' . $name))); define('GROCY_' . $name, ExternalSettingValue(getenv('GROCY_' . $name)));
} }
else else
{ {
define('GROCY_' . $name, $value); define('GROCY_' . $name, $value);
} }
} }
} }
global $GROCY_DEFAULT_USER_SETTINGS; global $GROCY_DEFAULT_USER_SETTINGS;
@ -211,7 +205,6 @@ function DefaultUserSetting(string $name, $value)
{ {
$GROCY_DEFAULT_USER_SETTINGS[$name] = $value; $GROCY_DEFAULT_USER_SETTINGS[$name] = $value;
} }
} }
function GetUserDisplayName($user) function GetUserDisplayName($user)

View File

@ -17,7 +17,7 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
$this->ApiKeyHeaderName = $this->AppContainer->get('ApiKeyHeaderName'); $this->ApiKeyHeaderName = $this->AppContainer->get('ApiKeyHeaderName');
} }
function authenticate(Request $request) public function authenticate(Request $request)
{ {
if (!defined('GROCY_SHOW_AUTH_VIEWS')) if (!defined('GROCY_SHOW_AUTH_VIEWS'))
{ {
@ -33,7 +33,7 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
$apiKeyService = new ApiKeyService(); $apiKeyService = new ApiKeyService();
// First check of the API key in the configured header // First check of the API key in the configured header
if (!$request->hasHeader($this->ApiKeyHeaderName) || !$apiKeyService->IsValidApiKey($request->getHeaderLine($this->ApiKeyHeaderName))) if (!$request->hasHeader($this->ApiKeyHeaderName) || !$apiKeyService->IsValidApiKey($request->getHeaderLine($this->ApiKeyHeaderName)))
{ {
$validApiKey = false; $validApiKey = false;
@ -43,14 +43,14 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
$usedApiKey = $request->getHeaderLine($this->ApiKeyHeaderName); $usedApiKey = $request->getHeaderLine($this->ApiKeyHeaderName);
} }
// Not recommended, but it's also possible to provide the API key via a query parameter (same name as the configured header) // Not recommended, but it's also possible to provide the API key via a query parameter (same name as the configured header)
if (!$validApiKey && !empty($request->getQueryParam($this->ApiKeyHeaderName)) && $apiKeyService->IsValidApiKey($request->getQueryParam($this->ApiKeyHeaderName))) if (!$validApiKey && !empty($request->getQueryParam($this->ApiKeyHeaderName)) && $apiKeyService->IsValidApiKey($request->getQueryParam($this->ApiKeyHeaderName)))
{ {
$validApiKey = true; $validApiKey = true;
$usedApiKey = $request->getQueryParam($this->ApiKeyHeaderName); $usedApiKey = $request->getQueryParam($this->ApiKeyHeaderName);
} }
// Handling of special purpose API keys // Handling of special purpose API keys
if (!$validApiKey) if (!$validApiKey)
{ {
if ($routeName === 'calendar-ical') if ($routeName === 'calendar-ical')
@ -59,21 +59,16 @@ class ApiKeyAuthMiddleware extends AuthMiddleware
{ {
$validApiKey = true; $validApiKey = true;
} }
} }
} }
if ($validApiKey) if ($validApiKey)
{ {
return $apiKeyService->GetUserByApiKey($usedApiKey); return $apiKeyService->GetUserByApiKey($usedApiKey);
} }
else else
{ {
return null; return null;
} }
} }
} }

View File

@ -30,9 +30,7 @@ abstract class AuthMiddleware extends BaseMiddleware
{ {
return $handler->handle($request); return $handler->handle($request);
} }
else elseif ($routeName === 'login')
if ($routeName === 'login')
{ {
define('GROCY_AUTHENTICATED', false); define('GROCY_AUTHENTICATED', false);
return $handler->handle($request); return $handler->handle($request);
@ -66,7 +64,6 @@ abstract class AuthMiddleware extends BaseMiddleware
{ {
return $response->withHeader('Location', $this->AppContainer->get('UrlManager')->ConstructUrl('/login')); return $response->withHeader('Location', $this->AppContainer->get('UrlManager')->ConstructUrl('/login'));
} }
} }
else else
{ {
@ -76,9 +73,7 @@ abstract class AuthMiddleware extends BaseMiddleware
return $response = $handler->handle($request); return $response = $handler->handle($request);
} }
} }
} }
/** /**
@ -86,5 +81,5 @@ abstract class AuthMiddleware extends BaseMiddleware
* @return mixed|null the user row or null if the request is not authenticated * @return mixed|null the user row or null if the request is not authenticated
* @throws \Exception Throws an \Exception if config is invalid. * @throws \Exception Throws an \Exception if config is invalid.
*/ */
protected abstract function authenticate(Request $request); abstract protected function authenticate(Request $request);
} }

View File

@ -28,14 +28,13 @@ class CorsMiddleware
else else
{ {
$response = $handler->handle($request); $response = $handler->handle($request);
} }
//$routeContext = RouteContext::fromRequest($request); //$routeContext = RouteContext::fromRequest($request);
//$routingResults = $routeContext->getRoutingResults(); //$routingResults = $routeContext->getRoutingResults();
//$methods = $routingResults->getAllowedMethods(); //$methods = $routingResults->getAllowedMethods();
//$requestHeaders = $request->getHeaderLine('Access-Control-Request-Headers'); //$requestHeaders = $request->getHeaderLine('Access-Control-Request-Headers');
$response = $response->withHeader('Access-Control-Allow-Origin', '*'); $response = $response->withHeader('Access-Control-Allow-Origin', '*');
@ -44,5 +43,4 @@ class CorsMiddleware
return $response; return $response;
} }
} }

View File

@ -22,5 +22,4 @@ class DefaultAuthMiddleware extends AuthMiddleware
$user = $auth->authenticate($request); $user = $auth->authenticate($request);
return $user; return $user;
} }
} }

View File

@ -25,7 +25,5 @@ class JsonMiddleware extends BaseMiddleware
return $response; return $response;
} }
} }
} }

View File

@ -28,9 +28,7 @@ class LocaleMiddleware extends BaseMiddleware
{ {
return $locale; return $locale;
} }
} }
} }
$langs = implode(',', $request->getHeader('Accept-Language')); $langs = implode(',', $request->getHeader('Accept-Language'));
@ -38,12 +36,13 @@ class LocaleMiddleware extends BaseMiddleware
// src: https://gist.github.com/spolischook/0cde9c6286415cddc088 // src: https://gist.github.com/spolischook/0cde9c6286415cddc088
$prefLocales = array_reduce( $prefLocales = array_reduce(
explode(',', $langs), explode(',', $langs),
function ($res, $el) function ($res, $el) {
{
list($l, $q) = array_merge(explode(';q=', $el), [1]); list($l, $q) = array_merge(explode(';q=', $el), [1]);
$res[$l] = (float) $q; $res[$l] = (float) $q;
return $res; return $res;
}, []); },
[]
);
arsort($prefLocales); arsort($prefLocales);
$availableLocales = scandir(__DIR__ . '/../localization'); $availableLocales = scandir(__DIR__ . '/../localization');
@ -55,25 +54,23 @@ class LocaleMiddleware extends BaseMiddleware
return $locale; return $locale;
} }
// e.g. en_GB // e.g. en_GB
if (in_array(substr($locale, 0, 5), $availableLocales)) if (in_array(substr($locale, 0, 5), $availableLocales))
{ {
return substr($locale, 0, 5); return substr($locale, 0, 5);
} }
// e.g: cs // e.g: cs
// or en // or en
// or de // or de
if (in_array(substr($locale, 0, 2), $availableLocales)) if (in_array(substr($locale, 0, 2), $availableLocales))
{ {
return substr($locale, 0, 2); return substr($locale, 0, 2);
} }
} }
return GROCY_DEFAULT_LOCALE; return GROCY_DEFAULT_LOCALE;
} }
} }

View File

@ -8,7 +8,7 @@ use Psr\Http\Message\ServerRequestInterface as Request;
class ReverseProxyAuthMiddleware extends AuthMiddleware class ReverseProxyAuthMiddleware extends AuthMiddleware
{ {
function authenticate(Request $request) public function authenticate(Request $request)
{ {
if (!defined('GROCY_SHOW_AUTH_VIEWS')) if (!defined('GROCY_SHOW_AUTH_VIEWS'))
{ {
@ -36,5 +36,4 @@ class ReverseProxyAuthMiddleware extends AuthMiddleware
return $user; return $user;
} }
} }

View File

@ -16,7 +16,7 @@ class SessionAuthMiddleware extends AuthMiddleware
$this->SessionCookieName = $this->AppContainer->get('LoginControllerInstance')->GetSessionCookieName(); $this->SessionCookieName = $this->AppContainer->get('LoginControllerInstance')->GetSessionCookieName();
} }
function authenticate(Request $request) public function authenticate(Request $request)
{ {
if (!defined('GROCY_SHOW_AUTH_VIEWS')) if (!defined('GROCY_SHOW_AUTH_VIEWS'))
{ {
@ -33,7 +33,5 @@ class SessionAuthMiddleware extends AuthMiddleware
{ {
return $sessionService->GetUserBySessionKey($_COOKIE[$this->SessionCookieName]); return $sessionService->GetUserBySessionKey($_COOKIE[$this->SessionCookieName]);
} }
} }
} }

View File

@ -4,12 +4,9 @@ use Grocy\Middleware\AuthMiddleware;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Slim\Routing\RouteCollectorProxy; use Slim\Routing\RouteCollectorProxy;
use Grocy\Middleware\JsonMiddleware; use Grocy\Middleware\JsonMiddleware;
$app->group('', function (RouteCollectorProxy $group) {
$app->group('', function(RouteCollectorProxy $group)
{
// System routes // System routes
$group->get('/', '\Grocy\Controllers\SystemController:Root')->setName('root'); $group->get('/', '\Grocy\Controllers\SystemController:Root')->setName('root');
$group->get('/about', '\Grocy\Controllers\SystemController:About'); $group->get('/about', '\Grocy\Controllers\SystemController:About');
@ -34,9 +31,9 @@ $app->group('', function(RouteCollectorProxy $group)
$group->get('/user/{userId}/permissions', '\Grocy\Controllers\UsersController:PermissionList'); $group->get('/user/{userId}/permissions', '\Grocy\Controllers\UsersController:PermissionList');
$group->get('/usersettings', '\Grocy\Controllers\UsersController:UserSettings'); $group->get('/usersettings', '\Grocy\Controllers\UsersController:UserSettings');
$group->get('/files/{group}/{fileName}', '\Grocy\Controllers\FilesApiController:ShowFile'); $group->get('/files/{group}/{fileName}', '\Grocy\Controllers\FilesApiController:ShowFile');
// Stock routes // Stock routes
if (GROCY_FEATURE_FLAG_STOCK) if (GROCY_FEATURE_FLAG_STOCK)
{ {
$group->get('/stockoverview', '\Grocy\Controllers\StockController:Overview'); $group->get('/stockoverview', '\Grocy\Controllers\StockController:Overview');
@ -139,8 +136,7 @@ $app->group('', function(RouteCollectorProxy $group)
$group->get('/manageapikeys/new', '\Grocy\Controllers\OpenApiController:CreateNewApiKey'); $group->get('/manageapikeys/new', '\Grocy\Controllers\OpenApiController:CreateNewApiKey');
}); });
$app->group('/api', function(RouteCollectorProxy $group) $app->group('/api', function (RouteCollectorProxy $group) {
{
// OpenAPI // OpenAPI
$group->get('/openapi/specification', '\Grocy\Controllers\OpenApiController:DocumentationSpec'); $group->get('/openapi/specification', '\Grocy\Controllers\OpenApiController:DocumentationSpec');
@ -263,7 +259,6 @@ $app->group('/api', function(RouteCollectorProxy $group)
})->add(JsonMiddleware::class); })->add(JsonMiddleware::class);
// Handle CORS preflight OPTIONS requests // Handle CORS preflight OPTIONS requests
$app->options('/api/{routes:.+}', function(Request $request, Response $response): Response $app->options('/api/{routes:.+}', function (Request $request, Response $response): Response {
{
return $response->withStatus(204); return $response->withStatus(204);
}); });

View File

@ -32,7 +32,7 @@ class ApiKeyService extends BaseService
return $apiKey->id; return $apiKey->id;
} }
// Returns any valid key for $keyType, // Returns any valid key for $keyType,
// not allowed for key type "default" // not allowed for key type "default"
public function GetOrCreateApiKey($keyType) public function GetOrCreateApiKey($keyType)
{ {
@ -52,9 +52,7 @@ class ApiKeyService extends BaseService
{ {
return $this->CreateApiKey($keyType); return $this->CreateApiKey($keyType);
} }
} }
} }
public function GetUserByApiKey($apiKey) public function GetUserByApiKey($apiKey)
@ -84,7 +82,7 @@ class ApiKeyService extends BaseService
if ($apiKeyRow !== null) if ($apiKeyRow !== null)
{ {
// This should not change the database file modification time as this is used // This should not change the database file modification time as this is used
// to determine if REALLY something has changed // to determine if REALLY something has changed
$dbModTime = $this->getDatabaseService()->GetDbChangedTime(); $dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$apiKeyRow->update([ $apiKeyRow->update([
@ -98,9 +96,7 @@ class ApiKeyService extends BaseService
{ {
return false; return false;
} }
} }
} }
public function RemoveApiKey($apiKey) public function RemoveApiKey($apiKey)
@ -112,5 +108,4 @@ class ApiKeyService extends BaseService
{ {
return RandomString(50); return RandomString(50);
} }
} }

View File

@ -29,8 +29,7 @@ class ApplicationService extends BaseService
} }
// Sort changelog items to have the changelog descending by newest version // Sort changelog items to have the changelog descending by newest version
usort($changelogItems, function ($a, $b) usort($changelogItems, function ($a, $b) {
{
if ($a['release_number'] == $b['release_number']) if ($a['release_number'] == $b['release_number'])
{ {
return 0; return 0;
@ -59,7 +58,6 @@ class ApplicationService extends BaseService
$this->InstalledVersion->Version = "pre-release-$commitHash"; $this->InstalledVersion->Version = "pre-release-$commitHash";
$this->InstalledVersion->ReleaseDate = substr($commitDate, 0, 19); $this->InstalledVersion->ReleaseDate = substr($commitDate, 0, 19);
} }
} }
return $this->InstalledVersion; return $this->InstalledVersion;
@ -77,5 +75,4 @@ class ApplicationService extends BaseService
'sqlite_version' => $sqliteVersion 'sqlite_version' => $sqliteVersion
]; ];
} }
} }

View File

@ -61,5 +61,4 @@ class BaseService
{ {
return UsersService::getInstance(); return UsersService::getInstance();
} }
} }

View File

@ -66,5 +66,4 @@ class BatteriesService extends BaseService
$batteryRow = $this->getDatabase()->batteries()->where('id = :1', $batteryId)->fetch(); $batteryRow = $this->getDatabase()->batteries()->where('id = :1', $batteryId)->fetch();
return $batteryRow !== null; return $batteryRow !== null;
} }
} }

View File

@ -2,14 +2,6 @@
namespace Grocy\Services; namespace Grocy\Services;
#use \Grocy\Services\StockService;
#use \Grocy\Services\TasksService;
#use \Grocy\Services\ChoresService;
#use \Grocy\Services\BatteriesService;
#use \Grocy\Services\UsersService;
use Grocy\Helpers\UrlManager; use Grocy\Helpers\UrlManager;
class CalendarService extends BaseService class CalendarService extends BaseService
@ -34,9 +26,7 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/stockoverview') 'link' => $this->UrlManager->ConstructUrl('/stockoverview')
]; ];
} }
} }
} }
$taskEvents = []; $taskEvents = [];
@ -54,7 +44,6 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/tasks') 'link' => $this->UrlManager->ConstructUrl('/tasks')
]; ];
} }
} }
$choreEvents = []; $choreEvents = [];
@ -85,7 +74,6 @@ class CalendarService extends BaseService
'allDay' => $chore->track_date_only == 1 'allDay' => $chore->track_date_only == 1
]; ];
} }
} }
$batteryEvents = []; $batteryEvents = [];
@ -104,7 +92,6 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/batteriesoverview') 'link' => $this->UrlManager->ConstructUrl('/batteriesoverview')
]; ];
} }
} }
$mealPlanRecipeEvents = []; $mealPlanRecipeEvents = [];
@ -129,7 +116,6 @@ class CalendarService extends BaseService
'link' => $this->UrlManager->ConstructUrl('/recipes' . '?recipe=' . $recipeOfCurrentDay->includes_recipe_id . '#fullscreen') 'link' => $this->UrlManager->ConstructUrl('/recipes' . '?recipe=' . $recipeOfCurrentDay->includes_recipe_id . '#fullscreen')
]; ];
} }
} }
$mealPlanDayNotes = $this->getDatabase()->meal_plan()->where('type', 'note'); $mealPlanDayNotes = $this->getDatabase()->meal_plan()->where('type', 'note');
@ -158,7 +144,6 @@ class CalendarService extends BaseService
'date_format' => 'date' 'date_format' => 'date'
]; ];
} }
} }
return array_merge($stockEvents, $taskEvents, $choreEvents, $batteryEvents, $mealPlanRecipeEvents, $mealPlanNotesEvents, $mealPlanProductEvents); return array_merge($stockEvents, $taskEvents, $choreEvents, $batteryEvents, $mealPlanRecipeEvents, $mealPlanNotesEvents, $mealPlanProductEvents);
@ -169,5 +154,4 @@ class CalendarService extends BaseService
parent::__construct(); parent::__construct();
$this->UrlManager = new UrlManager(GROCY_BASE_URL); $this->UrlManager = new UrlManager(GROCY_BASE_URL);
} }
} }

View File

@ -5,23 +5,15 @@ namespace Grocy\Services;
class ChoresService extends BaseService class ChoresService extends BaseService
{ {
const CHORE_ASSIGNMENT_TYPE_IN_ALPHABETICAL_ORDER = 'in-alphabetical-order'; const CHORE_ASSIGNMENT_TYPE_IN_ALPHABETICAL_ORDER = 'in-alphabetical-order';
const CHORE_ASSIGNMENT_TYPE_NO_ASSIGNMENT = 'no-assignment'; const CHORE_ASSIGNMENT_TYPE_NO_ASSIGNMENT = 'no-assignment';
const CHORE_ASSIGNMENT_TYPE_RANDOM = 'random'; const CHORE_ASSIGNMENT_TYPE_RANDOM = 'random';
const CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST = 'who-least-did-first'; const CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST = 'who-least-did-first';
const CHORE_PERIOD_TYPE_DAILY = 'daily'; const CHORE_PERIOD_TYPE_DAILY = 'daily';
const CHORE_PERIOD_TYPE_DYNAMIC_REGULAR = 'dynamic-regular'; const CHORE_PERIOD_TYPE_DYNAMIC_REGULAR = 'dynamic-regular';
const CHORE_PERIOD_TYPE_MANUALLY = 'manually'; const CHORE_PERIOD_TYPE_MANUALLY = 'manually';
const CHORE_PERIOD_TYPE_MONTHLY = 'monthly'; const CHORE_PERIOD_TYPE_MONTHLY = 'monthly';
const CHORE_PERIOD_TYPE_WEEKLY = 'weekly'; const CHORE_PERIOD_TYPE_WEEKLY = 'weekly';
const CHORE_PERIOD_TYPE_YEARLY = 'yearly'; const CHORE_PERIOD_TYPE_YEARLY = 'yearly';
public function CalculateNextExecutionAssignment($choreId) public function CalculateNextExecutionAssignment($choreId)
@ -45,33 +37,29 @@ class ChoresService extends BaseService
{ {
$assignedUsers[] = $user; $assignedUsers[] = $user;
} }
} }
$nextExecutionUserId = null; $nextExecutionUserId = null;
if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_RANDOM) if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_RANDOM)
{ {
// Random assignment and only 1 user in the group? Well, ok - will be hard to guess the next one... // Random assignment and only 1 user in the group? Well, ok - will be hard to guess the next one...
if (count($assignedUsers) == 1) if (count($assignedUsers) == 1)
{ {
$nextExecutionUserId = array_shift($assignedUsers)->id; $nextExecutionUserId = array_shift($assignedUsers)->id;
} }
else else
{ {
// Randomness in small groups will likely often result in the same user, so try it as long as this is the case // Randomness in small groups will likely often result in the same user, so try it as long as this is the case
while ($nextExecutionUserId == null || $nextExecutionUserId == $lastDoneByUserId) while ($nextExecutionUserId == null || $nextExecutionUserId == $lastDoneByUserId)
{ {
$nextExecutionUserId = $assignedUsers[array_rand($assignedUsers)]->id; $nextExecutionUserId = $assignedUsers[array_rand($assignedUsers)]->id;
} }
} }
} }
else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_IN_ALPHABETICAL_ORDER) elseif ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_IN_ALPHABETICAL_ORDER)
{ {
usort($assignedUsers, function ($a, $b) usort($assignedUsers, function ($a, $b) {
{
return strcmp($a->display_name, $b->display_name); return strcmp($a->display_name, $b->display_name);
}); });
@ -88,24 +76,21 @@ class ChoresService extends BaseService
{ {
$nextRoundMatches = true; $nextRoundMatches = true;
} }
} }
// If nothing has matched, probably it was the last user in the sorted list -> the first one is the next one // If nothing has matched, probably it was the last user in the sorted list -> the first one is the next one
if ($nextExecutionUserId == null) if ($nextExecutionUserId == null)
{ {
$nextExecutionUserId = array_shift($assignedUsers)->id; $nextExecutionUserId = array_shift($assignedUsers)->id;
} }
} }
else if ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST) elseif ($chore->assignment_type == self::CHORE_ASSIGNMENT_TYPE_WHO_LEAST_DID_FIRST)
{ {
$row = $this->getDatabase()->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch(); $row = $this->getDatabase()->chores_execution_users_statistics()->where('chore_id = :1', $choreId)->orderBy('execution_count')->limit(1)->fetch();
if ($row != null) if ($row != null)
{ {
$nextExecutionUserId = $row->user_id; $nextExecutionUserId = $row->user_id;
} }
} }
$chore->update([ $chore->update([
@ -217,5 +202,4 @@ class ChoresService extends BaseService
$choreRow = $this->getDatabase()->chores()->where('id = :1', $choreId)->fetch(); $choreRow = $this->getDatabase()->chores()->where('id = :1', $choreId)->fetch();
return $choreRow !== null; return $choreRow !== null;
} }
} }

View File

@ -24,16 +24,12 @@ class DatabaseMigrationService extends BaseService
$migrationNumber = ltrim($migrationFile->getBasename('.php'), '0'); $migrationNumber = ltrim($migrationFile->getBasename('.php'), '0');
$this->ExecutePhpMigrationWhenNeeded($migrationNumber, $migrationFile->getPathname()); $this->ExecutePhpMigrationWhenNeeded($migrationNumber, $migrationFile->getPathname());
} }
else elseif ($migrationFile->getExtension() === 'sql')
if ($migrationFile->getExtension() === 'sql')
{ {
$migrationNumber = ltrim($migrationFile->getBasename('.sql'), '0'); $migrationNumber = ltrim($migrationFile->getBasename('.sql'), '0');
$this->ExecuteSqlMigrationWhenNeeded($migrationNumber, file_get_contents($migrationFile->getPathname())); $this->ExecuteSqlMigrationWhenNeeded($migrationNumber, file_get_contents($migrationFile->getPathname()));
} }
} }
} }
private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile) private function ExecutePhpMigrationWhenNeeded(int $migrationId, string $phpFile)
@ -45,7 +41,6 @@ class DatabaseMigrationService extends BaseService
include $phpFile; include $phpFile;
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); $this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
} }
} }
private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql) private function ExecuteSqlMigrationWhenNeeded(int $migrationId, string $sql)
@ -57,7 +52,5 @@ class DatabaseMigrationService extends BaseService
$this->getDatabaseService()->ExecuteDbStatement($sql); $this->getDatabaseService()->ExecuteDbStatement($sql);
$this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')'); $this->getDatabaseService()->ExecuteDbStatement('INSERT INTO migrations (migration) VALUES (' . $migrationId . ')');
} }
} }
} }

View File

@ -2,8 +2,6 @@
namespace Grocy\Services; namespace Grocy\Services;
#use \Grocy\Services\ApplicationService;
class DatabaseService class DatabaseService
{ {
private static $DbConnection = null; private static $DbConnection = null;
@ -99,5 +97,4 @@ class DatabaseService
return GROCY_DATAPATH . '/grocy.db'; return GROCY_DATAPATH . '/grocy.db';
} }
} }

View File

@ -2,8 +2,6 @@
namespace Grocy\Services; namespace Grocy\Services;
#use \Grocy\Services\LocalizationService;
class DemoDataGeneratorService extends BaseService class DemoDataGeneratorService extends BaseService
{ {
protected $LocalizationService; protected $LocalizationService;
@ -311,7 +309,6 @@ class DemoDataGeneratorService extends BaseService
$this->DownloadFileIfNotAlreadyExists('https://releases.grocy.info/demoresources/chocolate_sauce.jpg', "$recipePicturesFolder/chocolate_sauce.jpg"); $this->DownloadFileIfNotAlreadyExists('https://releases.grocy.info/demoresources/chocolate_sauce.jpg', "$recipePicturesFolder/chocolate_sauce.jpg");
$this->DownloadFileIfNotAlreadyExists('https://releases.grocy.info/demoresources/pancakes_chocolate_sauce.jpg', "$recipePicturesFolder/pancakes_chocolate_sauce.jpg"); $this->DownloadFileIfNotAlreadyExists('https://releases.grocy.info/demoresources/pancakes_chocolate_sauce.jpg', "$recipePicturesFolder/pancakes_chocolate_sauce.jpg");
} }
} }
public function __construct() public function __construct()
@ -331,7 +328,6 @@ class DemoDataGeneratorService extends BaseService
] ]
]))); ])));
} }
} }
private function NextSupermarketId() private function NextSupermarketId()
@ -366,5 +362,4 @@ class DemoDataGeneratorService extends BaseService
$localizedText = $this->getLocalizationService()->__t($text, null); $localizedText = $this->getLocalizationService()->__t($text, null);
return str_replace("'", "''", $localizedText); return str_replace("'", "''", $localizedText);
} }
} }

View File

@ -34,22 +34,17 @@ class FilesService extends BaseService
{ {
$image->resizeToBestFit($bestFitWidth, $bestFitHeight); $image->resizeToBestFit($bestFitWidth, $bestFitHeight);
} }
else elseif ($bestFitHeight !== null)
if ($bestFitHeight !== null)
{ {
$image->resizeToHeight($bestFitHeight); $image->resizeToHeight($bestFitHeight);
} }
else elseif ($bestFitWidth !== null)
if ($bestFitWidth !== null)
{ {
$image->resizeToWidth($bestFitWidth); $image->resizeToWidth($bestFitWidth);
} }
$image->save($filePathDownscaled); $image->save($filePathDownscaled);
} }
} }
catch (ImageResizeException $ex) catch (ImageResizeException $ex)
{ {
@ -81,7 +76,5 @@ class FilesService extends BaseService
{ {
mkdir($this->StoragePath); mkdir($this->StoragePath);
} }
} }
} }

View File

@ -2,7 +2,6 @@
namespace Grocy\Services; namespace Grocy\Services;
#use \Grocy\Services\DatabaseService;
use Gettext\Translation; use Gettext\Translation;
use Gettext\Translations; use Gettext\Translations;
use Gettext\Translator; use Gettext\Translator;
@ -31,9 +30,7 @@ class LocalizationService
$this->PotMain[] = $translation; $this->PotMain[] = $translation;
$this->PotMain->toPoFile(__DIR__ . '/../localization/strings.pot'); $this->PotMain->toPoFile(__DIR__ . '/../localization/strings.pot');
} }
} }
} }
public function GetPluralCount() public function GetPluralCount()
@ -46,7 +43,6 @@ class LocalizationService
{ {
return 2; return 2;
} }
} }
public function GetPluralDefinition() public function GetPluralDefinition()
@ -59,7 +55,6 @@ class LocalizationService
{ {
return '(n != 1)'; return '(n != 1)';
} }
} }
public function GetPoAsJsonString() public function GetPoAsJsonString()
@ -93,7 +88,6 @@ class LocalizationService
{ {
return vsprintf($this->Translator->gettext($text), ...$placeholderValues); return vsprintf($this->Translator->gettext($text), ...$placeholderValues);
} }
} }
public static function getInstance(string $culture) public static function getInstance(string $culture)
@ -137,7 +131,6 @@ class LocalizationService
{ {
$this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/demo_data.pot')); $this->Pot = $this->Pot->mergeWith(Translations::fromPoFile(__DIR__ . '/../localization/demo_data.pot'));
} }
} }
$this->PoUserStrings = new Translations(); $this->PoUserStrings = new Translations();
@ -213,5 +206,4 @@ class LocalizationService
$this->Translator = new Translator(); $this->Translator = new Translator();
$this->Translator->loadTranslations($this->Po); $this->Translator->loadTranslations($this->Po);
} }
} }

View File

@ -2,8 +2,6 @@
namespace Grocy\Services; namespace Grocy\Services;
#use \Grocy\Services\StockService;
use LessQL\Result; use LessQL\Result;
class RecipesService extends BaseService class RecipesService extends BaseService
@ -42,11 +40,8 @@ class RecipesService extends BaseService
]); ]);
$shoppinglistRow->save(); $shoppinglistRow->save();
} }
} }
} }
} }
public function ConsumeRecipe($recipeId) public function ConsumeRecipe($recipeId)
@ -65,7 +60,6 @@ class RecipesService extends BaseService
{ {
$this->getStockService()->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true); $this->getStockService()->ConsumeProduct($recipePosition->product_id, $recipePosition->recipe_amount, false, StockService::TRANSACTION_TYPE_CONSUME, 'default', $recipeId, null, $transactionId, true);
} }
} }
$recipeRow = $this->getDatabase()->recipes()->where('id = :1', $recipeId)->fetch(); $recipeRow = $this->getDatabase()->recipes()->where('id = :1', $recipeId)->fetch();
@ -75,7 +69,6 @@ class RecipesService extends BaseService
$recipeResolvedRow = $this->getDatabase()->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch(); $recipeResolvedRow = $this->getDatabase()->recipes_resolved()->where('recipe_id = :1', $recipeId)->fetch();
$this->getStockService()->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs)); $this->getStockService()->AddProduct($recipeRow->product_id, floatval($recipeRow->desired_servings), null, StockService::TRANSACTION_TYPE_SELF_PRODUCTION, date('Y-m-d'), floatval($recipeResolvedRow->costs));
} }
} }
public function GetRecipesPosResolved() public function GetRecipesPosResolved()
@ -99,5 +92,4 @@ class RecipesService extends BaseService
$recipeRow = $this->getDataBase()->recipes()->where('id = :1', $recipeId)->fetch(); $recipeRow = $this->getDataBase()->recipes()->where('id = :1', $recipeId)->fetch();
return $recipeRow !== null; return $recipeRow !== null;
} }
} }

View File

@ -13,7 +13,7 @@ class SessionService extends BaseService
$expires = date('Y-m-d H:i:s', intval(time() + 2592000)); $expires = date('Y-m-d H:i:s', intval(time() + 2592000));
// Default is that sessions expire in 30 days // Default is that sessions expire in 30 days
if ($stayLoggedInPermanently === true) if ($stayLoggedInPermanently === true)
{ {
$expires = date('Y-m-d H:i:s', PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX >> 32); // Never $expires = date('Y-m-d H:i:s', PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX >> 32); // Never
@ -61,7 +61,7 @@ class SessionService extends BaseService
if ($sessionRow !== null) if ($sessionRow !== null)
{ {
// This should not change the database file modification time as this is used // This should not change the database file modification time as this is used
// to determine if REALLY something has changed // to determine if REALLY something has changed
$dbModTime = $this->getDatabaseService()->GetDbChangedTime(); $dbModTime = $this->getDatabaseService()->GetDbChangedTime();
$sessionRow->update([ $sessionRow->update([
@ -75,9 +75,7 @@ class SessionService extends BaseService
{ {
return false; return false;
} }
} }
} }
public function RemoveSession($sessionKey) public function RemoveSession($sessionKey)
@ -89,5 +87,4 @@ class SessionService extends BaseService
{ {
return RandomString(50); return RandomString(50);
} }
} }

View File

@ -5,21 +5,13 @@ namespace Grocy\Services;
class StockService extends BaseService class StockService extends BaseService
{ {
const TRANSACTION_TYPE_CONSUME = 'consume'; const TRANSACTION_TYPE_CONSUME = 'consume';
const TRANSACTION_TYPE_INVENTORY_CORRECTION = 'inventory-correction'; const TRANSACTION_TYPE_INVENTORY_CORRECTION = 'inventory-correction';
const TRANSACTION_TYPE_PRODUCT_OPENED = 'product-opened'; const TRANSACTION_TYPE_PRODUCT_OPENED = 'product-opened';
const TRANSACTION_TYPE_PURCHASE = 'purchase'; const TRANSACTION_TYPE_PURCHASE = 'purchase';
const TRANSACTION_TYPE_SELF_PRODUCTION = 'self-production'; const TRANSACTION_TYPE_SELF_PRODUCTION = 'self-production';
const TRANSACTION_TYPE_STOCK_EDIT_NEW = 'stock-edit-new'; const TRANSACTION_TYPE_STOCK_EDIT_NEW = 'stock-edit-new';
const TRANSACTION_TYPE_STOCK_EDIT_OLD = 'stock-edit-old'; const TRANSACTION_TYPE_STOCK_EDIT_OLD = 'stock-edit-old';
const TRANSACTION_TYPE_TRANSFER_FROM = 'transfer_from'; const TRANSACTION_TYPE_TRANSFER_FROM = 'transfer_from';
const TRANSACTION_TYPE_TRANSFER_TO = 'transfer_to'; const TRANSACTION_TYPE_TRANSFER_TO = 'transfer_to';
public function AddMissingProductsToShoppingList($listId = 1) public function AddMissingProductsToShoppingList($listId = 1)
@ -38,8 +30,8 @@ class StockService extends BaseService
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch(); $alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id', $missingProduct->id)->fetch();
if ($alreadyExistingEntry) // Update if ($alreadyExistingEntry)
{ { // Update
if ($alreadyExistingEntry->amount < $amountToAdd) if ($alreadyExistingEntry->amount < $amountToAdd)
{ {
$alreadyExistingEntry->update([ $alreadyExistingEntry->update([
@ -47,10 +39,9 @@ class StockService extends BaseService
'shopping_list_id' => $listId 'shopping_list_id' => $listId
]); ]);
} }
} }
else // Insert else
{ { // Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([ $shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
'product_id' => $missingProduct->id, 'product_id' => $missingProduct->id,
'amount' => $amountToAdd, 'amount' => $amountToAdd,
@ -58,9 +49,7 @@ class StockService extends BaseService
]); ]);
$shoppinglistRow->save(); $shoppinglistRow->save();
} }
} }
} }
public function AddProduct(int $productId, float $amount, $bestBeforeDate, $transactionType, $purchasedDate, $price, $quFactorPurchaseToStock, $locationId = null, $shoppingLocationId = null, &$transactionId = null) public function AddProduct(int $productId, float $amount, $bestBeforeDate, $transactionType, $purchasedDate, $price, $quFactorPurchaseToStock, $locationId = null, $shoppingLocationId = null, &$transactionId = null)
@ -70,9 +59,9 @@ class StockService extends BaseService
throw new \Exception('Product does not exist or is inactive'); throw new \Exception('Product does not exist or is inactive');
} }
// Tare weight handling // Tare weight handling
// The given amount is the new total amount including the container weight (gross) // The given amount is the new total amount including the container weight (gross)
// The amount to be posted needs to be the given amount - stock amount - tare weight // The amount to be posted needs to be the given amount - stock amount - tare weight
$productDetails = (object) $this->GetProductDetails($productId); $productDetails = (object) $this->GetProductDetails($productId);
@ -86,14 +75,14 @@ class StockService extends BaseService
$amount = $amount - floatval($productDetails->stock_amount) - floatval($productDetails->product->tare_weight); $amount = $amount - floatval($productDetails->stock_amount) - floatval($productDetails->product->tare_weight);
} }
//Sets the default best before date, if none is supplied //Sets the default best before date, if none is supplied
if ($bestBeforeDate == null) if ($bestBeforeDate == null)
{ {
if (intval($productDetails->product->default_best_before_days) == -1) if (intval($productDetails->product->default_best_before_days) == -1)
{ {
$bestBeforeDate = date('2999-12-31'); $bestBeforeDate = date('2999-12-31');
} }
else if (intval($productDetails->product->default_best_before_days) > 0) elseif (intval($productDetails->product->default_best_before_days) > 0)
{ {
$bestBeforeDate = date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $productDetails->product->default_best_before_days . ' days')); $bestBeforeDate = date('Y-m-d', strtotime(date('Y-m-d') . ' + ' . $productDetails->product->default_best_before_days . ' days'));
} }
@ -101,7 +90,6 @@ class StockService extends BaseService
{ {
$bestBeforeDate = date('Y-m-d'); $bestBeforeDate = date('Y-m-d');
} }
} }
if ($transactionType === self::TRANSACTION_TYPE_PURCHASE || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION || $transactionType == self::TRANSACTION_TYPE_SELF_PRODUCTION) if ($transactionType === self::TRANSACTION_TYPE_PURCHASE || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION || $transactionType == self::TRANSACTION_TYPE_SELF_PRODUCTION)
@ -149,7 +137,6 @@ class StockService extends BaseService
{ {
throw new \Exception("Transaction type $transactionType is not valid (StockService.AddProduct)"); throw new \Exception("Transaction type $transactionType is not valid (StockService.AddProduct)");
} }
} }
public function AddProductToShoppingList($productId, $amount = 1, $note = null, $listId = 1) public function AddProductToShoppingList($productId, $amount = 1, $note = null, $listId = 1)
@ -165,16 +152,16 @@ class StockService extends BaseService
} }
$alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch(); $alreadyExistingEntry = $this->getDatabase()->shopping_list()->where('product_id = :1 AND shopping_list_id = :2', $productId, $listId)->fetch();
if ($alreadyExistingEntry) // Update if ($alreadyExistingEntry)
{ { // Update
$alreadyExistingEntry->update([ $alreadyExistingEntry->update([
'amount' => ($alreadyExistingEntry->amount + $amount), 'amount' => ($alreadyExistingEntry->amount + $amount),
'shopping_list_id' => $listId, 'shopping_list_id' => $listId,
'note' => $note 'note' => $note
]); ]);
} }
else // Insert else
{ { // Insert
$shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([ $shoppinglistRow = $this->getDatabase()->shopping_list()->createRow([
'product_id' => $productId, 'product_id' => $productId,
'amount' => $amount, 'amount' => $amount,
@ -183,7 +170,6 @@ class StockService extends BaseService
]); ]);
$shoppinglistRow->save(); $shoppinglistRow->save();
} }
} }
public function ClearShoppingList($listId = 1) public function ClearShoppingList($listId = 1)
@ -208,9 +194,9 @@ class StockService extends BaseService
throw new \Exception('Location does not exist'); throw new \Exception('Location does not exist');
} }
// Tare weight handling // Tare weight handling
// The given amount is the new total amount including the container weight (gross) // The given amount is the new total amount including the container weight (gross)
// The amount to be posted needs to be the absolute value of the given amount - stock amount - tare weight // The amount to be posted needs to be the absolute value of the given amount - stock amount - tare weight
$productDetails = (object) $this->GetProductDetails($productId); $productDetails = (object) $this->GetProductDetails($productId);
@ -226,12 +212,12 @@ class StockService extends BaseService
if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION) if ($transactionType === self::TRANSACTION_TYPE_CONSUME || $transactionType === self::TRANSACTION_TYPE_INVENTORY_CORRECTION)
{ {
if ($locationId === null) // Consume from any location if ($locationId === null)
{ { // Consume from any location
$potentialStockEntries = $this->GetProductStockEntries($productId, false, $allowSubproductSubstitution); $potentialStockEntries = $this->GetProductStockEntries($productId, false, $allowSubproductSubstitution);
} }
else // Consume only from the supplied location else
{ { // Consume only from the supplied location
$potentialStockEntries = $this->GetProductStockEntriesForLocation($productId, $locationId, false, $allowSubproductSubstitution); $potentialStockEntries = $this->GetProductStockEntriesForLocation($productId, $locationId, false, $allowSubproductSubstitution);
} }
@ -259,8 +245,8 @@ class StockService extends BaseService
break; break;
} }
if ($amount >= $stockEntry->amount) // Take the whole stock entry if ($amount >= $stockEntry->amount)
{ { // Take the whole stock entry
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->getDatabase()->stock_log()->createRow([
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1, 'amount' => $stockEntry->amount * -1,
@ -281,8 +267,8 @@ class StockService extends BaseService
$amount -= $stockEntry->amount; $amount -= $stockEntry->amount;
} }
else // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount else
{ { // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->getDatabase()->stock_log()->createRow([
@ -307,7 +293,6 @@ class StockService extends BaseService
$amount = 0; $amount = 0;
} }
} }
return $this->getDatabase()->lastInsertId(); return $this->getDatabase()->lastInsertId();
@ -316,7 +301,6 @@ class StockService extends BaseService
{ {
throw new Exception("Transaction type $transactionType is not valid (StockService.ConsumeProduct)"); throw new Exception("Transaction type $transactionType is not valid (StockService.ConsumeProduct)");
} }
} }
public function EditStockEntry(int $stockRowId, float $amount, $bestBeforeDate, $locationId, $shoppingLocationId, $price, $open, $purchasedDate, $quFactorPurchaseToStock) public function EditStockEntry(int $stockRowId, float $amount, $bestBeforeDate, $locationId, $shoppingLocationId, $price, $open, $purchasedDate, $quFactorPurchaseToStock)
@ -354,9 +338,7 @@ class StockService extends BaseService
{ {
$openedDate = date('Y-m-d'); $openedDate = date('Y-m-d');
} }
else elseif (!$open)
if (!$open)
{ {
$openedDate = null; $openedDate = null;
} }
@ -399,8 +381,8 @@ class StockService extends BaseService
$plugin = $this->LoadBarcodeLookupPlugin(); $plugin = $this->LoadBarcodeLookupPlugin();
$pluginOutput = $plugin->Lookup($barcode); $pluginOutput = $plugin->Lookup($barcode);
if ($pluginOutput !== null) // Lookup was successful if ($pluginOutput !== null)
{ { // Lookup was successful
if ($addFoundProduct === true) if ($addFoundProduct === true)
{ {
// Add product to database and include new product id in output // Add product to database and include new product id in output
@ -409,7 +391,6 @@ class StockService extends BaseService
$pluginOutput['id'] = $newRow->id; $pluginOutput['id'] = $newRow->id;
} }
} }
return $pluginOutput; return $pluginOutput;
@ -466,7 +447,6 @@ class StockService extends BaseService
{ {
return $this->getDatabase()->uihelper_stock_current_overview_including_opened(); return $this->getDatabase()->uihelper_stock_current_overview_including_opened();
} }
} }
public function GetExpiringProducts(int $days = 5, bool $excludeExpired = false) public function GetExpiringProducts(int $days = 5, bool $excludeExpired = false)
@ -605,7 +585,7 @@ class StockService extends BaseService
public function GetProductStockEntries($productId, $excludeOpened = false, $allowSubproductSubstitution = false, $ordered = true) public function GetProductStockEntries($productId, $excludeOpened = false, $allowSubproductSubstitution = false, $ordered = true)
{ {
// In order of next use: // In order of next use:
// First expiring first, then first in first out // First expiring first, then first in first out
$sqlWhereProductId = 'product_id = :1'; $sqlWhereProductId = 'product_id = :1';
@ -623,7 +603,9 @@ class StockService extends BaseService
} }
$result = $this->getDatabase()->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId); $result = $this->getDatabase()->stock()->where($sqlWhereProductId . ' ' . $sqlWhereAndOpen, $productId);
if ($ordered) if ($ordered)
{
return $result->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC'); return $result->orderBy('best_before_date', 'ASC')->orderBy('purchased_date', 'ASC');
}
return $result; return $result;
} }
@ -662,9 +644,9 @@ class StockService extends BaseService
$shoppingLocationId = $productDetails->last_shopping_location_id; $shoppingLocationId = $productDetails->last_shopping_location_id;
} }
// Tare weight handling // Tare weight handling
// The given amount is the new total amount including the container weight (gross) // The given amount is the new total amount including the container weight (gross)
// So assume that the amount in stock is the amount also including the container weight // So assume that the amount in stock is the amount also including the container weight
$containerWeight = 0; $containerWeight = 0;
@ -677,9 +659,7 @@ class StockService extends BaseService
{ {
throw new \Exception('The new amount cannot equal the current stock amount'); throw new \Exception('The new amount cannot equal the current stock amount');
} }
else elseif ($newAmount > floatval($productDetails->stock_amount) + $containerWeight)
if ($newAmount > floatval($productDetails->stock_amount) + $containerWeight)
{ {
$bookingAmount = $newAmount - floatval($productDetails->stock_amount); $bookingAmount = $newAmount - floatval($productDetails->stock_amount);
@ -690,9 +670,7 @@ class StockService extends BaseService
return $this->AddProduct($productId, $bookingAmount, $bestBeforeDate, self::TRANSACTION_TYPE_INVENTORY_CORRECTION, date('Y-m-d'), $price, $locationId, $shoppingLocationId); return $this->AddProduct($productId, $bookingAmount, $bestBeforeDate, self::TRANSACTION_TYPE_INVENTORY_CORRECTION, date('Y-m-d'), $price, $locationId, $shoppingLocationId);
} }
else elseif ($newAmount < $productDetails->stock_amount + $containerWeight)
if ($newAmount < $productDetails->stock_amount + $containerWeight)
{ {
$bookingAmount = $productDetails->stock_amount - $newAmount; $bookingAmount = $productDetails->stock_amount - $newAmount;
@ -747,8 +725,8 @@ class StockService extends BaseService
$newBestBeforeDate = date('Y-m-d', strtotime('+' . $product->default_best_before_days_after_open . ' days')); $newBestBeforeDate = date('Y-m-d', strtotime('+' . $product->default_best_before_days_after_open . ' days'));
} }
if ($amount >= $stockEntry->amount) // Mark the whole stock entry as opened if ($amount >= $stockEntry->amount)
{ { // Mark the whole stock entry as opened
$logRow = $this->getDatabase()->stock_log()->createRow([ $logRow = $this->getDatabase()->stock_log()->createRow([
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount, 'amount' => $stockEntry->amount,
@ -772,8 +750,8 @@ class StockService extends BaseService
$amount -= $stockEntry->amount; $amount -= $stockEntry->amount;
} }
else // Stock entry amount is > than needed amount -> split the stock entry else
{ { // Stock entry amount is > than needed amount -> split the stock entry
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$newStockRow = $this->getDatabase()->stock()->createRow([ $newStockRow = $this->getDatabase()->stock()->createRow([
@ -812,7 +790,6 @@ class StockService extends BaseService
$amount = 0; $amount = 0;
} }
} }
return $this->getDatabase()->lastInsertId(); return $this->getDatabase()->lastInsertId();
@ -827,7 +804,7 @@ class StockService extends BaseService
$productRow = $this->getDatabase()->shopping_list()->where('product_id = :1', $productId)->fetch(); $productRow = $this->getDatabase()->shopping_list()->where('product_id = :1', $productId)->fetch();
//If no entry was found with for this product, we return gracefully //If no entry was found with for this product, we return gracefully
if ($productRow != null && !empty($productRow)) if ($productRow != null && !empty($productRow))
{ {
$newAmount = $productRow->amount - $amount; $newAmount = $productRow->amount - $amount;
@ -839,9 +816,7 @@ class StockService extends BaseService
{ {
$productRow->update(['amount' => $newAmount]); $productRow->update(['amount' => $newAmount]);
} }
} }
} }
public function TransferProduct(int $productId, float $amount, int $locationIdFrom, int $locationIdTo, $specificStockEntryId = 'default', &$transactionId = null) public function TransferProduct(int $productId, float $amount, int $locationIdFrom, int $locationIdTo, $specificStockEntryId = 'default', &$transactionId = null)
@ -861,9 +836,9 @@ class StockService extends BaseService
throw new \Exception('Destination location does not exist'); throw new \Exception('Destination location does not exist');
} }
// Tare weight handling // Tare weight handling
// The given amount is the new total amount including the container weight (gross) // The given amount is the new total amount including the container weight (gross)
// The amount to be posted needs to be the absolute value of the given amount - stock amount - tare weight // The amount to be posted needs to be the absolute value of the given amount - stock amount - tare weight
$productDetails = (object) $this->GetProductDetails($productId); $productDetails = (object) $this->GetProductDetails($productId);
@ -871,7 +846,6 @@ class StockService extends BaseService
{ {
// Hard fail for now, as we not yet support transfering tare weight enabled products // Hard fail for now, as we not yet support transfering tare weight enabled products
throw new \Exception('Transfering tare weight enabled products is not yet possible'); throw new \Exception('Transfering tare weight enabled products is not yet possible');
if ($amount < floatval($productDetails->product->tare_weight)) if ($amount < floatval($productDetails->product->tare_weight))
{ {
throw new \Exception('The amount cannot be lower than the defined tare weight'); throw new \Exception('The amount cannot be lower than the defined tare weight');
@ -912,23 +886,22 @@ class StockService extends BaseService
$locationFrom = $this->getDatabase()->locations()->where('id', $locationIdFrom)->fetch(); $locationFrom = $this->getDatabase()->locations()->where('id', $locationIdFrom)->fetch();
$locationTo = $this->getDatabase()->locations()->where('id', $locationIdTo)->fetch(); $locationTo = $this->getDatabase()->locations()->where('id', $locationIdTo)->fetch();
// Product was moved from a non-freezer to freezer location -> freeze // Product was moved from a non-freezer to freezer location -> freeze
if (intval($locationFrom->is_freezer) === 0 && intval($locationTo->is_freezer) === 1 && $productDetails->product->default_best_before_days_after_freezing > 0) if (intval($locationFrom->is_freezer) === 0 && intval($locationTo->is_freezer) === 1 && $productDetails->product->default_best_before_days_after_freezing > 0)
{ {
$newBestBeforeDate = date('Y-m-d', strtotime('+' . $productDetails->product->default_best_before_days_after_freezing . ' days')); $newBestBeforeDate = date('Y-m-d', strtotime('+' . $productDetails->product->default_best_before_days_after_freezing . ' days'));
} }
// Product was moved from a freezer to non-freezer location -> thaw // Product was moved from a freezer to non-freezer location -> thaw
if (intval($locationFrom->is_freezer) === 1 && intval($locationTo->is_freezer) === 0 && $productDetails->product->default_best_before_days_after_thawing > 0) if (intval($locationFrom->is_freezer) === 1 && intval($locationTo->is_freezer) === 0 && $productDetails->product->default_best_before_days_after_thawing > 0)
{ {
$newBestBeforeDate = date('Y-m-d', strtotime('+' . $productDetails->product->default_best_before_days_after_thawing . ' days')); $newBestBeforeDate = date('Y-m-d', strtotime('+' . $productDetails->product->default_best_before_days_after_thawing . ' days'));
} }
} }
$correlationId = uniqid(); $correlationId = uniqid();
if ($amount >= $stockEntry->amount) // Take the whole stock entry if ($amount >= $stockEntry->amount)
{ { // Take the whole stock entry
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([ $logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([
'product_id' => $stockEntry->product_id, 'product_id' => $stockEntry->product_id,
'amount' => $stockEntry->amount * -1, 'amount' => $stockEntry->amount * -1,
@ -968,8 +941,8 @@ class StockService extends BaseService
$amount -= $stockEntry->amount; $amount -= $stockEntry->amount;
} }
else // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount else
{ { // Stock entry amount is > than needed amount -> split the stock entry resp. update the amount
$restStockAmount = $stockEntry->amount - $amount; $restStockAmount = $stockEntry->amount - $amount;
$logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([ $logRowForLocationFrom = $this->getDatabase()->stock_log()->createRow([
@ -1026,7 +999,6 @@ class StockService extends BaseService
$amount = 0; $amount = 0;
} }
} }
return $this->getDatabase()->lastInsertId(); return $this->getDatabase()->lastInsertId();
@ -1041,7 +1013,7 @@ class StockService extends BaseService
throw new \Exception('Booking does not exist or was already undone'); throw new \Exception('Booking does not exist or was already undone');
} }
// Undo all correlated bookings first, in order from newest first to the oldest // Undo all correlated bookings first, in order from newest first to the oldest
if (!$skipCorrelatedBookings && !empty($logRow->correlation_id)) if (!$skipCorrelatedBookings && !empty($logRow->correlation_id))
{ {
$correlatedBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll(); $correlatedBookings = $this->getDatabase()->stock_log()->where('undone = 0 AND correlation_id = :1', $logRow->correlation_id)->orderBy('id', 'DESC')->fetchAll();
@ -1122,7 +1094,7 @@ class StockService extends BaseService
} }
elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_FROM) elseif ($logRow->transaction_type === self::TRANSACTION_TYPE_TRANSFER_FROM)
{ {
// Add corresponding amount back to stock or // Add corresponding amount back to stock or
// create a row if missing // create a row if missing
$stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch(); $stockRow = $this->getDatabase()->stock()->where('stock_id = :1 AND location_id = :2', $logRow->stock_id, $logRow->location_id)->fetch();
@ -1214,7 +1186,6 @@ class StockService extends BaseService
{ {
throw new \Exception('This booking cannot be undone'); throw new \Exception('This booking cannot be undone');
} }
} }
public function UndoTransaction($transactionId) public function UndoTransaction($transactionId)
@ -1230,7 +1201,6 @@ class StockService extends BaseService
{ {
$this->UndoBooking($transactionBooking->id, true); $this->UndoBooking($transactionBooking->id, true);
} }
} }
private function LoadBarcodeLookupPlugin() private function LoadBarcodeLookupPlugin()
@ -1253,7 +1223,6 @@ class StockService extends BaseService
{ {
throw new \Exception("Plugin $pluginName was not found"); throw new \Exception("Plugin $pluginName was not found");
} }
} }
private function LocationExists($locationId) private function LocationExists($locationId)
@ -1273,5 +1242,4 @@ class StockService extends BaseService
$shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch(); $shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch();
return $shoppingListRow !== null; return $shoppingListRow !== null;
} }
} }

View File

@ -46,5 +46,4 @@ class TasksService extends BaseService
$taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch(); $taskRow = $this->getDatabase()->tasks()->where('id = :1', $taskId)->fetch();
return $taskRow !== null; return $taskRow !== null;
} }
} }

View File

@ -5,27 +5,16 @@ namespace Grocy\Services;
class UserfieldsService extends BaseService class UserfieldsService extends BaseService
{ {
const USERFIELD_TYPE_CHECKBOX = 'checkbox'; const USERFIELD_TYPE_CHECKBOX = 'checkbox';
const USERFIELD_TYPE_DATE = 'date'; const USERFIELD_TYPE_DATE = 'date';
const USERFIELD_TYPE_DATETIME = 'datetime'; const USERFIELD_TYPE_DATETIME = 'datetime';
const USERFIELD_TYPE_DECIMAL_NUMBER = 'number-decimal'; const USERFIELD_TYPE_DECIMAL_NUMBER = 'number-decimal';
const USERFIELD_TYPE_FILE = 'file'; const USERFIELD_TYPE_FILE = 'file';
const USERFIELD_TYPE_IMAGE = 'image'; const USERFIELD_TYPE_IMAGE = 'image';
const USERFIELD_TYPE_INTEGRAL_NUMBER = 'number-integral'; const USERFIELD_TYPE_INTEGRAL_NUMBER = 'number-integral';
const USERFIELD_TYPE_LINK = 'link'; const USERFIELD_TYPE_LINK = 'link';
const USERFIELD_TYPE_PRESET_CHECKLIST = 'preset-checklist'; const USERFIELD_TYPE_PRESET_CHECKLIST = 'preset-checklist';
const USERFIELD_TYPE_PRESET_LIST = 'preset-list'; const USERFIELD_TYPE_PRESET_LIST = 'preset-list';
const USERFIELD_TYPE_SINGLE_LINE_TEXT = 'text-single-line'; const USERFIELD_TYPE_SINGLE_LINE_TEXT = 'text-single-line';
const USERFIELD_TYPE_SINGLE_MULTILINE_TEXT = 'text-multi-line'; const USERFIELD_TYPE_SINGLE_MULTILINE_TEXT = 'text-multi-line';
protected $OpenApiSpec = null; protected $OpenApiSpec = null;
@ -117,14 +106,14 @@ class UserfieldsService extends BaseService
$alreadyExistingEntry = $this->getDatabase()->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch(); $alreadyExistingEntry = $this->getDatabase()->userfield_values()->where('field_id = :1 AND object_id = :2', $fieldId, $objectId)->fetch();
if ($alreadyExistingEntry) // Update if ($alreadyExistingEntry)
{ { // Update
$alreadyExistingEntry->update([ $alreadyExistingEntry->update([
'value' => $value 'value' => $value
]); ]);
} }
else // Insert else
{ { // Insert
$newRow = $this->getDatabase()->userfield_values()->createRow([ $newRow = $this->getDatabase()->userfield_values()->createRow([
'field_id' => $fieldId, 'field_id' => $fieldId,
'object_id' => $objectId, 'object_id' => $objectId,
@ -132,9 +121,7 @@ class UserfieldsService extends BaseService
]); ]);
$newRow->save(); $newRow->save();
} }
} }
} }
public function __construct() public function __construct()
@ -156,5 +143,4 @@ class UserfieldsService extends BaseService
{ {
return in_array($entity, $this->GetEntities()); return in_array($entity, $this->GetEntities());
} }
} }

View File

@ -62,7 +62,6 @@ class UsersService extends BaseService
{ {
return null; return null;
} }
} }
public function GetUserSettings($userId) public function GetUserSettings($userId)
@ -106,7 +105,6 @@ class UsersService extends BaseService
]); ]);
$settingRow->save(); $settingRow->save();
} }
} }
private function UserExists($userId) private function UserExists($userId)
@ -114,5 +112,4 @@ class UsersService extends BaseService
$userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch(); $userRow = $this->getDatabase()->users()->where('id = :1', $userId)->fetch();
return $userRow !== null; return $userRow !== null;
} }
} }