Completed
Pull Request — master (#418)
by Jonas
02:55
created

isPricingMappingAllowedAction()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 38
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 8.439
c 0
b 0
f 0
cc 6
eloc 22
nc 5
nop 0
1
<?php
2
/**
3
 * (c) shopware AG <[email protected]>
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
8
use Shopware\Connect\Units;
9
use ShopwarePlugins\Connect\Components\ConnectExport;
10
use ShopwarePlugins\Connect\Components\Validator\ProductAttributesValidator\ProductsAttributesValidator;
11
use ShopwarePlugins\Connect\Components\Utils\UnitMapper;
12
use ShopwarePlugins\Connect\Components\Logger;
13
use ShopwarePlugins\Connect\Components\SnHttpClient;
14
use ShopwarePlugins\Connect\Components\ErrorHandler;
15
use Shopware\Connect\Gateway\ChangeGateway;
16
use ShopwarePlugins\Connect\Components\ProductQuery\BaseProductQuery;
17
use ShopwarePlugins\Connect\Components\ConfigFactory;
18
use Shopware\Models\Plugin\Plugin;
19
20
/**
21
 * @category  Shopware
22
 * @package   Shopware\Plugins\SwagConnect
23
 * @copyright Copyright (c) 2013, shopware AG (http://www.shopware.de)
24
 */
25
class Shopware_Controllers_Backend_ConnectConfig extends Shopware_Controllers_Backend_ExtJs
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
26
{
27
    /** @var \ShopwarePlugins\Connect\Components\Config */
28
    private $configComponent;
29
30
    /**
31
     * @var \ShopwarePlugins\Connect\Components\ConnectFactory
32
     */
33
    private $factory;
34
35
    /**
36
     * @var \ShopwarePlugins\Connect\Components\Utils\UnitMapper
37
     */
38
    private $unitMapper;
39
40
    /**
41
     * @var \ShopwarePlugins\Connect\Components\Logger
42
     */
43
    private $logger;
44
45
    /**
46
     * @var \Shopware\Components\Model\ModelRepository
47
     */
48
    private $customerGroupRepository;
49
50
    /**
51
     * @var \ShopwarePlugins\Connect\Components\PriceGateway
52
     */
53
    private $priceGateway;
54
55
    /**
56
     * @var \ShopwarePlugins\Connect\Components\SnHttpClient
57
     */
58
    private $snHttpClient;
59
60
    /**
61
     * The getGeneralAction function is an ExtJs event listener method of the
62
     * connect module. The function is used to load store
63
     * required in the general config form.
64
     * @return string
65
     */
66
    public function getGeneralAction()
67
    {
68
        $generalConfig = $this->getConfigComponent()->getGeneralConfig();
69
70
        $this->View()->assign([
71
            'success' => true,
72
            'data' => $generalConfig
73
        ]);
74
    }
75
76
    /**
77
     * The saveGeneralAction function is an ExtJs event listener method of the
78
     * connect module. The function is used to save store data.
79
     * @return string
80
     */
81 View Code Duplication
    public function saveGeneralAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
    {
83
        try {
84
            $data = $this->Request()->getParam('data');
85
            unset($data['id']);
86
            $this->getConfigComponent()->setGeneralConfigs($data);
87
88
            $this->View()->assign([
89
                'success' => true
90
            ]);
91
        } catch (\Exception $e) {
92
            $this->View()->assign([
93
                'success' => false,
94
                'message' => $e->getMessage()
95
            ]);
96
        }
97
    }
98
99
    public function changeLoggingAction()
100
    {
101
        try {
102
            $enableLogging = $this->Request()->getParam('enableLogging');
103
            $this->getConfigComponent()->setConfig('logRequest', $enableLogging, null, 'general');
104
105
            $this->View()->assign([
106
                'success' => true
107
            ]);
108
        } catch (\Exception $e) {
109
            $this->View()->assign([
110
                'success' => false,
111
            ]);
112
        }
113
    }
114
115
    public function getLoggingEnabledAction()
116
    {
117
        $this->View()->assign([
118
            'success' => true,
119
            'enableLogging' => $this->getConfigComponent()->getConfig('logRequest', 0),
120
        ]);
121
    }
122
123
    /**
124
     * The getImportAction function is an ExtJs event listener method of the
125
     * connect module. The function is used to load store
126
     * required in the import config form.
127
     * @return string
128
     */
129
    public function getImportAction()
130
    {
131
        $importConfigArray = $this->getConfigComponent()->getImportConfig();
132
133
        $this->View()->assign(
134
            [
135
                'success' => true,
136
                'data' => $importConfigArray
137
            ]
138
        );
139
    }
140
141
    /**
142
     * The saveImportAction function is an ExtJs event listener method of the
143
     * connect module. The function is used to save store data.
144
     * @return string
145
     */
146
    public function saveImportAction()
147
    {
148
        $data = $this->Request()->getParam('data');
149
        $data = !isset($data[0]) ? [$data] : $data;
150
151
        $this->getConfigComponent()->setImportConfigs($data);
152
153
        $this->View()->assign(
154
            [
155
                'success' => true
156
            ]
157
        );
158
    }
159
160
    /**
161
     * The getExportAction function is an ExtJs event listener method of the
162
     * connect module. The function is used to load store
163
     * required in the export config form.
164
     * @return string
165
     */
166
    public function getExportAction()
167
    {
168
        $exportConfigArray = $this->getConfigComponent()->getExportConfig();
169
        if (!array_key_exists('exportPriceMode', $exportConfigArray) || $this->isPriceTypeReset()) {
170
            $exportConfigArray['exportPriceMode'] = [];
171
        }
172
173
174
        //Resets the exportPriceMode
175
        if ($this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_NONE) {
176
            $exportConfigArray['exportPriceMode'] = [];
177
        }
178
179
        if (!array_key_exists(BaseProductQuery::LONG_DESCRIPTION_FIELD, $exportConfigArray)) {
180
            $exportConfigArray[BaseProductQuery::LONG_DESCRIPTION_FIELD] = true;
181
        }
182
183
        $this->View()->assign(
184
            [
185
                'success' => true,
186
                'data' => $exportConfigArray
187
            ]
188
        );
189
    }
190
191
    /**
192
     * @return bool
193
     */
194
    public function isPriceTypeReset()
195
    {
196
        return $this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_NONE;
197
    }
198
199
    /**
200
     * ExtJS uses this action to check is price mapping allowed.
201
     * If there is at least one exported product to connect,
202
     * price mapping cannot be changed.
203
     */
204
    public function isPricingMappingAllowedAction()
205
    {
206
        $isPriceModeEnabled = false;
207
        $isPurchasePriceModeEnabled = false;
208
        $isPricingMappingAllowed = $this->isPriceTypeReset();
209
210
        if ($isPricingMappingAllowed) {
211
            $this->View()->assign(
212
                [
213
                    'success' => true,
214
                    'isPricingMappingAllowed' => $isPricingMappingAllowed,
215
                    'isPriceModeEnabled' => true,
216
                    'isPurchasePriceModeEnabled' => true,
217
                ]
218
            );
219
220
            return;
221
        }
222
223
        if ($this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_BOTH
224
        || $this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_RETAIL) {
225
            $isPriceModeEnabled = true;
226
        }
227
228
        if ($this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_BOTH
229
        || $this->getSDK()->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_PURCHASE) {
230
            $isPurchasePriceModeEnabled = true;
231
        }
232
233
        $this->View()->assign(
234
            [
235
                'success' => true,
236
                'isPricingMappingAllowed' => $isPricingMappingAllowed,
237
                'isPriceModeEnabled' => $isPriceModeEnabled,
238
                'isPurchasePriceModeEnabled' => $isPurchasePriceModeEnabled,
239
            ]
240
        );
241
    }
242
243
    /**
244
     * The saveExportAction function is an ExtJs event listener method of the
245
     * connect module. The function is used to save store data.
246
     * @return string
247
     */
248
    public function saveExportAction()
249
    {
250
        $data = $this->Request()->getParam('data');
251
        $exportPrice = in_array('price', $data['exportPriceMode']);
252
        $exportPurchasePrice = in_array('purchasePrice', $data['exportPriceMode']);
253
254
        $isModified = $this->getConfigComponent()->compareExportConfiguration($data);
255
        $isPriceTypeReset = $this->isPriceTypeReset();
256
257
        if ($isModified === false && $this->getSDK()->getPriceType() !== \Shopware\Connect\SDK::PRICE_TYPE_NONE) {
258
            $data = !isset($data[0]) ? [$data] : $data;
259
            $this->getConfigComponent()->setExportConfigs($data);
260
            $this->View()->assign(
261
                [
262
                    'success' => true,
263
                ]
264
            );
265
266
            return;
267
        }
268
269
        if ($exportPrice && $exportPurchasePrice) {
270
            $priceType = \Shopware\Connect\SDK::PRICE_TYPE_BOTH;
271
        } elseif ($exportPrice) {
272
            $priceType = \Shopware\Connect\SDK::PRICE_TYPE_RETAIL;
273
            unset($data['priceFieldForPurchasePriceExport']);
274
            unset($data['priceGroupForPurchasePriceExport']);
275
        } elseif ($exportPurchasePrice) {
276
            $priceType = \Shopware\Connect\SDK::PRICE_TYPE_PURCHASE;
277
            unset($data['priceFieldForPriceExport']);
278
            unset($data['priceGroupForPriceExport']);
279
        } else {
280
            $this->View()->assign([
281
                'success' => false,
282
                'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
283
                    'config/export/priceFieldIsNotSupported',
284
                    'Price field is not maintained. Some of the products have price = 0',
285
                    true
286
                )
287
            ]);
288
289
            return;
290
        }
291
292
        if ($priceType == \Shopware\Connect\SDK::PRICE_TYPE_BOTH
293
            && $data['priceFieldForPurchasePriceExport'] == $data['priceFieldForPriceExport']
294
            && $data['priceGroupForPurchasePriceExport'] == $data['priceGroupForPriceExport']
295
        ) {
296
            $this->View()->assign([
297
                'success' => false,
298
                'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
299
                    'config/export/error/same_price_fields',
300
                    'Endkunden-VK und Listenverkaufspreis müssen an verschiedene Felder angeschlossen sein',
301
                    true
302
                )
303
            ]);
304
305
            return;
306
        }
307
308
        $detailPurchasePrice = method_exists('Shopware\Models\Article\Detail', 'setPurchasePrice');
309
        if ($exportPurchasePrice && $detailPurchasePrice) {
310
            $data['priceFieldForPurchasePriceExport'] = 'detailPurchasePrice';
311
        }
312
313 View Code Duplication
        if ($priceType == \Shopware\Connect\SDK::PRICE_TYPE_BOTH
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
314
            || $priceType == \Shopware\Connect\SDK::PRICE_TYPE_RETAIL
315
        ) {
316
            /** @var \Shopware\Models\Customer\Group $groupPrice */
317
            $groupPrice = $this->getCustomerGroupRepository()->findOneBy(['key' => $data['priceGroupForPriceExport']]);
318
            if (!$groupPrice) {
319
                $this->View()->assign([
320
                    'success' => false,
321
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
322
                        'config/export/invalid_customer_group',
323
                        'Ungültige Kundengruppe',
324
                        true
325
                    )
326
                ]);
327
328
                return;
329
            }
330
331
            if ($this->getPriceGateway()->countProductsWithConfiguredPrice($groupPrice, $data['priceFieldForPriceExport']) === 0) {
332
                $this->View()->assign([
333
                    'success' => false,
334
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
335
                        'config/export/priceFieldIsNotSupported',
336
                        'Price field is not maintained. Some of the products have price = 0',
337
                        true
338
                    )
339
                ]);
340
341
                return;
342
            }
