custom/plugins/AcrisDiscountGroupCS/src/AcrisDiscountGroupCS.php line 20

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Acris\DiscountGroup;
  3. use Doctrine\DBAL\Connection;
  4. use Shopware\Core\Content\ImportExport\ImportExportProfileEntity;
  5. use Shopware\Core\Framework\Context;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
  11. use Shopware\Core\Framework\Plugin;
  12. use Shopware\Core\Framework\Plugin\Context\InstallContext;
  13. use Shopware\Core\Framework\Plugin\Context\UninstallContext;
  14. use Shopware\Core\Framework\Plugin\Context\UpdateContext;
  15. use Shopware\Core\System\CustomField\CustomFieldTypes;
  16. use Shopware\Core\System\Snippet\SnippetEntity;
  17. class AcrisDiscountGroupCS extends Plugin
  18. {
  19.     /** @deprecated  */
  20.     const CUSTOM_FIELD_SET_NAME_DISCOUNT_GROUP 'acris_discount_group';
  21.     const CUSTOM_FIELD_SET_NAME_CUSTOMER_DISCOUNT_GROUP 'acris_discount_group_customer';
  22.     const CUSTOM_FIELD_SET_NAME_PRODUCT_DISCOUNT_GROUP 'acris_discount_group_product';
  23.     const IMPORT_EXPORT_PROFILE_NAME 'ACRIS Discount Groups';
  24.     public function install(InstallContext $context): void
  25.     {
  26.         $this->addCustomFields($context->getContext());
  27.         $this->addImportExportProfile($context->getContext());
  28.     }
  29.     public function postUpdate(UpdateContext $updateContext): void
  30.     {
  31.         if(version_compare($updateContext->getCurrentPluginVersion(), '1.2.0''<') && $updateContext->getPlugin()->isActive() === true) {
  32.             $this->addImportExportProfile($updateContext->getContext());
  33.         }
  34.         
  35.         if(version_compare($updateContext->getCurrentPluginVersion(), '1.4.0''<')
  36.             && version_compare($updateContext->getUpdatePluginVersion(), '1.4.0''>=')) {
  37.             $this->addCustomFields($updateContext->getContext());
  38.         }
  39.     }
  40.     public function uninstall(UninstallContext $context): void
  41.     {
  42.         if ($context->keepUserData()) {
  43.             return;
  44.         }
  45.         $this->cleanupImportExportProfile($context->getContext());
  46.         $this->removeCustomFields($context->getContext(), [self::CUSTOM_FIELD_SET_NAME_DISCOUNT_GROUPself::CUSTOM_FIELD_SET_NAME_PRODUCT_DISCOUNT_GROUPself::CUSTOM_FIELD_SET_NAME_CUSTOMER_DISCOUNT_GROUP]);
  47.         $this->cleanupDatabase();
  48.     }
  49.     private function cleanupDatabase(): void
  50.     {
  51.         $connection $this->container->get(Connection::class);
  52.         $connection->executeStatement('DROP TABLE IF EXISTS acris_discount_group_rule');
  53.         $connection->executeStatement('DROP TABLE IF EXISTS acris_discount_dynamic_groups');
  54.         $connection->executeStatement('DROP TABLE IF EXISTS acris_discount_group');
  55.         $connection->executeStatement('DROP TABLE IF EXISTS acris_discount_group_translation');
  56.         $connection->executeUpdate('ALTER TABLE `rule` DROP COLUMN `acrisDiscountGroups`');
  57.         $connection->executeUpdate('ALTER TABLE `product_stream` DROP COLUMN `acrisDiscountGroups`');
  58.         $connection->executeUpdate('ALTER TABLE `product` DROP COLUMN `acrisDiscountGroups`');
  59.         $connection->executeUpdate('ALTER TABLE `customer` DROP COLUMN `acrisDiscountGroups`');
  60.     }
  61.     private function addCustomFields(Context $context): void
  62.     {
  63.         /* Check for snippets if they exist for custom fields */
  64.         $this->checkForExistingCustomFieldSnippets($context);
  65.         $this->removeCustomFields($context, [self::CUSTOM_FIELD_SET_NAME_DISCOUNT_GROUP]);
  66.         $customFieldSet $this->container->get('custom_field_set.repository');
  67.         if($customFieldSet->search((new Criteria())->addFilter(new EqualsFilter('name'self::CUSTOM_FIELD_SET_NAME_CUSTOMER_DISCOUNT_GROUP)), $context)->count() == 0) {
  68.             $customFieldSet->create([[
  69.                 'name' => self::CUSTOM_FIELD_SET_NAME_CUSTOMER_DISCOUNT_GROUP,
  70.                 'config' => [
  71.                     'label' => [
  72.                         'en-GB' => 'Customer discount group',
  73.                         'de-DE' => 'Kunden-Rabattgruppe'
  74.                     ]
  75.                 ],
  76.                 'customFields' => [
  77.                     ['name' => 'acris_discount_group_customer_value''type' => CustomFieldTypes::TEXT,
  78.                         'config' => [
  79.                             'componentName' => 'sw-field',
  80.                             'type' => 'text',
  81.                             'customFieldType' => 'text',
  82.                             'customFieldPosition' => 1,
  83.                             'label' => [
  84.                                 'en-GB' => 'Customer discount group',
  85.                                 'de-DE' => 'Kunden-Rabattgruppe'
  86.                             ],
  87.                             'helpText' => [
  88.                                 'en-GB' => 'The customer discount group can be used via the ACRIS plugin to allow multiple customers with the same customer discount group to receive a discount.',
  89.                                 'de-DE' => 'Die Kunden-Rabattgruppe kann über das ACRIS Plugin verwendet werden, um mehreren Kunden mit derselben Kunden-Rabattgruppe einen Rabatt zu ermöglichen.'
  90.                             ]
  91.                         ]]
  92.                 ],
  93.                 'relations' => [
  94.                     [
  95.                         'entityName' => 'customer'
  96.                     ]
  97.                 ]
  98.             ]], $context);
  99.         };
  100.         if($customFieldSet->search((new Criteria())->addFilter(new EqualsFilter('name'self::CUSTOM_FIELD_SET_NAME_PRODUCT_DISCOUNT_GROUP)), $context)->count() == 0) {
  101.             $customFieldSet->create([[
  102.                 'name' => self::CUSTOM_FIELD_SET_NAME_PRODUCT_DISCOUNT_GROUP,
  103.                 'config' => [
  104.                     'label' => [
  105.                         'en-GB' => 'Merchandise group (discount group)',
  106.                         'de-DE' => 'Warengruppe (Rabattgruppe)'
  107.                     ]
  108.                 ],
  109.                 'customFields' => [
  110.                     ['name' => 'acris_discount_group_product_value''type' => CustomFieldTypes::TEXT,
  111.                         'config' => [
  112.                             'componentName' => 'sw-field',
  113.                             'type' => 'text',
  114.                             'customFieldType' => 'text',
  115.                             'customFieldPosition' => 1,
  116.                             'label' => [
  117.                                 'en-GB' => 'Merchandise group (discount group)',
  118.                                 'de-DE' => 'Warengruppe (Rabattgruppe)'
  119.                             ],
  120.                             'helpText' => [
  121.                                 'en-GB' => 'The merchandise group (discount group) can be used via the ACRIS plugin to allow all products with the same merchandise group (discount group) to receive a discount.',
  122.                                 'de-DE' => 'Die Warengruppe (Rabattgruppe) kann über das ACRIS Plugin verwendet werden, um allen Produkten mit derselben Warengruppe (Rabattgruppe) einen Rabatt zu ermöglichen.'
  123.                             ]
  124.                         ]]
  125.                 ],
  126.                 'relations' => [
  127.                     [
  128.                         'entityName' => 'product'
  129.                     ]
  130.                 ]
  131.             ]], $context);
  132.         };
  133.     }
  134.     private function removeCustomFields(Context $context, array $setNames): void
  135.     {
  136.         /* Check for snippets if they exist for custom fields */
  137.         $this->checkForExistingCustomFieldSnippets($context);
  138.         $customFieldSet $this->container->get('custom_field_set.repository');
  139.         foreach ($setNames as $setName) {
  140.             $id $customFieldSet->searchIds((new Criteria())->addFilter(new EqualsFilter('name'$setName)), $context)->firstId();
  141.             if($id$customFieldSet->delete([['id' => $id]], $context);
  142.         }
  143.     }
  144.     private function checkForExistingCustomFieldSnippets(Context $context)
  145.     {
  146.         /** @var EntityRepositoryInterface $snippetRepository */
  147.         $snippetRepository $this->container->get('snippet.repository');
  148.         $criteria = new Criteria();
  149.         $criteria->addFilter(new MultiFilter(MultiFilter::CONNECTION_OR, [
  150.             new EqualsFilter('translationKey''customFields.' 'acris_discount_group_value'),
  151.             new EqualsFilter('translationKey''customFields.' 'acris_discount_group_customer_value'),
  152.             new EqualsFilter('translationKey''customFields.' 'acris_discount_group_product_value'),
  153.         ]));
  154.         /** @var EntitySearchResult $searchResult */
  155.         $searchResult $snippetRepository->search($criteria$context);
  156.         if ($searchResult->count() > 0) {
  157.             $snippetIds = [];
  158.             /** @var SnippetEntity $snippet */
  159.             foreach ($searchResult->getEntities()->getElements() as $snippet) {
  160.                 $snippetIds[] = [
  161.                     'id' => $snippet->getId()
  162.                 ];
  163.             }
  164.             if (!empty($snippetIds)) {
  165.                 $snippetRepository->delete($snippetIds$context);
  166.             }
  167.         }
  168.     }
  169.     private function addImportExportProfile(Context $context): void
  170.     {
  171.         $importExportProfileRepository $this->container->get('import_export_profile.repository');
  172.         foreach ($this->getOptimizedSystemDefaultProfiles() as $profile) {
  173.             $this->createIfNotExists($importExportProfileRepository, [['name' => 'name''value' => $profile['name']]], $profile$context);
  174.         }
  175.     }
  176.     private function getOptimizedSystemDefaultProfiles(): array
  177.     {
  178.         return [
  179.             [
  180.                 'name' => self::IMPORT_EXPORT_PROFILE_NAME,
  181.                 'label' => self::IMPORT_EXPORT_PROFILE_NAME,
  182.                 'systemDefault' => true,
  183.                 'sourceEntity' => 'acris_discount_group',
  184.                 'fileType' => 'text/csv',
  185.                 'delimiter' => ';',
  186.                 'enclosure' => '"',
  187.                 'mapping' => [
  188.                     ['key' => 'id''mappedKey' => 'id'],
  189.                     ['key' => 'internalName''mappedKey' => 'internalName'],
  190.                     ['key' => 'active''mappedKey' => 'active'],
  191.                     ['key' => 'activeFrom''mappedKey' => 'activeFrom'],
  192.                     ['key' => 'activeUntil''mappedKey' => 'activeUntil'],
  193.                     ['key' => 'priority''mappedKey' => 'priority'],
  194.                     ['key' => 'excluded''mappedKey' => 'excluded'],
  195.                     ['key' => 'customerAssignmentType''mappedKey' => 'customerAssignmentType'],
  196.                     ['key' => 'customer.id''mappedKey' => 'customerId'],
  197.                     ['key' => 'discountGroup''mappedKey' => 'categoryDiscountGroup'],
  198.                     ['key' => 'rules''mappedKey' => 'ruleIds'],
  199.                     ['key' => 'productAssignmentType''mappedKey' => 'productAssignmentType'],
  200.                     ['key' => 'product.id''mappedKey' => 'productId'],
  201.                     ['key' => 'materialGroup''mappedKey' => 'productDiscountGroup'],
  202.                     ['key' => 'productStreams''mappedKey' => 'productStreamIds'],
  203.                     ['key' => 'discountType''mappedKey' => 'discountType'],
  204.                     ['key' => 'discount''mappedKey' => 'discount'],
  205.                     ['key' => 'calculationType''mappedKey' => 'calculationType'],
  206.                     ['key' => 'listPriceType''mappedKey' => 'listPriceType'],
  207.                 ],
  208.                 'translations' => [
  209.                     'en-GB' => [
  210.                         'label' => self::IMPORT_EXPORT_PROFILE_NAME
  211.                     ],
  212.                     'de-DE' => [
  213.                         'label' => self::IMPORT_EXPORT_PROFILE_NAME
  214.                     ]
  215.                 ],
  216.             ],
  217.         ];
  218.     }
  219.     private function createIfNotExists(EntityRepositoryInterface $repository, array $equalFields, array $dataContext $context)
  220.     {
  221.         $filters = [];
  222.         foreach ($equalFields as $equalField) {
  223.             $filters[] = new EqualsFilter($equalField['name'], $equalField['value']);
  224.         }
  225.         if(sizeof($filters) > 1) {
  226.             $filter = new MultiFilter(MultiFilter::CONNECTION_OR$filters);
  227.         } else {
  228.             $filter array_shift($filters);
  229.         }
  230.         $searchResult $repository->search((new Criteria())->addFilter($filter), $context);
  231.         if($searchResult->count() == 0) {
  232.             $repository->create([$data], $context);
  233.         }
  234.     }
  235.     private function cleanupImportExportProfile(Context $context): void
  236.     {
  237.         $importExportProfile $this->container->get('import_export_profile.repository');
  238.         $storeLocatorProfiles $importExportProfile->search((new Criteria())->addFilter(new EqualsFilter('sourceEntity''acris_discount_group')), $context);
  239.         $ids = [];
  240.         if ($storeLocatorProfiles->getTotal() > && $storeLocatorProfiles->first()) {
  241.             /** @var ImportExportProfileEntity $entity */
  242.             foreach ($storeLocatorProfiles->getEntities() as $entity) {
  243.                 if ($entity->getSystemDefault() === true) {
  244.                     $importExportProfile->update([
  245.                         ['id' => $entity->getId(), 'systemDefault' => false ]
  246.                     ], $context);
  247.                 }
  248.                 $ids[] = ['id' => $entity->getId()];
  249.             }
  250.             $importExportProfile->delete($ids$context);
  251.         }
  252.     }
  253. }