Lines 84.39% 173 / 205
Methods 73.33% 11 / 15
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readResponse 96.51% 83 / 86 0.00% 0 / 1 11
 handleDownloadRequest 95.23% 20 / 21 0.00% 0 / 1 4
 renderHtmlResponse 100.00% 26 / 26 100.00% 1 / 1 1
 [BO\Zmsstatistic\BaseController] __invoke 100.00% 5 / 5 100.00% 1 / 1 2
 [BO\Zmsstatistic\Helper\Access] initAccessRights 100.00% 6 / 6 100.00% 1 / 1 4
 [BO\Zmsstatistic\Helper\Access] readWorkstation 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsstatistic\Helper\Access] readDepartment 100.00% 5 / 5 100.00% 1 / 1 2
 [BO\Zmsstatistic\Helper\Access] readOrganisation 100.00% 5 / 5 100.00% 1 / 1 2
 [BO\Zmsstatistic\Helper\Access] readOwner 100.00% 5 / 5 100.00% 1 / 1 2
 [BO\Zmsstatistic\Helper\Access] validateAccessRights 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsstatistic\Helper\Access] validateAccess 100.00% 4 / 4 100.00% 1 / 1 7
 [BO\Zmsstatistic\Helper\Access] validateScope 66.66% 2 / 3 0.00% 0 / 1 4.59
 [BO\Zmsstatistic\Helper\Access] isPathWithoutScope 100.00% 5 / 5 100.00% 1 / 1 4
 [BO\Zmsstatistic\Helper\Access] testLogin 0.00% 0 / 27 0.00% 0 / 1 42
 [BO\Zmsstatistic\Helper\Access] exceptionTemplateExists 100.00% 2 / 2 100.00% 1 / 1 1