343
        }
344
345 View Code Duplication
        if ($priceType == \Shopware\Connect\SDK::PRICE_TYPE_BOTH
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
346
            || $priceType == \Shopware\Connect\SDK::PRICE_TYPE_PURCHASE
347
        ) {
348
            /** @var \Shopware\Models\Customer\Group $groupPurchasePrice */
349
            $groupPurchasePrice = $this->getCustomerGroupRepository()->findOneBy([
350
                'key' => $data['priceGroupForPurchasePriceExport']
351
            ]);
352
            if (!$groupPurchasePrice && !$detailPurchasePrice) {
353
                $this->View()->assign([
354
                    'success' => false,
355
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
356
                        'config/export/invalid_customer_group',
357
                        'Ungültige Kundengruppe',
358
                        true
359
                    )
360
                ]);
361
362
                return;
363
            }
364
365
            if ($this->getPriceGateway()->countProductsWithConfiguredPrice($groupPurchasePrice, $data['priceFieldForPurchasePriceExport']) === 0) {
366
                $this->View()->assign([
367
                    'success' => false,
368
                    'message' => Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
369
                        'config/export/priceFieldIsNotSupported',
370
                        'Price field is not maintained. Some of the products have price = 0',
371
                        true
372
                    )
373
                ]);
374
375
                return;
