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