17class ReportCapacityIndex extends BaseController
18{
19    protected int $resolveLevel = 2;
20
21    /**
22     * @SuppressWarnings(Param)
23     * @return ResponseInterface
24     */
25    #[\Override]
26    public function readResponse(
27        RequestInterface $request,
28        ResponseInterface $response,
29        array $args
30    ): mixed {
31        $this->workstation->getUseraccount()->testPermissions(['statistic', 'capacityreport']);
32
33        /** @var \Psr\Http\Message\ServerRequestInterface $request */
34        $validator = $request->getAttribute('validator');
35        $reportCapacityService = new ReportCapacityService();
36        $reportHelper = new ReportHelper();
37
38        $selectedScopes = $reportHelper->extractSelectedScopes(
39            $validator->getParameter('scopes')->isArray()->getValue() ?? []
40        );
41
42        $workstationScopeId = $reportHelper->getWorkstationScopeId($this->workstation);
43        $scopeId = $reportHelper->resolveScopeIdParam($selectedScopes, $workstationScopeId);
44
45        $capacityPeriod = $workstationScopeId !== null
46            ? $reportCapacityService->getCapacityPeriod((string) $workstationScopeId)
47            : null;
48        $scopeDateBounds = $reportCapacityService->getScopeDateBoundsByScopeId();
49
50        $dateRange = $reportHelper->extractDateRange(
51            $validator->getParameter('from')->isString()->getValue(),
52            $validator->getParameter('to')->isString()->getValue()
53        );
54
55        $fetchedCapacity = $reportCapacityService->getExchangeCapacityData($scopeId, $dateRange, $args);
56        $exchangeCapacityDaily = null;
57        $exchangeCapacityChartDaily = null;
58        $exchangeCapacityChartSparseDaily = null;
59        $exchangeCapacityHourly = null;
60        $exchangeCapacityChartHourly = null;
61        $exchangeCapacityChartSparseHourly = null;
62        $displayExchanges = null;
63
64        if ($fetchedCapacity instanceof Exchange) {
65            $period = $args['period'] ?? null;
66            $displayExchanges = $reportCapacityService->buildCapacityDisplayExchanges(
67                $fetchedCapacity,
68                $dateRange,
69                $period
70            );
71            $exchangeCapacityDaily = $displayExchanges['dailyTable'];
72            $exchangeCapacityChartSparseDaily = $displayExchanges['dailyChartSparse'];
73            $exchangeCapacityChartDaily = $displayExchanges['dailyChartFull'];
74            $exchangeCapacityHourly = $displayExchanges['hourlyTable'];
75            $exchangeCapacityChartSparseHourly = $displayExchanges['hourlyChartSparse'];
76            $exchangeCapacityChartHourly = $displayExchanges['hourlyChartFull'];
77        }
78
79        $type = $validator->getParameter('type')->isString()->getValue();
80        if ($type) {
81            $granularity = $validator->getParameter('granularity')->isString()->getValue();
82            $timeline = $validator->getParameter('timeline')->isString()->getValue();
83            $downloadExchange = is_array($displayExchanges)
84                ? $reportCapacityService->selectDownloadExchange(
85                    $displayExchanges,
86                    $granularity,
87                    $timeline
88                )
89                : null;
90
91            return $this->handleDownloadRequest(
92                $request,
93                $response,
94                $args,
95                $scopeId,
96                $downloadExchange,
97                $dateRange,
98                $selectedScopes,
99                $reportCapacityService
100            );
101        }
102
103        $displayScopeIds = $selectedScopes;
104        if ($displayScopeIds === [] && $workstationScopeId !== null) {
105            $displayScopeIds = [(string) $workstationScopeId];
106        }
107        $scopeSlotTimes = [];
108        $visualization = $fetchedCapacity instanceof Exchange
109            ? ($fetchedCapacity['visualization'] ?? null)
110            : null;
111        if (is_array($visualization) && is_array($visualization['scopeSlotTimes'] ?? null)) {
112            $scopeSlotTimes = $visualization['scopeSlotTimes'];
113        }
114        if ($scopeSlotTimes === []) {
115            $scopeSlotTimes = $reportCapacityService->getSelectedScopeSlotTimes($displayScopeIds);
116        }
117        $scopeSlotTimeHint = $reportCapacityService->formatScopeSlotTimeHint($scopeSlotTimes);
118
119        return $this->renderHtmlResponse(
120            $response,
121            $args,
122            $capacityPeriod,
123            $dateRange,
124            $exchangeCapacityDaily,
125            $exchangeCapacityChartDaily,
126            $exchangeCapacityChartSparseDaily,
127            $selectedScopes,
128            $scopeDateBounds,
129            $scopeSlotTimeHint,
130            $exchangeCapacityHourly,
131            $exchangeCapacityChartHourly,
132            $exchangeCapacityChartSparseHourly
133        );
134    }
135
136    private function handleDownloadRequest(
137        RequestInterface $request,
138        ResponseInterface $response,
139        array $args,
140        string $scopeId,
141        mixed $downloadExchange,
142        ?array $dateRange,
143        array $selectedScopes = [],
144        ?ReportCapacityService $reportCapacityService = null
145    ): ResponseInterface {
146        if ($reportCapacityService === null) {
147            $reportCapacityService = new ReportCapacityService();
148        }
149
150        /** @var \Psr\Http\Message\ServerRequestInterface $request */
151        $validator = $request->getAttribute('validator');
152        $valueMode = $validator->getParameter('valueMode')->isString()->getValue();
153        $valueMode = $valueMode === 'minutes' ? 'minutes' : 'slots';
154        $channelMode = $validator->getParameter('channelMode')->isString()->getValue();
155        $channelMode = in_array($channelMode, ['total', 'public', 'intern_only'], true)
156            ? $channelMode
157            : 'total';
158
159        $args = $reportCapacityService->prepareDownloadArgs(
160            $args,
161            $scopeId,
162            $downloadExchange,
163            $dateRange,
164            $selectedScopes,
165            $valueMode,
166            $channelMode
167        );
168
169        /** @var mixed $container */
170        $container = \App::$slim->getContainer();
171        return (new Download\CapacityReport($container))
172            ->readResponse($request, $response, $args);
173    }
174
175    private function renderHtmlResponse(
176        ResponseInterface $response,
177        array $args,
178        mixed $capacityPeriod,
179        array|null $dateRange,
180        mixed $exchangeCapacityDaily,
181        Exchange|null $exchangeCapacityChartDaily,
182        Exchange|null $exchangeCapacityChartSparseDaily,
183        array $selectedScopes = [],
184        array $scopeDateBounds = [],
185        ?string $scopeSlotTimeHint = null,
186        Exchange|null $exchangeCapacityHourly = null,
187        Exchange|null $exchangeCapacityChartHourly = null,
188        Exchange|null $exchangeCapacityChartSparseHourly = null
189    ): ResponseInterface {
190        return Render::withHtml(
191            $response,
192            'page/reportCapacityIndex.twig',
193            [
194                'title' => 'Terminkapazität Standort',
195                'activeScope' => 'active',
196                'menuActive' => 'capacity',
197                'department' => $this->department,
198                'organisation' => $this->organisation,
199                'capacityPeriod' => $capacityPeriod,
200                'scopeDateBounds' => $scopeDateBounds,
201                'showAll' => 1,
202                'period' => $args['period'] ?? null,
203                'dateRange' => $dateRange,
204                'exchangeCapacityDaily' => $exchangeCapacityDaily,
205                'exchangeCapacityChartDaily' => $exchangeCapacityChartDaily,
206                'exchangeCapacityChartSparseDaily' => $exchangeCapacityChartSparseDaily,
207                'exchangeCapacityHourly' => $exchangeCapacityHourly,
208                'exchangeCapacityChartHourly' => $exchangeCapacityChartHourly,
209                'exchangeCapacityChartSparseHourly' => $exchangeCapacityChartSparseHourly,
210                'source' => ['entity' => 'CapacityIndex'],
211                'selectedScopeIds' => $selectedScopes,
212                'scopeSlotTimeHint' => $scopeSlotTimeHint,
213                'workstation' => $this->workstation->getArrayCopy(),
214            ]
215        );
216    }
217}