376
            }
377
        }
378
379
        $connectExport = $this->getConnectExport();
380
381
        if ($isPriceTypeReset) {
382
            //removes all hashes from from sw_connect_product
383
            //and resets all item status
384
            $connectExport->clearConnectItems();
385
        }
386
387
        try {
388
            $data = !isset($data[0]) ? [$data] : $data;
389
            $response = $this->getSnHttpClient()->sendRequestToConnect(
390
                'account/settings',
391
                ['priceType' => $priceType]
392
            );
393
394
            $responseBody = json_decode($response->getBody());
395
            if (!$responseBody->success) {
396
                throw new \RuntimeException($responseBody->message);
397
            }
398
399
            $this->getSDK()->verifySdk();
400
            $this->getConfigComponent()->setExportConfigs($data);
401
402
            //todo@sb: check this. Not possible to export all products at the same request.
403
            $ids = $connectExport->getExportArticlesIds();
404
            $sourceIds = $this->getHelper()->getArticleSourceIds($ids);
405
            $errors = $connectExport->export($sourceIds);
406
        } catch (\RuntimeException $e) {
407
            $this->getLogger()->write(true, 'Save export settings', $e->getMessage() . $e->getTraceAsString());
408
            $this->View()->assign([
409
                    'success' => false,
410
                    'message' => $e->getMessage()
411
                ]);
412
413
            return;
414
        }
