Failed Conditions
Push — master ( e0fde8...98a030 )
by
unknown
44:34 queued 15:21
created

AssetController   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 480
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 212
dl 0
loc 480
rs 8.48
c 0
b 0
f 0
wmc 49

6 Methods

Rating   Name   Duplication   Size   Complexity  
C updateAction() 0 85 14
B detailsAction() 0 77 7
A getStatusesByAllowedAction() 0 11 3
B attachToCartItemAction() 0 45 6
B updateBusinessUnitRelationAction() 0 72 10
B createAction() 0 63 9

How to fix   Complexity   

Complex Class

Complex classes like AssetController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AssetController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Copyright © 2016-present Spryker Systems GmbH. All rights reserved.
5
 * Use of this software requires acceptance of the Evaluation License Agreement. See LICENSE file.
6
 */
7
8
namespace SprykerFeature\Yves\SelfServicePortal\Controller;
9
10
use Generated\Shared\Transfer\CompanyBusinessUnitTransfer;
11
use Generated\Shared\Transfer\ItemTransfer;
12
use Generated\Shared\Transfer\SspAssetBusinessUnitAssignmentTransfer;
13
use Generated\Shared\Transfer\SspAssetCollectionRequestTransfer;
14
use Generated\Shared\Transfer\SspAssetConditionsTransfer;
15
use Generated\Shared\Transfer\SspAssetCriteriaTransfer;
16
use Generated\Shared\Transfer\SspAssetIncludeTransfer;
17
use Generated\Shared\Transfer\SspAssetQuoteItemAttachmentRequestTransfer;
18
use Spryker\Yves\Kernel\Controller\AbstractController;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, SprykerFeature\Yves\Self...ller\AbstractController. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
19
use Spryker\Yves\Kernel\PermissionAwareTrait;
20
use Spryker\Yves\Kernel\View\View;
21
use SprykerFeature\Shared\SelfServicePortal\Plugin\Permission\CreateSspAssetPermissionPlugin;
22
use SprykerFeature\Shared\SelfServicePortal\Plugin\Permission\UnassignSspAssetPermissionPlugin;
23
use SprykerFeature\Shared\SelfServicePortal\Plugin\Permission\UpdateSspAssetPermissionPlugin;
24
use SprykerFeature\Yves\SelfServicePortal\Asset\Form\QuoteItemSspAssetForm;
25
use SprykerFeature\Yves\SelfServicePortal\Asset\Form\SspAssetBusinessUnitRelationsForm;
26
use SprykerFeature\Yves\SelfServicePortal\Plugin\Router\SelfServicePortalPageRouteProviderPlugin;
27
use SprykerFeature\Yves\SelfServicePortal\SelfServicePortalConfig;
28
use Symfony\Component\HttpFoundation\JsonResponse;
29
use Symfony\Component\HttpFoundation\RedirectResponse;
30
use Symfony\Component\HttpFoundation\Request;
31
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
32
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
33
34
/**
35
 * @method \SprykerFeature\Client\SelfServicePortal\SelfServicePortalClientInterface getClient()
36
 * @method \SprykerFeature\Yves\SelfServicePortal\SelfServicePortalFactory getFactory()
37
 * @method \SprykerFeature\Yves\SelfServicePortal\SelfServicePortalConfig getConfig()
38
 */