Inherited from BO\Zmsstatistic\BaseController

20    public function __invoke(RequestInterface $request, ResponseInterface $response, array $args)
21    {
22        $request = $this->initRequest($request);
23        if ($this->withAccess) {
24            $this->initAccessRights($request);
25        }
26        $noCacheResponse = \BO\Slim\Render::withLastModified($response, time(), '0');
27        return $this->readResponse($request, $noCacheResponse, $args);
28    }

Inherited from BO\Zmsstatistic\Helper\Access

33    protected function initAccessRights(RequestInterface $request): void
34    {
35        $this->workstation = $this->readWorkstation();
36        if ($this->workstation && isset($this->workstation->scope['id']) && $this->workstation->scope['id'] > 0) {
37            $this->department = $this->readDepartment();
38            $this->organisation = $this->readOrganisation();
39            $this->owner = $this->readOwner();
40        }
41        $this->validateAccessRights($request);
42    }
44    protected function readWorkstation(): mixed
45    {
46        $workstation = \App::http()->readGetResult('/workstation/', ['resolveReferences' => $this->resolveLevel]);
47        return $workstation->getEntity();
48    }
50    protected function readDepartment(): mixed
51    {
52        if ($this->workstation->getUseraccount()->hasPermissions(['statistic'])) {
53            return \App::http()
54                ->readGetResult('/scope/' . $this->workstation->scope['id'] . '/department/')
55                ->getEntity();
56        }
57        return null;
58    }
60    protected function readOrganisation(): mixed
61    {
62        if ($this->workstation->getUseraccount()->isSuperUser()) {
63            return \App::http()
64                ->readGetResult('/department/' . $this->department->getId() . '/organisation/')
65                ->getEntity();
66        }
67        return null;
68    }
70    protected function readOwner(): mixed
71    {
72        if ($this->workstation->getUseraccount()->isSuperUser()) {
73            return \App::http()
74                ->readGetResult('/organisation/' . $this->organisation->getId() . '/owner/')
75                ->getEntity();
76        }
77        return null;
78    }
80    protected function validateAccessRights(RequestInterface $request): void
81    {
82        $path = $request->getUri()->getPath();
83        $this->validateAccess($path);
84        $this->validateScope($path);
85    }
87    protected function validateAccess(string $path): void
88    {
89        if (
90            (false !== strpos($path, 'owner') && ! $this->owner) ||
91            (false !== strpos($path, 'organisation') && ! $this->organisation) ||
92            (false !== strpos($path, 'department') && ! $this->department)
93        ) {
94            throw new UserAccountAccessRightsFailed();
95        }
96    }
98    protected function validateScope(string $path): void
99    {
100        if (
101            $this->isPathWithoutScope($path)
102            && (! isset($this->workstation['scope']) || ! isset($this->workstation['scope']['id']))
103        ) {
104            throw new WorkstationMissingScope();
105        }
106    }
108    protected function isPathWithoutScope(string $path): bool
109    {
110        // TODO: refactor to integrate these access rules in the controller to make them visible
111        return (false === strpos($path, 'select')
112            && false === strpos($path, 'warehouse')
113            && false === strpos($path, 'logout')
114            && false === strpos($path, 'report')
115        );
116    }
121    protected function testLogin(mixed $input): mixed
122    {
123        $userAccount = new Useraccount(array(
124            'id' => $input['loginName'],
125            'password' => $input['password'],
126            'departments' => array('id' => 0) // required in schema validation
127        ));
128        try {
129            /** @var Workstation $workstation */
130            $workstation = \App::http()->readPostResult('/workstation/login/', $userAccount)->getEntity();
131            return $workstation;
132        } catch (\BO\Zmsclient\Exception $exception) {
133            $template = TwigExceptionHandler::getExceptionTemplate($exception);
134            if ('BO\Zmsentities\Exception\SchemaValidation' == $exception->template) {
135                $exceptionData = [
136                  'template' => 'exception/bo/zmsbackend/useraccount/exception/invalidcredentials.twig'
137                ];
138                $exceptionData['data']['password']['messages'] = [
139                    'Der Nutzername oder das Passwort wurden falsch eingegeben'
140                ];
141            } elseif ('BO\Zmsbackend\Useraccount\Exception\UserAlreadyLoggedIn' == $exception->template) {
142                Auth::setKey($exception->data['authkey'], time() + \App::SESSION_DURATION);
143                throw $exception;
144            } elseif (
145                '' != $exception->template
146                && $this->exceptionTemplateExists($template)
147            ) {
148                $exceptionData = [
149                  'template' => $template,
150                  'data' => $exception->data
151                ];
152            } else {
153                throw $exception;
154            }
155        }
156        return $exceptionData;
157    }
159    protected function exceptionTemplateExists(string $template): bool
160    {
161        /** @var mixed $container */
162        $container = \App::$slim->getContainer();
163        return $container->get('view')->getLoader()->exists($template);
164    }