415
416
        if (!empty($errors)) {
417
            $msg = null;
418
            foreach ($errors as $type) {
419
                $msg .= implode("<br>\n", $type);
420
            }
421
422
            $this->View()->assign([
423
                    'success' => false,
424
                    'message' => $msg
425
                ]);
426
427
            return;
428
        }
429
430
        $this->View()->assign(
431
            [
432
                'success' => true
433
            ]
434
        );
435
    }
436
437
    /**
438
     * @return ConnectExport
439
     */
440
    public function getConnectExport()
441
    {
442
        return new ConnectExport(
443
            $this->getHelper(),
444
            $this->getSDK(),
445
            $this->getModelManager(),
446
            new ProductsAttributesValidator(),
447
            $this->getConfigComponent(),
448
            new ErrorHandler(),
449
            $this->container->get('events')
450
        );
451
    }
452
453
    /**
454
     * It will make a call to SocialNetwork to reset the price type,
455
     * if this call return success true, then it will reset the export settings locally
456
     *
457
     * @return void
458
     */
459
    public function resetPriceTypeAction()
460
    {
461
        $response = $this->getSnHttpClient()->sendRequestToConnect('account/reset/price-type');
462
        $responseBody = json_decode($response->getBody());
463
464 View Code Duplication
        if (!$responseBody->success) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
465
            $this->View()->assign([
466
                'success' => false,
467
                'message' => $responseBody->message
468
            ]);
469
470
            return;
471
        }
472
473
        try {
474
            $this->resetExportedProducts();
475
        } catch (\Exception $e) {
476
            $this->View()->assign([
477
                'success' => false,
478
                'message' => $responseBody->message
479
            ]);
480
481
            return;
482
        }
483
484
        $this->View()->assign([
485
            'success' => true,
486
        ]);
487
    }
488
489
    /**
490
     * It will make a call to SocialNetwork to reset the exchange settings,
491
     * if this call return success true, then it will reset the export settings locally
492
     *
493
     * @return void
494
     */
495
    public function resetExchangeSettingsAction()
496
    {
497
        $response = $this->getSnHttpClient()->sendRequestToConnect('account/reset/exchange-settings');
498
499
        $responseBody = json_decode($response->getBody());
500
501 View Code Duplication
        if (!$responseBody->success) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
502
            $this->View()->assign([
503
                'success' => false,
504
                'message' => $responseBody->message
505
            ]);
506
507
            return;
508
        }
509
510
        try {
511
            $this->resetExportedProducts();
512
513
            //remove the existing api key
514
            $this->getConfigComponent()->setGeneralConfigs(['apiKey' => '']);
515
516
            //recreate the register menu
517
            $this->get('swagconnect.menu_service')->createRegisterMenu();
518
        } catch (\Exception $e) {
519
            $this->View()->assign([
520
                'success' => false,
521
                'message' => $responseBody->message
522
            ]);
523
524
            return;
525
        }