39
class AssetController extends AbstractController
40
{
41
    use PermissionAwareTrait;
42
43
    /**
44
     * @var string
45
     */
46
    protected const GLOSSARY_KEY_ASSET_CREATED = 'self_service_portal.asset.success.created';
47
48
    /**
49
     * @var string
50
     */
51
    protected const GLOSSARY_KEY_ASSET_UPDATED = 'self_service_portal.asset.success.updated';
52
53
    /**
54
     * @var string
55
     */
56
    protected const GLOSSARY_KEY_ASSET_CREATE_ERROR = 'self_service_portal.asset.error.create';
57
58
    /**
59
     * @var string
60
     */
61
    protected const GLOSSARY_KEY_ASSET_UPDATE_ERROR = 'self_service_portal.asset.error.update';
62
63
    /**
64
     * @var string
65
     */
66
    protected const GLOSSARY_KEY_BUSINESS_UNIT_RELATION_UPDATED = 'self_service_portal.asset.success.business_unit_relation_updated';
67
68
    /**
69
     * @var string
70
     */
71
    protected const MESSAGE_CART_SSP_ASSET_CHANGED_SUCCESS = 'self_service_portal.ssp_asset.success.attached_to_cart';
72
73
    /**
74
     * @uses \SprykerShop\Yves\CustomerPage\Plugin\Router\CustomerPageRouteProviderPlugin::ROUTE_CUSTOMER_OVERVIEW
75
     *
76
     * @var string
77
     */
78
    protected const ROUTE_CUSTOMER_OVERVIEW = 'customer/overview';
79
80
     /**
81
      * @var string
82
      */
83
    protected const FLASH_MESSAGE_LIST_TEMPLATE_PATH = '@ShopUi/components/organisms/flash-message-list/flash-message-list.twig';
84
85
    /**
86
     * @var string
87
     */
88
    protected const KEY_MESSAGES = 'messages';
89
90
    /**
91
     * The number of services to be included in the SspAssetTransfer.
92
     * This constant is used to limit the number of services fetched for each asset.
93
     *
94
     * @var int
95
     */
96
    protected const SERVICE_COUNT = 4;
97
98
    /**
99
     * @uses \SprykerShop\Yves\CartPage\Plugin\Router\CartPageAsyncRouteProviderPlugin::ROUTE_NAME_CART_ASYNC_VIEW
100
     *
101
     * @var string
102
     */
103
    protected const ROUTE_NAME_CART_ASYNC_VIEW = 'cart/async/view';
104
105
    /**
106
     * @var string
107
     */
108
    protected const GLOSSARY_KEY_ASSET_ATTACH_TO_CART_ITEM_ERROR = 'self_service_portal.asset.error.attach_to_cart_item';
109
110
    /**
111
     * @param \Symfony\Component\HttpFoundation\Request $request
112
     *
113
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
114
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
115
     *
116
     * @return \Spryker\Yves\Kernel\View\View|\Symfony\Component\HttpFoundation\RedirectResponse
117
     */
118
    public function detailsAction(Request $request): View|RedirectResponse
119
    {
120
        $sspAssetReference = (string)$request->query->get('reference');
121
        if (!$sspAssetReference) {
122
            throw new NotFoundHttpException('Asset reference not found');
123
        }
124
125
        $companyUserTransfer = $this->getFactory()->getCompanyUserClient()->findCompanyUser();
126
127
        if (!$this->getFactory()->createSspAssetCustomerPermissionChecker()->canViewAsset()) {
128
            throw new AccessDeniedHttpException('self_service_portal.asset.access.denied');
129
        }
130
131
        if (!$companyUserTransfer) {
132
            throw new NotFoundHttpException('Company user not found');
133
        }
134
135
        $companyUserTransfer->setCustomer($this->getFactory()->getCustomerClient()->getCustomerById($companyUserTransfer->getFkCustomerOrFail()));
136
137
        $sspAssetCriteriaTransfer = (new SspAssetCriteriaTransfer())
138
            ->setSspAssetConditions(
139
                (new SspAssetConditionsTransfer())
140
                    ->addReference($sspAssetReference)
141
                    ->setStatuses(
142
                        $this->getStatusesByAllowedAction(SelfServicePortalConfig::ASSET_ACTION_VIEW),
143
                    ),
144
            )
145
            ->setInclude(
146
                (new SspAssetIncludeTransfer())
147
                    ->setWithOwnerCompanyBusinessUnit(true)
148
                    ->setWithAssignedBusinessUnits(true)
149
                    ->setWithSspInquiries(true)
150
                    ->setWithFiles(true)
151
                    ->setWithServicesCount(static::SERVICE_COUNT),
152
            );
153
154
        $sspAssetCriteriaTransfer->setCompanyUser($companyUserTransfer);
155
156
        $sspAssetCollectionTransfer = $this->getClient()->getSspAssetCollection(
157
            $sspAssetCriteriaTransfer,
158
        );
159
160
        /** @var \Generated\Shared\Transfer\SspAssetTransfer|null $sspAssetTransfer */
161
        $sspAssetTransfer = $sspAssetCollectionTransfer->getSspAssets()->getIterator()->current();
162
163
        if (!$sspAssetTransfer) {
164
            throw new NotFoundHttpException(sprintf(
165
                'Ssp Asset with provided Reference %s was not found.',
166
                $sspAssetReference,
167
            ));
168
        }
169
170
        $canBusinessUnitBeUnassigned = false;
171
        foreach ($sspAssetTransfer->getBusinessUnitAssignments() as $sspAssetBusinessUnitAssignmentTransfer) {
172
            if ($sspAssetBusinessUnitAssignmentTransfer->getCompanyBusinessUnitOrFail()->getIdCompanyBusinessUnitOrFail() === $companyUserTransfer->getCompanyBusinessUnitOrFail()->getIdCompanyBusinessUnit()) {
173
                $canBusinessUnitBeUnassigned = true;
174
            }
175
        }
176
177
        return $this->view(
178
            [
179
                'sspAsset' => $sspAssetTransfer,
180
                'canBusinessUnitBeUnassigned' => $canBusinessUnitBeUnassigned,
181
                'unassignBusinessUnitForm' => $this->getFactory()->createSspAssetBusinessUnitRelationsForm([
182
                    SspAssetBusinessUnitRelationsForm::FIELD_BUSINESS_UNIT_ID => $companyUserTransfer->getCompanyBusinessUnitOrFail()->getIdCompanyBusinessUnitOrFail(),
183
                    SspAssetBusinessUnitRelationsForm::FIELD_ASSET_REFERENCE => $sspAssetReference,
184
                ])->createView(),
185
                'isUnassignmentAllowed' => in_array(
186
                    $sspAssetTransfer->getStatusOrFail(),
187
                    $this->getStatusesByAllowedAction(SelfServicePortalConfig::ASSET_ACTION_UNASSIGN),
188
                ),
189
                'isUpdateAllowed' => in_array(
190
                    $sspAssetTransfer->getStatusOrFail(),
191
                    $this->getStatusesByAllowedAction(SelfServicePortalConfig::ASSET_ACTION_UPDATE),
192
                )],
193
            [],
194
            '@SelfServicePortal/views/asset-details/asset-details.twig',
195
        );
196
    }
197
198
    /**
199
     * @param \Symfony\Component\HttpFoundation\Request $request
200
     *
201
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
202
     *
203
     * @return \Spryker\Yves\Kernel\View\View|\Symfony\Component\HttpFoundation\RedirectResponse
204
     */
205
    public function createAction(Request $request): View|RedirectResponse
206
    {
207
        $companyUserTransfer = $this->getFactory()
208
            ->getCompanyUserClient()
209
            ->findCompanyUser();
210
211
        if (!$companyUserTransfer) {
212
            $this->addErrorMessage('company.error.company_user_not_found');
213
214
            return $this->redirectResponseInternal(static::ROUTE_CUSTOMER_OVERVIEW);
215
        }
216
217
        if (!$this->can(CreateSspAssetPermissionPlugin::KEY)) {
218
            throw new AccessDeniedHttpException('self_service_portal.asset.access.denied');
219
        }
220
221
        $sspAssetCreateForm = $this->getFactory()
222
            ->createAssetForm()
223
            ->handleRequest($request);
224
225
        if ($sspAssetCreateForm->isSubmitted() && $sspAssetCreateForm->isValid()) {
226
            $sspAssetTransfer = $this->getFactory()->createSspAssetFormDataToTransferMapper()->mapFormDataToSspAssetTransfer(
227
                $sspAssetCreateForm,
228
                $sspAssetCreateForm->getData(),
229
            );
230
231
            $sspAssetTransfer->addBusinessUnitAssignment(
232
                (new SspAssetBusinessUnitAssignmentTransfer())->setCompanyBusinessUnit(
233
                    $companyUserTransfer->getCompanyBusinessUnit(),
234
                ),
235
            );
236
237
            $sspAssetTransfer->setCompanyBusinessUnit($companyUserTransfer->getCompanyBusinessUnit());
238
239
            $sspAssetCollectionResponseTransfer = $this->getClient()->createSspAssetCollection(
240
                (new SspAssetCollectionRequestTransfer())
241
                    ->addSspAsset($sspAssetTransfer)
242
                    ->setCompanyUser($companyUserTransfer),
243
            );
244
245
            if (!$sspAssetCollectionResponseTransfer->getErrors()->count() && $sspAssetCollectionResponseTransfer->getSspAssets()->count()) {
246
                $this->addSuccessMessage(static::GLOSSARY_KEY_ASSET_CREATED);
247
248
                return $this->redirectResponseInternal(SelfServicePortalPageRouteProviderPlugin::ROUTE_NAME_ASSET_DETAILS, [
249
                    'reference' => $sspAssetCollectionResponseTransfer->getSspAssets()->getIterator()->current()->getReference(),
250
                ]);
251
            }
252
253
            foreach ($sspAssetCollectionResponseTransfer->getErrors() as $error) {
254
                $this->addErrorMessage($error->getMessageOrFail());
255
            }
256
257
            if (!$sspAssetCollectionResponseTransfer->getSspAssets()->count()) {
258
                $this->addErrorMessage(static::GLOSSARY_KEY_ASSET_CREATE_ERROR);
259
            }
260
        }
261
262
        return $this->view(
263
            [
264
                'form' => $sspAssetCreateForm->createView(),
265
            ],
266
            [],
267
            '@SelfServicePortal/views/asset-create/asset-create.twig',
268
        );
269
    }
270
271
    /**
272
     * @param \Symfony\Component\HttpFoundation\Request $request
273
     *
274
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
275
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
276
     *
277
     * @return \Spryker\Yves\Kernel\View\View|\Symfony\Component\HttpFoundation\RedirectResponse
278
     */
279
    public function updateAction(Request $request): View|RedirectResponse
280
    {
281
        $sspAssetReference = $request->get('reference');
282
283
        if (!$sspAssetReference) {
284
            throw new NotFoundHttpException('Asset reference not found');
285
        }
286
287
        if (!$this->can(UpdateSspAssetPermissionPlugin::KEY)) {
288
            throw new AccessDeniedHttpException('self_service_portal.asset.access.denied');
289
        }
290
291
        $companyUserTransfer = $this->getFactory()
292
            ->getCompanyUserClient()
293
            ->findCompanyUser();
294
295
        if (!$companyUserTransfer) {
296
            $this->addErrorMessage('company.error.company_user_not_found');
297
298
            return $this->redirectResponseInternal(static::ROUTE_CUSTOMER_OVERVIEW);
299
        }
300
301
        $sspAssetFormDataProvider = $this->getFactory()->createSspAssetFormDataProvider();
302
        $sspAssetTransfer = $sspAssetFormDataProvider->getData($sspAssetReference, $companyUserTransfer);
303
304
        if (!$sspAssetTransfer) {
305
            throw new NotFoundHttpException('ssp_asset.error.not_found');
306
        }
307
308
        if (
309
            !in_array(
310
                $sspAssetTransfer->getStatusOrFail(),
311
                $this->getStatusesByAllowedAction(SelfServicePortalConfig::ASSET_ACTION_UPDATE),
312
            )
313
        ) {
314
            throw new AccessDeniedHttpException('self_service_portal.asset.access.status.restricted');
315
        }
316
317
        $sspAssetUpdateForm = $this->getFactory()
318
            ->createAssetForm($sspAssetTransfer, $sspAssetFormDataProvider->getOptions($sspAssetTransfer))
319
            ->handleRequest($request);
320
321
        if ($sspAssetUpdateForm->isSubmitted() && $sspAssetUpdateForm->isValid()) {
322
            $sspAssetTransfer = $this->getFactory()->createSspAssetFormDataToTransferMapper()->mapFormDataToSspAssetTransfer(
323
                $sspAssetUpdateForm,
324
                $sspAssetUpdateForm->getData(),
325
            );
326
327
            $sspAssetCollectionResponseTransfer = $this->getClient()->updateSspAssetCollection(
328
                (new SspAssetCollectionRequestTransfer())->setCompanyUser($companyUserTransfer)
329
                    ->addSspAsset($sspAssetTransfer),
330
            );
331
332
            if (!$sspAssetCollectionResponseTransfer->getErrors()->count() && $sspAssetCollectionResponseTransfer->getSspAssets()->count()) {
333
                $this->addSuccessMessage(static::GLOSSARY_KEY_ASSET_UPDATED);
334
335
                return $this->redirectResponseInternal(SelfServicePortalPageRouteProviderPlugin::ROUTE_NAME_ASSET_DETAILS, [
336
                    'reference' => $sspAssetCollectionResponseTransfer->getSspAssets()->getIterator()->current()->getReference(),
337
                ]);
338
            }
339
340
            foreach ($sspAssetCollectionResponseTransfer->getErrors() as $error) {
341
                $this->addErrorMessage($error->getMessageOrFail());
342
            }
343
344
            if (!$sspAssetCollectionResponseTransfer->getSspAssets()->count()) {
345
                $this->addErrorMessage(static::GLOSSARY_KEY_ASSET_UPDATE_ERROR);
346
            }
347
        }
348
349
        $currentCompanyBusinessUnitAssigment = null;
350
        foreach ($sspAssetTransfer->getBusinessUnitAssignments() as $sspBusinessUnitAssetAssignmentTransfer) {
351
            if ($sspBusinessUnitAssetAssignmentTransfer->getCompanyBusinessUnitOrFail()->getIdCompanyBusinessUnitOrFail() === $companyUserTransfer->getCompanyBusinessUnitOrFail()->getIdCompanyBusinessUnit()) {
352
                $currentCompanyBusinessUnitAssigment = $sspBusinessUnitAssetAssignmentTransfer;
353
            }
354
        }
355
356
        return $this->view(
357
            [
358
                'form' => $sspAssetUpdateForm->createView(),
359
                'sspAsset' => $sspAssetTransfer,
360
                'currentCompanyBusinessUnitAssigment' => $currentCompanyBusinessUnitAssigment,
361
            ],
362
            [],
363
            '@SelfServicePortal/views/asset-update/asset-update.twig',
364
        );
365
    }
366
367
    /**
368
     * @param \Symfony\Component\HttpFoundation\Request $request
369
     *
370
     * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
371
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
372
     *
373
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
374
     */
375
    public function updateBusinessUnitRelationAction(Request $request): RedirectResponse
376
    {
377
        $companyUserTransfer = $this->getFactory()->getCompanyUserClient()->findCompanyUser();
378
379
        if (!$companyUserTransfer) {
380
            return $this->redirectResponseInternal(static::ROUTE_CUSTOMER_OVERVIEW);
381
        }
382
383
        if (!$this->can(UnassignSspAssetPermissionPlugin::KEY)) {
384
            throw new AccessDeniedHttpException('self_service_portal.asset.access.denied');
385
        }
386
387
        $form = $this->getFactory()->createSspAssetBusinessUnitRelationsForm();
388
389
        $form->handleRequest($request);
390
391
        if ($form->isSubmitted() && $form->isValid()) {
392
            $formData = $form->getData();
393
394
            /** @var \Generated\Shared\Transfer\SspAssetTransfer|null $sspAssetTransfer */
395
            $sspAssetTransfer = $this->getClient()->getSspAssetCollection(
396
                (new SspAssetCriteriaTransfer())->setCompanyUser($companyUserTransfer)
397
                    ->setSspAssetConditions(
398
                        (new SspAssetConditionsTransfer())->addReference($formData[SspAssetBusinessUnitRelationsForm::FIELD_ASSET_REFERENCE]),
399
                    ),
400
            )->getSspAssets()->getIterator()->current();
401
402
            if (!$sspAssetTransfer) {
403
                throw new NotFoundHttpException('self_service_portal.asset.error.not_found');
404
            }
405
406
            if (!in_array($sspAssetTransfer->getStatusOrFail(), $this->getStatusesByAllowedAction(SelfServicePortalConfig::ASSET_ACTION_UNASSIGN))) {
407
                throw new AccessDeniedHttpException('self_service_portal.asset.access.status.restricted');
408
            }
409
410
            $businessUnitIdToUnassign = (int)$formData[SspAssetBusinessUnitRelationsForm::FIELD_BUSINESS_UNIT_ID];
411
412
            if ($sspAssetTransfer->getCompanyBusinessUnit()?->getIdCompanyBusinessUnitOrFail() === $businessUnitIdToUnassign) {
413
                $this->addErrorMessage('self_service_portal.asset.error.cannot_unassign_own_business_unit');
414
415
                return $this->redirectResponseInternal(SelfServicePortalPageRouteProviderPlugin::ROUTE_NAME_ASSET_DETAILS, [
416
                    'reference' => $sspAssetTransfer->getReference(),
417
                ]);
418
            }
419
420
            $sspAssetCollectionResponseTransfer = $this->getClient()->updateSspAssetCollection(
421
                (new SspAssetCollectionRequestTransfer())
422
                    ->addBusinessUnitAssignmentToDelete(
423
                        (new SspAssetBusinessUnitAssignmentTransfer())
424
                            ->setCompanyBusinessUnit(
425
                                (new CompanyBusinessUnitTransfer())->setIdCompanyBusinessUnit($businessUnitIdToUnassign),
426
                            )
427
                            ->setSspAsset($sspAssetTransfer),
428
                    ),
429
            );
430
431
            if ($sspAssetCollectionResponseTransfer->getErrors()->count()) {
432
                foreach ($sspAssetCollectionResponseTransfer->getErrors() as $error) {
433
                    $this->addErrorMessage($error->getMessageOrFail());
434
                }
435
436
                return $this->redirectResponseInternal(SelfServicePortalPageRouteProviderPlugin::ROUTE_NAME_ASSET_DETAILS, [
437
                    'reference' => $sspAssetTransfer->getReference(),
438
                ]);
439
            }
440
441
            $this->addSuccessMessage(static::GLOSSARY_KEY_BUSINESS_UNIT_RELATION_UPDATED);
442
443
            return $this->redirectResponseInternal(SelfServicePortalPageRouteProviderPlugin::ROUTE_NAME_ASSET_LIST);
444
        }
445
446
        return $this->redirectResponseInternal(SelfServicePortalPageRouteProviderPlugin::ROUTE_NAME_ASSET_LIST);
447
    }
448
449
    /**
450
     * @param \Symfony\Component\HttpFoundation\Request $request
451
     *
452
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
453
     *
454
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
455
     */
456
    public function attachToCartItemAction(Request $request): RedirectResponse|JsonResponse
457
    {
458
        $companyUserTransfer = $this->getFactory()->getCompanyUserClient()->findCompanyUser();
459
460
        if (!$companyUserTransfer) {
461
            $this->addErrorMessage('company.error.company_user_not_found');
462
463
            return $this->redirectResponseInternal(static::ROUTE_CUSTOMER_OVERVIEW);
464
        }
465
466
        if (!$this->getFactory()->createSspAssetCustomerPermissionChecker()->canViewAsset()) {
467
            throw new AccessDeniedHttpException('self_service_portal.asset.access.denied');
468
        }
469
470
        $form = $this->getFactory()->createQuoteItemSspAssetForm();
471
        $form->handleRequest($request);
472
473
        if (!$form->isSubmitted() || !$form->isValid()) {
474
            $this->addErrorMessage($this->getFactory()->getGlossaryClient()->translate(
475
                static::GLOSSARY_KEY_ASSET_ATTACH_TO_CART_ITEM_ERROR,
476
                $this->getLocale(),
477
            ));
478
479
            return $this->jsonResponse([
480
                static::KEY_MESSAGES => $this->renderView(static::FLASH_MESSAGE_LIST_TEMPLATE_PATH)->getContent(),
481
            ]);
482
        }
483
484
        $quoteResponseTransfer = $this->getFactory()->getSelfServicePortalClient()->attachSspAssetToQuoteItem(
485
            (new SspAssetQuoteItemAttachmentRequestTransfer())
486
                ->setSspAssetReference($form->get(QuoteItemSspAssetForm::FIELD_SSP_ASSET_REFERENCE)->getData())
487
                ->setItem(
488
                    (new ItemTransfer())
489
                        ->setSku($form->get(QuoteItemSspAssetForm::FIELD_SKU)->getData())
490
                        ->setGroupKey($form->get(QuoteItemSspAssetForm::FIELD_GROUP_KEY)->getData()),
491
                ),
492
        );
493
494
        if ($quoteResponseTransfer->getIsSuccessful()) {
495
            $this->addSuccessMessage($this->getFactory()
496
                ->getGlossaryClient()
497
                ->translate(static::MESSAGE_CART_SSP_ASSET_CHANGED_SUCCESS, $this->getLocale(), ['%sku%' => $form->get(QuoteItemSspAssetForm::FIELD_SKU)->getData()]));
498
        }
499
500
        return $this->redirectResponseInternal(static::ROUTE_NAME_CART_ASYNC_VIEW);
501
    }
502
503
    /**
504
     * @param string $allowedAction
505
     *
506
     * @return array<string>
507
     */
508
    protected function getStatusesByAllowedAction(string $allowedAction): array
509
    {
510
        $statuses = [];
511
512
        foreach ($this->getFactory()->getConfig()->getSspStatusAllowedActionsMapping() as $status => $allowedActions) {
513
            if (in_array($allowedAction, $allowedActions)) {
514
                $statuses[] = $status;
515
            }
516
        }
517
518
        return $statuses;
519
    }
520
}
521