Completed
Pull Request — master (#421)
by Christian
03:14
created

Setup::run()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 13
nc 2
nop 2
dl 0
loc 17
rs 9.4285
c 0
b 0
f 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
namespace ShopwarePlugins\Connect\Bootstrap;
9
10
use Shopware\Bundle\AttributeBundle\Service\CrudService;
11
use Shopware\Models\Attribute\Configuration;
12
use Shopware\Models\Customer\Group;
13
use Shopware\Components\Model\ModelManager;
14
use Enlight_Components_Db_Adapter_Pdo_Mysql as Pdo;
15
use ShopwarePlugins\Connect\Components\Config;
16
use Shopware\Models\Order\Status;
17
use ShopwarePlugins\Connect\Components\ConfigFactory;
18
use ShopwarePlugins\Connect\Components\ConnectFactory;
19
use ShopwarePlugins\Connect\Components\Utils\ConnectOrderUtil;
20
21
/**
22
 * The setup class does the basic setup of the shopware Connect plugin. All operations should be implemented in a way
23
 * that they can also be run on update of the plugin
24
 *
25
 * Class Setup
26
 * @package ShopwarePlugins\Connect\Bootstrap
27
 */
28
class Setup
29
{
30
    /**
31
     * @var Pdo
32
     */
33
    protected $db;
34
35
    /**
36
     * @var ModelManager
37
     */
38
    protected $modelManager;
39
40
    private $menu;
41
42
    /**
43
     * Setup constructor.
44
     * @param ModelManager $modelManager
45
     * @param Pdo $db
46
     * @param Menu
47
     */
48
    public function __construct(
49
        ModelManager $modelManager,
50
        Pdo $db,
51
        Menu $menu
52
53
    ) {
54
        $this->modelManager = $modelManager;
55
        $this->db = $db;
56
        $this->menu = $menu;
57
    }
58
59
    public function run($fullSetup, $pluginPath)
60
    {
61
        $this->createMyTables();
62
        $this->createMyAttributes();
63
        $this->populateConfigTable();
64
        $this->importSnippets($pluginPath);
65
        $this->generateConnectPaymentAttribute();
66
        $this->populateDispatchAttributes();
67
        $this->populateConnectPaymentAttribute();
68
        $this->createConnectCustomerGroup();
69
70
        if ($fullSetup) {
71
            $this->createMyMenu();
72
            $this->populatePaymentStates();
73
            $this->populateOrderStates();
74
        }
75
    }
76
77
    /**
78
     * Creates the plugin menu item
79
     */
80
    private function createMyMenu()
81
    {
82
        $this->menu->synchronize();
83
84
        $sql = "INSERT IGNORE INTO `s_core_snippets` (`namespace`, `shopID`, `localeID`, `name`, `value`, `created`, `updated`) VALUES
85
            ('backend/index/view/main', 1, 1, 'Connect', 'Connect', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
86
            ('backend/index/view/main', 1, 2, 'Connect', 'Connect', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
87
            ('backend/index/view/main', 1, 1, 'Connect/Export', 'Produkte zu Connect', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
88
            ('backend/index/view/main', 1, 2, 'Connect/Export', 'Export', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
89
            ('backend/index/view/main', 1, 1, 'Connect/Settings', 'Einstellungen', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
90
            ('backend/index/view/main', 1, 2, 'Connect/Settings', 'Settings', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
91
            ('backend/index/view/main', 1, 1, 'Connect/Register', 'Einrichtung', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
92
            ('backend/index/view/main', 1, 2, 'Connect/Register', 'Register', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
93
            ('backend/index/view/main', 1, 1, 'Connect/Import', 'Produkte von Connect', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
94
            ('backend/index/view/main', 1, 2, 'Connect/Import', 'Import', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
95
            ('backend/index/view/main', 1, 1, 'Connect/OpenConnect', 'Login', '2016-03-17 18:32:48', '2016-03-17 18:32:48'),
96
            ('backend/index/view/main', 1, 2, 'Connect/OpenConnect', 'Login', '2016-03-17 18:32:48', '2016-03-17 18:32:48')
97
98
            ON DUPLICATE KEY UPDATE
99
              `namespace` = VALUES(`namespace`),
100
              `shopID` = VALUES(`shopID`),
101
              `name` = VALUES(`name`),
102
              `localeID` = VALUES(`localeID`),
103
              `value` = VALUES(`value`)
104
              ;";
105
        $this->db->exec($sql);
106
    }
107
108
    /**
109
     * Create necessary tables
110
     */
111
    private function createMyTables()
112
    {
113
        $queries = ['
114
            CREATE TABLE IF NOT EXISTS `sw_connect_change` (
115
              `c_entity_id` varchar(64) NOT NULL,
116
              `c_operation` char(8) NOT NULL,
117
              `c_revision` decimal(20,10) NOT NULL,
118
              `c_payload` longblob,
119
              `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
120
              UNIQUE KEY `c_revision` (`c_revision`),
121
              KEY `c_entity_id` (`c_entity_id`),
122
              INDEX `c_operation` (`c_operation`)
123
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
124
           CREATE TABLE IF NOT EXISTS `sw_connect_data` (
125
              `d_key` varchar(32) NOT NULL,
126
              `d_value` varchar(256) NOT NULL,
127
              `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
128
              PRIMARY KEY (`d_key`)
129
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
130
            CREATE TABLE IF NOT EXISTS `sw_connect_product` (
131
              `p_source_id` varchar(64) NOT NULL,
132
              `p_hash` varchar(64) NOT NULL,
133
              `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
134
              PRIMARY KEY (`p_source_id`)
135
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
136
            CREATE TABLE IF NOT EXISTS `sw_connect_reservations` (
137
              `r_id` varchar(32) NOT NULL,
138
              `r_state` varchar(12) NOT NULL,
139
              `r_order` longblob NOT NULL,
140
              `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
141
              PRIMARY KEY (`r_id`)
142
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
143
            CREATE TABLE IF NOT EXISTS `sw_connect_shop_config` (
144
              `s_shop` varchar(32) NOT NULL,
145
              `s_config` LONGBLOB NOT NULL,
146
              `changed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
147
              PRIMARY KEY (`s_shop`)
148
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
149
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_config` (
150
              `id` int(11) NOT NULL AUTO_INCREMENT,
151
              `name` varchar(255) NOT NULL,
152
              `value` TEXT NOT NULL,
153
              `shopId` int(11) NULL,
154
              `groupName` varchar(255) NULL,
155
              PRIMARY KEY (`id`)
156
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
157
            CREATE TABLE IF NOT EXISTS `sw_connect_shipping_costs` (
158
              `sc_from_shop` VARCHAR(32) NOT NULL,
159
              `sc_to_shop` VARCHAR(32) NOT NULL,
160
              `sc_revision` VARCHAR(32) NOT NULL,
161
              `sc_shipping_costs` LONGBLOB NOT NULL,
162
              `sc_customer_costs` LONGBLOB NOT NULL,
163
              `changed` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
164
              PRIMARY KEY (`sc_from_shop`, `sc_to_shop`),
165
              INDEX (`sc_revision`)
166
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
167
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_log` (
168
              `id` int(11) NOT NULL AUTO_INCREMENT,
169
              `isError` int(1) NOT NULL,
170
              `service` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
171
              `command` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
172
              `request` text COLLATE utf8_unicode_ci DEFAULT NULL,
173
              `response` text COLLATE utf8_unicode_ci DEFAULT NULL,
174
              `time` datetime NOT NULL,
175
              PRIMARY KEY (`id`)
176
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', '
177
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_marketplace_attr` (
178
              `id` int(11) NOT NULL AUTO_INCREMENT,
179
              `marketplace_attribute` varchar(255) NOT NULL UNIQUE,
180
              `local_attribute` varchar(255) NOT NULL UNIQUE,
181
              PRIMARY KEY (`id`)
182
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', "
183
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_items` (
184
             `id` int(11) NOT NULL AUTO_INCREMENT,
185
             `article_id` int(11) unsigned DEFAULT NULL,
186
             `article_detail_id` int(11) unsigned DEFAULT NULL,
187
             `shop_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
188
             `source_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
189
             `export_status` varchar(255) COLLATE utf8_unicode_ci,
190
             `export_message` text COLLATE utf8_unicode_ci,
191
             `exported` TINYINT(1) DEFAULT 0,
192
             `category` text COLLATE utf8_unicode_ci,
193
             `purchase_price` double DEFAULT NULL,
194
             `fixed_price` int(1) DEFAULT NULL,
195
             `free_delivery` int(1) DEFAULT NULL,
196
             `update_price` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'inherit',
197
             `update_image` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'inherit',
198
             `update_main_image` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'inherit',
199
             `update_long_description` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'inherit',
200
             `update_short_description` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'inherit',
201
             `update_additional_description` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'inherit',
202
             `update_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'inherit',
203
             `last_update` longtext COLLATE utf8_unicode_ci,
204
             `last_update_flag` int(11) DEFAULT NULL,
205
             `group_id` VARCHAR (64) NULL DEFAULT NULL,
206
             `is_main_variant` TINYINT(1) NULL DEFAULT NULL,
207
             `purchase_price_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
208
             `offer_valid_until` int(10) NOT NULL,
209
             `stream` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
210
             `cron_update` TINYINT(1) NULL DEFAULT NULL,
211
             `revision` decimal(20,10) DEFAULT NULL,
212
             PRIMARY KEY (`id`),
213
             UNIQUE KEY `article_detail_id` (`article_detail_id`),
214
             KEY `article_id` (`article_id`),
215
             INDEX source_id (source_id, shop_id),
216
             INDEX group_id (group_id, shop_id),
217
             INDEX IDX_revision (revision),
218
             INDEX IDX_status (export_status)
219
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", '
220
            CREATE TABLE IF NOT EXISTS `sw_connect_shipping_rules` (
221
             `sr_id` int(11) NOT NULL AUTO_INCREMENT,
222
             `sr_group_id` int(11) unsigned DEFAULT NULL,
223
             `sr_country` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
224
             `sr_delivery_days` int(5) DEFAULT NULL,
225
             `sr_price` double DEFAULT NULL,
226
             `sr_zip_prefix` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
227
             PRIMARY KEY (`sr_id`),
228
             KEY `sr_group_id` (`sr_group_id`)
229
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci','
230
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_categories` (
231
              `id` int(11) NOT NULL AUTO_INCREMENT,
232
              `category_key` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
233
              `label` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
234
              `local_category_id` int(11) DEFAULT NULL,
235
              `shop_id` int(11) NULL,
236
              PRIMARY KEY (`id`),
237
              INDEX (`category_key`),
238
              UNIQUE KEY `scuk_connect_category_for_shop_id` (`category_key`,`shop_id`)
239
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;', '
240
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_product_to_categories` (
241
              `id` int(11) NOT NULL AUTO_INCREMENT,
242
              `connect_category_id` int(11) NOT NULL,
243
              `articleID` int(11) NOT NULL,
244
              PRIMARY KEY (`id`),
245
              INDEX article_id (articleID),
246
              UNIQUE KEY `scuk_connect_category_id` (`connect_category_id`,`articleID`)
247
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;', '
248
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_streams` (
249
              `id` int(11) NOT NULL AUTO_INCREMENT,
250
              `stream_id` int(11) NOT NULL,
251
              `export_status` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
252
              `export_message` text COLLATE utf8_unicode_ci DEFAULT NULL,
253
              PRIMARY KEY (`id`)
254
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;',"
255
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_streams_relation` (
256
                `stream_id` int(11) unsigned NOT NULL,
257
                `article_id` int(11) unsigned NOT NULL,
258
                `deleted` int(1) NOT NULL DEFAULT '0',
259
                UNIQUE KEY `stream_id` (`stream_id`,`article_id`),
260
                CONSTRAINT s_plugin_connect_streams_selection_fk_stream_id FOREIGN KEY (stream_id) REFERENCES s_product_streams (id) ON DELETE CASCADE,
261
                CONSTRAINT s_plugin_connect_streams_selection_fk_article_id FOREIGN KEY (article_id) REFERENCES s_articles (id) ON DELETE CASCADE
262
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;", '
263
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_categories_to_local_categories` (
264
                `id` int(11) NOT NULL AUTO_INCREMENT,
265
                `remote_category_id` int(11) NOT NULL,
266
                `local_category_id` int(11) unsigned NOT NULL,
267
                `stream` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
268
                PRIMARY KEY (`id`),
269
                UNIQUE KEY `scuk_connect_category_to_local_category` (`remote_category_id`, `local_category_id`, `stream`),
270
                CONSTRAINT s_plugin_connect_remote_categories_fk_remote_category_id FOREIGN KEY (remote_category_id) REFERENCES s_plugin_connect_categories (id) ON DELETE CASCADE,
271
                CONSTRAINT s_plugin_connect_remote_categories_fk_local_category_id FOREIGN KEY (local_category_id) REFERENCES s_categories (id) ON DELETE CASCADE
272
            ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
273
            ', '
274
            CREATE TABLE IF NOT EXISTS `s_plugin_connect_article_relations` (
275
                `id` int(11) NOT NULL AUTO_INCREMENT,
276
                `article_id` int(11) unsigned NOT NULL,
277
                `shop_id` int(11) NOT NULL,
278
                `related_article_local_id` int(11) NOT NULL,
279
                `relationship_type` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
280
                PRIMARY KEY (`id`),
281
                UNIQUE KEY `relations` (`article_id`, `shop_id`, `related_article_local_id`, `relationship_type`),
282
                CONSTRAINT s_plugin_connect_article_relations_fk_article_id FOREIGN KEY (article_id) REFERENCES s_articles (id) ON DELETE CASCADE
283
            ) ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
284
            '];
285
286
        foreach ($queries as $query) {
287
            $this->db->exec($query);
288
        }
289
    }
290
291
    public function getCrudService()
292
    {
293
        return Shopware()->Container()->get('shopware_attribute.crud_service');
294
    }
295
296
    /**
297
     * Creates product, order and category attributes
298
     */
299
    private function createMyAttributes()
300
    {
301
        /** @var CrudService $crudService */
302
        $crudService = $this->getCrudService();
303
304
        $crudService->update(
305
            's_order_attributes',
306
            'connect_shop_id',
307
            'integer'
308
        );
309
310
        $crudService->update(
311
            's_order_attributes',
312
            'connect_order_id',
313
            'integer'
314
        );
315
316
        $crudService->update(
317
            's_categories_attributes',
318
            'connect_import_mapping',
319
            'text'
320
        );
321
322
        $crudService->update(
323
            's_categories_attributes',
324
            'connect_export_mapping',
325
            'text'
326
        );
327
328
        $crudService->update(
329
            's_categories_attributes',
330
            'connect_imported',
331
            'text'
332
        );
333
334
        $crudService->update(
335
            's_media_attributes',
336
            'connect_hash',
337
            'string'
338
        );
339
340
        $crudService->update(
341
            's_premium_dispatch_attributes',
342
            'connect_allowed',
343
            'boolean',
344
            [],
345
            null,
346
            false,
347
            1
348
        );
349
350
        $crudService->update(
351
            's_articles_attributes',
352
            'connect_product_description',
353
            'html',
354
            [
355
                'translatable' => 1,
356
                'displayInBackend' => 1,
357
                'label' => 'Connect Beschreibung'
358
            ]
359
        );
360
361
        $crudService->update(
362
            's_articles_prices_attributes',
363
            'connect_price',
364
            'float',
365
            [],
366
            null,
367
            false,
368
            0
369
        );
370
371
        $crudService->update(
372
            's_core_customergroups_attributes',
373
            'connect_group',
374
            'boolean'
375
        );
376
377
        $crudService->update(
378
            's_articles_attributes',
379
            'connect_article_shipping',
380
            'text'
381
        );
382
383
        $crudService->update(
384
            's_articles_attributes',
385
            'connect_reference',
386
            'string'
387
        );
388
389
        $crudService->update(
390
            's_articles_attributes',
391
            'connect_property_group',
392
            'string'
393
        );
394
395
        $crudService->update(
396
            's_categories_attributes',
397
            'connect_imported_category',
398
            'boolean'
399
        );
400
401
        $crudService->update(
402
            's_articles_attributes',
403
            'connect_mapped_category',
404
            'boolean'
405
        );
406
407
        $crudService->update(
408
            's_articles_attributes',
409
            'connect_remote_unit',
410
            'string'
411
        );
412
413
        $crudService->update(
414
            's_articles_supplier_attributes',
415
            'connect_is_remote',
416
            'boolean',
417
            [],
418
            null,
419
            false,
420
            0
421
        );
422
423
        $crudService->update(
424
            's_articles_img_attributes',
425
            'connect_detail_mapping_id',
426
            'integer'
427
        );
428
429
        $crudService->update(
430
            's_filter_attributes',
431
            'connect_is_remote',
432
            'boolean',
433
            [],
434
            null,
435
            false,
436
            0
437
        );
438
439
        $crudService->update(
440
            's_filter_options_attributes',
441
            'connect_is_remote',
442
            'boolean',
443
            [],
444
            null,
445
            false,
446
            0
447
        );
448
449
        $crudService->update(
450
            's_filter_values_attributes',
451
            'connect_is_remote',
452
            'boolean',
453
            [],
454
            null,
455
            false,
456
            0
457
        );
458
459
        $crudService->update(
460
            's_product_streams_attributes',
461
            'connect_is_remote',
462
            'boolean',
463
            [],
464
            null,
465
            false,
466
            0
467
        );
468
469
        $this->modelManager->generateAttributeModels([
470
            's_articles_attributes',
471
            's_articles_supplier_attributes',
472
            's_order_attributes',
473
            's_core_customergroups_attributes',
474
            's_articles_prices_attributes',
475
            's_premium_dispatch_attributes',
476
            's_categories_attributes',
477
            's_order_details_attributes',
478
            's_order_basket_attributes',
479
            's_articles_img_attributes',
480
            's_media_attributes',
481
            's_filter_attributes',
482
            's_filter_options_attributes',
483
            's_filter_values_attributes',
484
            's_product_streams_attributes',
485
        ]);
486
    }
487
488
    /**
489
     * Creates the configuration table. Existing configs will not be overwritten
490
     */
491
    public function populateConfigTable()
492
    {
493
        /** @var Config $configComponent */
494
        $configComponent = ConfigFactory::getConfigInstance();
495
        // when add/remove item in $configs array
496
        // open ConnectConfigTest.php and change tearDown function
497
        // for some reason shopware runs test during plugin installation
498
        $configs = [
499
            'priceGroupForPriceExport' => ['', null, 'export'],
500
            'priceGroupForPurchasePriceExport' => ['', null, 'export'],
501
            'priceFieldForPriceExport' => ['', null, 'export'],
502
            'priceFieldForPurchasePriceExport' => ['', null, 'export'],
503
            'excludeInactiveProducts' => ['1', null, 'export'],
504
            'detailProductNoIndex' => ['1', null, 'general'],
505
            'detailShopInfo' => ['1', null, 'general'],
506
            'checkoutShopInfo' => ['1', null, 'general'],
507
            'longDescriptionField' => ['1', null, 'export'],
508
            'importImagesOnFirstImport' => ['1', null, 'import'],
509
            'autoUpdateProducts' => ['1', null, 'export'],
510
            'overwriteProductName' => ['1', null, 'import'],
511
            'overwriteProductPrice' => ['1', null, 'import'],
512
            'overwriteProductImage' => ['1', null, 'import'],
513
            'overwriteProductMainImage' => ['1', null, 'import'],
514
            'overwriteProductShortDescription' => ['1', null, 'import'],
515
            'overwriteProductLongDescription' => ['1', null, 'import'],
516
            'overwriteProductAdditionalDescription' => ['1', null, 'import'],
517
            'logRequest' => ['1', null, 'general'],
518
            'showShippingCostsSeparately' => ['0', null, 'general'],
519
            'articleImagesLimitImport' => [5, null, 'import'],
520
            'updateOrderStatus' => ['0', null, 'import'],
521
        ];
522
523
        foreach ($configs as $name => $values) {
524
            list($value, $shopId, $group) = $values;
525
526
            try {
527
                $configComponent->setConfig(
528
                    $name,
529
                    $configComponent->getConfig($name, $value, $shopId),
530
                    $shopId,
531
                    $group
532
                );
533
            } catch (\Exception $e) {
534
                // This may fail if the config table was not updated, yet.
535
                // The Updater will take care of this
536
            }
537
        }
538
    }
539
540
    /**
541
     * Import frontend snippets
542
     * @param $pluginPath string
543
     */
544
    public function importSnippets($pluginPath)
545
    {
546
        $sql = file_get_contents($pluginPath . '/Snippets/frontend.sql');
547
        $this->db->exec($sql);
548
    }
549
550
    /**
551
     * Creates a shopware Connect customer group - this can be used by the shop owner to manage the Connect product prices
552
     *
553
     * Logic is very simple here - if a group with the key 'SC' already exists, no new group is created
554
     */
555
    public function createConnectCustomerGroup()
556
    {
557
        $connectGroupAttributeId = $this->getConnectCustomerGroupId();
558
        if (!$this->connectCustomerGroupExists($connectGroupAttributeId)) {
559
560
            // Create Customer Group
561
            $this->db->insert(
562
                's_core_customergroups',
563
                [
564
                    'groupkey' => $this->getAvailableCustomerGroupName(),
565
                    'description' => 'SC export',
566
                    'tax' => 0,
567
                    'taxinput' => 0,
568
                    'mode' => 0
569
                ]
570
            );
571
572
            $customerGroupID = $this->db->fetchOne('SELECT MAX(id) FROM s_core_customergroups');
573
574
            // Create Customer Group Attributes
575
            $this->db->insert(
576
                's_core_customergroups_attributes',
577
                [
578
                  'customerGroupID' => $customerGroupID,
579
                  'connect_group' => 1
580
                ]
581
            );
582
        }
583
    }
584
585
    private function getConnectCustomerGroupId()
586
    {
587
        return $this->db->fetchOne(
588
            'SELECT customerGroupID
589
            FROM `s_core_customergroups_attributes`
590
            WHERE connect_group = 1'
591
        );
592
    }
593
594
    private function connectCustomerGroupExists($attributeId)
595
    {
596
        $result = $this->db->fetchOne(
597
            'SELECT COUNT(*)
598
            FROM `s_core_customergroups`
599
            WHERE id = :id',
600
            [
601
                'id' => $attributeId
602
            ]
603
        );
604
605
        return !empty($result);
606
    }
607
608
    /**
609
     * Return a free customer group name. It will only check 5 groups - if all are used, probably the detection
610
     * of existing connectCustomerGroups is broken. Throw an exception then
611
     *
612
     * @throws \RuntimeException
613
     * @return mixed
614
     */
615
    private function getAvailableCustomerGroupName()
616
    {
617
        $names = ['SC', 'SWC', 'SWCONN', 'SC-1'];
618
619
        $repo = $this->modelManager->getRepository('Shopware\Models\Customer\Group');
620
        foreach ($names as $name) {
621
            $model = $repo->findOneBy(['key' => $name]);
622
            if (is_null($model)) {
623
                return $name;
624
            }
625
        }
626
627
        throw new \RuntimeException('Could not find a free group name for the Shopware Connect customer group.Probably you need to delete an existing customer group created by Shopware Connect (SC, SWC, SWCONN, SC-1). Make sure, you really don\'t need it any more!'
628
        );
629
    }
630
631
    /**
632
     * Populates the dispatch attributes with entries for each dispatch type, so that
633
     * the connect attribute can be used
634
     */
635
    public function populateDispatchAttributes()
636
    {
637
        $this->db->exec('
638
            INSERT IGNORE INTO `s_premium_dispatch_attributes` (`dispatchID`)
639
            SELECT `id` FROM `s_premium_dispatch`
640
        ');
641
    }
642
643
    /**
644
     * Generates connect payment attribute
645
     */
646
    public function generateConnectPaymentAttribute()
647
    {
648
        /** @var CrudService $crudService */
649
        $crudService = $this->getCrudService();
650
651
        $crudService->update(
652
            's_core_paymentmeans_attributes',
653
            'connect_is_allowed',
654
            'boolean',
655
            [],
656
            null,
657
            false,
658
            1
659
        );
660
661
        $this->modelManager->generateAttributeModels([
662
            's_core_paymentmeans_attributes'
663
        ]);
664
665
        $this->modelManager->regenerateProxies();
666
    }
667
668
    public function populateConnectPaymentAttribute()
669
    {
670
        $this->db->exec('
671
            INSERT IGNORE INTO `s_core_paymentmeans_attributes` (`paymentmeanID`)
672
            SELECT `id` FROM `s_core_paymentmeans`
673
        ');
674
    }
675
676
    public function populatePaymentStates()
677
    {
678
        $states = [
679
            'sc_received' => ' SC received',
680
            'sc_requested' => 'SC requested',
681
            'sc_initiated' => 'SC initiated',
682
            'sc_instructed' => 'SC instructed',
683
            'sc_aborted' => 'SC aborted',
684
            'sc_timeout' => 'SC timeout',
685
            'sc_pending' => 'SC pending',
686
            'sc_refunded' => 'SC refunded',
687
            'sc_verify' => 'SC verify',
688
            'sc_loss' => 'SC loss',
689
            'sc_error' => 'SC error',
690
        ];
691
692
        $this->populateStates($states, Status::GROUP_PAYMENT);
693
    }
694
695
    public function populateOrderStates()
696
    {
697
        $states = [
698
            ConnectOrderUtil::ORDER_STATUS_ERROR => 'SC error'
699
        ];
700
701
        $this->populateStates($states, Status::GROUP_STATE);
702
    }
703
704
    public function populateStates(array $states, $group)
705
    {
706
        $currentId = $this->getMaxStateId();
707
708
        foreach ($states as $name => $description) {
709
            $isExists = $this->db->query('
710
                SELECT `id` FROM `s_core_states`
711
                WHERE `name` = ? AND `group` = ?
712
                ', [$name, $group]
713
            )->fetch();
714
715
            if ($isExists) {
716
                continue;
717
            }
718
719
            ++$currentId;
720
            $this->db->query('
721
                INSERT INTO `s_core_states`
722
                (`id`, `name`, `description`, `position`, `group`, `mail`)
723
                VALUES (?, ?, ?, ?, ?, ?)
724
                ', [$currentId, $name, $description, $currentId, $group, 0]
725
            );
726
        }
727
    }
728
729
    /**
730
     * @return int
731
     */
732
    private function getMaxStateId()
733
    {
734
        $query = $this->modelManager->getRepository('Shopware\Models\Order\Status')->createQueryBuilder('s');
735
        $query->select('MAX(s.id)');
736
        $result = $query->getQuery()->getOneOrNullResult();
737
738
        if (count($result) > 0) {
739
            return (int) reset($result);
740
        }
741
742
        return 0;
743
    }
744
}
745