526
527
        $this->View()->assign([
528
            'success' => true,
529
        ]);
530
    }
531
532
    /**
533
     * WARNING This code remove the current product changes
534
     * This is a single call operation and its danger one
535
     */
536
    private function resetExportedProducts()
537
    {
538
        $builder = $this->getModelManager()->getConnection()->createQueryBuilder();
539
        $builder->delete('sw_connect_change')
540
            ->where('c_operation IN (:changes)')
541
            ->setParameter(
542
                'changes',
543
                [
544
                    ChangeGateway::PRODUCT_INSERT,
545
                    ChangeGateway::PRODUCT_UPDATE,
546
                    ChangeGateway::PRODUCT_DELETE,
547
                    ChangeGateway::PRODUCT_STOCK,
548
                ],
549
                \Doctrine\DBAL\Connection::PARAM_STR_ARRAY
550
            );
551
        $builder->execute();
552
553
        $itemRepo = $this->getModelManager()->getRepository('Shopware\CustomModels\Connect\Attribute');
554
        $itemRepo->resetExportedItemsStatus();
555
556
        $streamRepo = $this->getModelManager()->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
557
        $streamRepo->resetExportedStatus();
558
    }
559
560
    /**
561
     * @return \ShopwarePlugins\Connect\Components\Helper
562
     */
563
    public function getHelper()
564
    {
565
        if ($this->factory === null) {
566
            $this->factory = new \ShopwarePlugins\Connect\Components\ConnectFactory();
567
        }
568
569
        return $this->factory->getHelper();
570
    }
571
572
    /**
573
     * @return \Shopware\Connect\SDK
574
     */
575
    public function getSDK()
576
    {
577
        return Shopware()->Container()->get('ConnectSDK');
578
    }
579
580
    /**
581
     * @return Shopware\Components\Model\ModelManager
582
     */
583
    public function getModelManager()
584
    {
585
        return Shopware()->Models();
586
    }
587
588
    /**
589
     * The getStaticPagesAction function is an ExtJs event listener method of the
590
     * connect module. The function is used to load store
591
     * required in the general config form for static cms pages combo.
592
     * @return string
593
     */
594
    public function getStaticPagesAction()
595
    {
596
        $builder = $this->getModelManager()->createQueryBuilder();
597
        $builder->select('st.id, st.description AS name');
598
        $builder->from('Shopware\Models\Site\Site', 'st');
599
600
        $query = $builder->getQuery();
601
        $query->setFirstResult($this->Request()->getParam('start'));
602
        $query->setMaxResults($this->Request()->getParam('limit'));
603
604
        $total = Shopware()->Models()->getQueryCount($query);
605
        $data = $query->getArrayResult();
606
607
        $this->View()->assign([
608
                'success' => true,
609
                'data' => $data,
610
                'total' => $total
611
            ]);
612
    }
613
614
    /**
615
     * Helper function to get access on the Config component
616
     *
617
     * @return \ShopwarePlugins\Connect\Components\Config
618
     */
619
    private function getConfigComponent()
620
    {
621
        if ($this->configComponent === null) {
622
            $this->configComponent = ConfigFactory::getConfigInstance();
623
        }
624
625
        return $this->configComponent;
626
    }
627
628
    /**
629
     * The getUnitsAction function is an ExtJs event listener method of the
630
     * connect module. The function is used to load store
631
     * required in the units mapping.
632
     * @return string
633
     */
634
    public function getUnitsAction()
635
    {
636
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Article\Unit');
637
        $units = $repository->findAll();
638
639
        $unitName = Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
640
            'import/unit/take_over_units',
641
            'Take over unit',
642
            true
643
        );
644
645
        $unitsMappingArray[] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$unitsMappingArray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $unitsMappingArray = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
646
            'shopwareUnitName' => $unitName,
647
            'shopwareUnitKey' => UnitMapper::ADOPT_UNIT_KEY,
648
        ];
649
650
        foreach ($units as $unit) {
651
            $unitsMappingArray[] = [
652
                'shopwareUnitName' => $unit->getName(),
653
                'shopwareUnitKey' => $unit->getUnit()
654
            ];
655
        }
656
657
        $this->View()->assign(
658
            [
659
                'success' => true,
660
                'data' => $unitsMappingArray
661
            ]
662
        );
663
    }
664
665
    /**
666
     * The saveUnitsMappingAction function is an ExtJs event listener method of the
667
     * connect module. The function is used to save units store data.
668
     * @return string
669
     */
670
    public function saveUnitsMappingAction()
671
    {
672
        $data = $this->Request()->getParam('data');
673
        $data = !isset($data[0]) ? [$data] : $data;
674
675
        //prepares units for adoption
676
        $adoptUnitKeys = [];
677
        foreach ($data as $index => $unit) {
678
            if ($unit['shopwareUnitKey'] == UnitMapper::ADOPT_UNIT_KEY) {
679
                $adoptUnitKeys[] = $unit['connectUnit'];
680
                $data[$index]['shopwareUnitKey'] = $unit['connectUnit'];
681
            }
682
        }
683
684
        if (!empty($adoptUnitKeys)) {
685
            $this->getUnitMapper()->createUnits($adoptUnitKeys);
686
        }
687
688
        $this->getConfigComponent()->setUnitsMapping($data);
689
690
        // update related products
691
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Article\Unit');
692
        foreach ($data as $unit) {
693
            /** @var \Shopware\Models\Article\Unit $unitModel */
694
            $unitModel = $repository->findOneBy(['unit' => $unit['shopwareUnitKey']]);
695
            if (!$unitModel) {
696
                continue;
697
            }
698
            $this->getHelper()->updateUnitInRelatedProducts($unitModel, $unit['connectUnit']);
699
        }
700
701
        $this->View()->assign(
702
            [
703
                'success' => true
704
            ]
705
        );
706
    }
707
708
    /**
709
     * The getConnectUnitsAction function is an ExtJs event listener method of the
710
     * connect module. The function is used to load store
711
     * required in the units mapping.
712
     * @return string
713
     */
714
    public function getConnectUnitsAction()
715
    {
716
        $connectUnits = new Units();
717
        $connectUnitsArray = $connectUnits->getLocalizedUnits('de');
718
        $unitsArray = [];
719
        $hideAssigned = (int) $this->Request()->getParam('hideAssignedUnits', 1);
720
721
        foreach ($this->getConfigComponent()->getUnitsMappings() as $connectUnit => $localUnit) {
722
            if ($hideAssigned == true && strlen($localUnit) > 0) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $hideAssigned of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
723
                continue;
724
            }
725
            $unitsArray[] = [
726
                'connectUnit' => $connectUnit,
727
                'name' => $connectUnitsArray[$connectUnit],
728
                'shopwareUnitKey' => $localUnit
729
            ];
730
        }
731
732
        $this->View()->assign(
733
            [
734
                'success' => true,
735
                'data' => $unitsArray
736
            ]
737
        );
738
    }
739
740
    /**
741
     * Ask SocialNetwork what time is need to finish the product update
742
     */
743
    public function calculateFinishTimeAction()
744
    {
745
        $changes = $this->getConnectExport()->getChangesCount();
746
        $seconds = 0;
747
        if ($changes > 0) {
748
            $seconds = $this->getSDK()->calculateFinishTime($changes);
749
        }
750
751
        try {
752
            $this->View()->assign(
753
                [
754
                    'success' => true,
755
                    'time' => $seconds,
756
                ]
757
            );
758
        } catch (\Exception $e) {
759
            $this->View()->assign(
760
                [
761
                    'success' => false,
762
                    'message' => $e->getMessage(),
763
                ]
764
            );
765
        }
766
    }
767
768
    public function getMarketplaceAttributesAction()
769
    {
770
        try {
771
            $verified = $this->getConfigComponent()->getConfig('apiKeyVerified', false);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $verified is correct as $this->getConfigComponen...apiKeyVerified', false) (which targets ShopwarePlugins\Connect\...nts\Config::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
772
773
            if ($verified) {
774
                $marketplaceAttributes = $this->getSDK()->getMarketplaceProductAttributes();
775
776
                $attributes = [];
777
                foreach ($marketplaceAttributes as $attributeKey => $attributeLabel) {
778
                    $attributes[] = [
779
                        'attributeKey' => $attributeKey,
780
                        'attributeLabel' => $attributeLabel,
781
                        'shopwareAttributeKey' => ''
782
                    ];
783
                }
784
            } else {
785
                $attributes = [];
786
            }
787
        } catch (\Exception $e) {
788
            // ignore this exception because sometimes
789
            // connect plugin is not configured and tries to
790
            // read marketplace attributes
791
            $attributes = [];
792
        }
793
794
        $this->View()->assign(
795
            [
796
                'success' => true,
797
                'data' => $attributes
798
            ]
799
        );
800
    }
801
802
    public function saveProductAttributesMappingAction()
803
    {
804
        try {
805
            $data = $this->Request()->getParam('data');
806
            $data = !isset($data[0]) ? [$data] : $data;
807
            $marketplaceGateway = $this->getFactory()->getMarketplaceGateway();
808
            $marketplaceGateway->setMarketplaceMapping($data);
809
810
            $this->View()->assign(['success' => true]);
811
        } catch (\Exception $e) {
812
            $this->View()->assign(
813
                [
814
                    'success' => false,
815
                    'message' => $e->getMessage()
816
                ]
817
            );
818
        }
819
    }
820
821
    public function getProductAttributesMappingAction()
822
    {
823
        $marketplaceGateway = $this->getFactory()->getMarketplaceGateway();
824
825
        $mappings = array_map(function ($attribute) use ($marketplaceGateway) {
826
            return [
827
                    'shopwareAttributeKey' => $attribute->getName(),
828
                    'shopwareAttributeLabel' => $attribute->getLabel(),
829
                    'attributeKey' => $marketplaceGateway->findMarketplaceMappingFor($attribute->getName()),
830
                ];
831
        }, array_values(
832
                array_filter(
833
                    Shopware()->Models()->getRepository('Shopware\Models\Article\Element')->findAll(),
834
                    function ($attribute) {
835
                        return $attribute->getName() != 'connectProductDescription';
836
                    }
837
                )
838
            )
839
        );
840
841
        $this->View()->assign(
842
            [
843
                'success' => true,
844
                'data' => $mappings
845
            ]
846
        );
847
    }
848
849
    /**
850
     * Loads all customer groups
851
     *
852
     * @throws Zend_Db_Statement_Exception
853
     */
854
    public function getExportCustomerGroupsAction()
855
    {
856
        $builder = $this->getCustomerGroupRepository()->createQueryBuilder('groups');
857
        $builder->select([
858
            'groups.id as id',
859
            'groups.key as key',
860
            'groups.name as name',
861
            'groups.tax as tax',
862
            'groups.taxInput as taxInput',
863
            'groups.mode as mode'
864
        ]);
865
866
        $query = $builder->getQuery();
867
868
        //get total result of the query
869
        $total = Shopware()->Models()->getQueryCount($query);
870
871
        $data = $query->getArrayResult();
872
873
        //return the data and total count
874
        $this->View()->assign(
875
            [
876
                'success' => true,
877
                'data' => $data,
878
                'total' => $total,
879
            ]
880
        );
881
    }
882
883
    /**
884
     * Loads all price groups where at least
885
     * one product with price greater than 0 exists
886
     *
887
     * @throws Zend_Db_Statement_Exception
888
     */
889
    public function getExportPriceGroupsAction()
890
    {
891
        $groups = [];
892
893
        $customerGroupKey = $this->Request()->getParam('customerGroup', 'EK');
894
        $priceExportMode = $this->Request()->getParam('priceExportMode');
895
        /** @var \Shopware\Models\Customer\Group $customerGroup */
896
        $customerGroup = $this->getCustomerGroupRepository()->findOneBy(['key' => $customerGroupKey]);
897
        if (!$customerGroup) {
898
            $this->View()->assign(
899
                [
900
                    'success' => true,
901
                    'data' => $groups,
902
                    'total' => count($groups),
903
                ]
904
            );
905
906
            return;
907
        }
908
909
        $exportConfigArray = $this->getConfigComponent()->getExportConfig();
910
911
        if (array_key_exists('exportPriceMode', $exportConfigArray)
912
            && count($exportConfigArray['exportPriceMode']) > 0
913
            && $this->getSDK()->getPriceType() != \Shopware\Connect\SDK::PRICE_TYPE_NONE
914
        ) {
915
            $groups[] = $this->getConfigComponent()->collectExportPrice($priceExportMode, $customerGroupKey);
916
        } else {
917
            $productCount = $this->getPriceGateway()->countProducts($customerGroup);
918
            $priceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'price');
919
            $basePriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'baseprice');
920
            $pseudoPriceConfiguredProducts = $this->getPriceGateway()->countProductsWithConfiguredPrice($customerGroup, 'pseudoprice');
921
922
            $groups[] = [
923
                'price' => false,
924
                'priceAvailable' => $priceConfiguredProducts > 0,
925
                'priceConfiguredProducts' => $priceConfiguredProducts,
926
                'basePrice' => false,
927
                'basePriceAvailable' => $basePriceConfiguredProducts > 0,
928
                'basePriceConfiguredProducts' => $basePriceConfiguredProducts,
929
                'pseudoPrice' => false,
930
                'pseudoPriceAvailable' => $pseudoPriceConfiguredProducts > 0,
931
                'pseudoPriceConfiguredProducts' => $pseudoPriceConfiguredProducts,
932
                'productCount' => $productCount
933
            ];
934
        }
935
936
        $this->View()->assign(
937
            [
938
                'success' => true,
939
                'data' => $groups,
940
                'total' => count($groups),
941
            ]
942
        );
943
    }
944
945
    public function adoptUnitsAction()
946
    {
947
        $connection = $this->getModelManager()->getConnection();
948
        $connection->beginTransaction();
949
950
        try {
951
            $units = array_filter($this->getConfigComponent()->getUnitsMappings(), function ($unit) {
952
                return strlen($unit) == 0;
953
            });
954
955
            $models = $this->getUnitMapper()->createUnits(array_keys($units));
956
            foreach ($models as $unit) {
957
                $this->getHelper()->updateUnitInRelatedProducts($unit, $unit->getUnit());
958
            }
959
            $connection->commit();
960
        } catch (\Exception $e) {
961
            $connection->rollBack();
962
            $this->getLogger()->write(true, $e->getMessage(), $e);
963
            $this->View()->assign(
964
                [
965
                    'success' => false,
966
                ]
967
            );
968
969
            return;
970
        }
971
972
        $this->View()->assign(
973
            [
974
                'success' => true,
975
            ]
976
        );
977
    }
978
979
    public function checkCronPluginAction()
980
    {
981
        $pluginRepo = $this->getModelManager()->getRepository(Plugin::class);
982
        $cronPlugin = $pluginRepo->findOneBy(['name' => 'Cron']);
983
984
        $this->View()->assign(
985
            [
986
                'cronActivated' => (bool) $cronPlugin->getActive()
987
            ]
988
        );
989
    }
990
991
    /**
992
     * @return \ShopwarePlugins\Connect\Components\ConnectFactory
993
     */
994
    public function getFactory()
995
    {
996
        if ($this->factory === null) {
997
            $this->factory = new \ShopwarePlugins\Connect\Components\ConnectFactory();
998
        }
999
1000
        return $this->factory;
1001
    }
1002
1003
    /**
1004
     * @return UnitMapper
1005
     */
1006
    private function getUnitMapper()
1007
    {
1008
        if (!$this->unitMapper) {
1009
            $this->unitMapper = new UnitMapper(
1010
                $this->getConfigComponent(),
1011
                $this->getModelManager()
1012
            );
1013
        }
1014
1015
        return $this->unitMapper;
1016
    }
1017
1018
    /**
1019
     * @return Logger
1020
     */
1021
    private function getLogger()
1022
    {
1023
        if (!$this->logger) {
1024
            $this->logger = new Logger(Shopware()->Db());
1025
        }
1026
1027
        return $this->logger;
1028
    }
1029
1030
    /**
1031
     * @return \Shopware\Components\Model\ModelRepository
1032
     */
1033
    private function getCustomerGroupRepository()
1034
    {
1035
        if (!$this->customerGroupRepository) {
1036
            $this->customerGroupRepository = Shopware()->Models()->getRepository('Shopware\Models\Customer\Group');
1037
        }
1038
1039
        return $this->customerGroupRepository;
1040
    }
1041
1042
    private function getPriceGateway()
1043
    {
1044
        if (!$this->priceGateway) {
1045
            $this->priceGateway = new \ShopwarePlugins\Connect\Components\PriceGateway(
1046
                Shopware()->Db()
1047
            );
1048
        }
1049
1050
        return $this->priceGateway;
1051
    }
1052
1053 View Code Duplication
    private function getSnHttpClient()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1054
    {
1055
        if (!$this->snHttpClient) {
1056
            $this->snHttpClient = new SnHttpClient(
1057
                $this->get('http_client'),
1058
                new \Shopware\Connect\Gateway\PDO(Shopware()->Db()->getConnection()),
1059
                $this->getConfigComponent()
1060
            );
1061
        }
1062
1063
        return $this->snHttpClient;
1064
    }
1065
}
1066