├── registration.php
├── src
├── etc
│ ├── module.xml
│ ├── adminhtml
│ │ ├── routes.xml
│ │ ├── di.xml
│ │ └── system.xml
│ └── config.xml
├── Block
│ └── Adminhtml
│ │ └── Product
│ │ └── Edit
│ │ └── Button
│ │ ├── ExportButton.php
│ │ ├── ImportButton.php
│ │ └── AbstractButton.php
├── view
│ └── adminhtml
│ │ └── ui_component
│ │ └── product_form.xml
├── Helper
│ ├── Reflection.php
│ └── Config.php
├── Plugin
│ ├── AddMaintenanceActionsPlugin.php
│ ├── SetStrictSkuFilterPlugin.php
│ └── SeparateAttributeColumnsPlugin.php
└── Controller
│ └── Adminhtml
│ └── Product
│ ├── AbstractAction.php
│ ├── Export.php
│ └── Import.php
├── composer.json
├── LICENSE.txt
└── README.md
/registration.php:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/etc/adminhtml/routes.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/etc/config.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 | /tmp
11 | 0
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rubic/magento2-module-product-maintenance",
3 | "description": "Magento 2 product maintenance using CSV files.",
4 | "type": "magento2-module",
5 | "license": "MIT",
6 | "autoload": {
7 | "files": [
8 | "registration.php"
9 | ],
10 | "psr-4": {
11 | "Rubic\\ProductMaintenance\\": "src/"
12 | }
13 | },
14 | "require": {
15 | "firegento/fastsimpleimport": "^1.1.0",
16 | "league/csv": "^9.1.2"
17 | },
18 | "suggest": {
19 | "firegento/extendedimport": "Allows automatic creation of new attribute values"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/Block/Adminhtml/Product/Edit/Button/ExportButton.php:
--------------------------------------------------------------------------------
1 | getUrl('product_maintenance/product/export', ['product_id' => $this->getProductId()]);
28 | }
29 | }
--------------------------------------------------------------------------------
/src/Block/Adminhtml/Product/Edit/Button/ImportButton.php:
--------------------------------------------------------------------------------
1 | getUrl('product_maintenance/product/import', ['product_id' => $this->getProductId()]);
28 | }
29 | }
--------------------------------------------------------------------------------
/src/view/adminhtml/ui_component/product_form.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
--------------------------------------------------------------------------------
/src/Helper/Reflection.php:
--------------------------------------------------------------------------------
1 | getProperty($property);
22 | $property->setAccessible(true);
23 | return $property;
24 | }
25 | }
--------------------------------------------------------------------------------
/src/etc/adminhtml/di.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright 2018 Rubic
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/src/Helper/Config.php:
--------------------------------------------------------------------------------
1 | scopeConfig = $scopeConfig;
26 | }
27 |
28 | /**
29 | * Determines if we should use separate attribute columns.
30 | *
31 | * @return bool
32 | */
33 | public function shouldUseSeparateAttributeColumns()
34 | {
35 | return (bool)$this->scopeConfig->getValue(self::XML_PATH_SEPARATE_ATTRIBUTE_COLUMNS);
36 | }
37 | }
--------------------------------------------------------------------------------
/src/etc/adminhtml/system.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 | service
11 | Rubic_ProductMaintenance::config_product_maintenance
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | Magento\Config\Model\Config\Source\Yesno
20 | If enabled, puts user defined attribute in separate columns instead of using additional_attributes column.
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/src/Block/Adminhtml/Product/Edit/Button/AbstractButton.php:
--------------------------------------------------------------------------------
1 | request = $request;
29 | }
30 |
31 | /**
32 | * Gets the action label.
33 | *
34 | * @return string
35 | */
36 | abstract protected function getActionLabel();
37 |
38 | /**
39 | * Gets the action URL.
40 | *
41 | * @return string
42 | */
43 | abstract protected function getActionUrl();
44 |
45 | /**
46 | * Gets the current product ID.
47 | *
48 | * @return int
49 | */
50 | protected function getProductId()
51 | {
52 | return $this->request->getParam('id');
53 | }
54 |
55 | /**
56 | * @return array
57 | */
58 | public function getButtonData()
59 | {
60 | return [
61 | 'label' => __($this->getActionLabel()),
62 | 'on_click' => "setLocation('{$this->getActionUrl()}')",
63 | 'sort_order' => 100
64 | ];
65 | }
66 | }
--------------------------------------------------------------------------------
/src/Plugin/AddMaintenanceActionsPlugin.php:
--------------------------------------------------------------------------------
1 | url = $url;
24 | }
25 |
26 | /**
27 | * Add import and export buttons to product actions in the grid.
28 | *
29 | * @param ProductActions $productActions
30 | * @param array $dataSource
31 | * @return array
32 | */
33 | public function afterPrepareDataSource(ProductActions $productActions, array $dataSource)
34 | {
35 | if (isset($dataSource['data']['items'])) {
36 | foreach ($dataSource['data']['items'] as &$item) {
37 | if (!isset($item['entity_id'])) continue;
38 | foreach (['export', 'import'] as $actionType) {
39 | $item[$productActions->getData('name')][$actionType] = [
40 | 'href' => $this->url->getUrl(
41 | sprintf('product_maintenance/product/%s', $actionType),
42 | [
43 | 'product_id' => $item['entity_id'],
44 | 'toGrid' => true
45 | ]
46 | ),
47 | 'label' => __(ucfirst($actionType)),
48 | 'hidden' => false,
49 | ];
50 | }
51 | }
52 | }
53 | return $dataSource;
54 | }
55 | }
--------------------------------------------------------------------------------
/src/Plugin/SetStrictSkuFilterPlugin.php:
--------------------------------------------------------------------------------
1 | reflectionHelper = $reflectionHelper;
25 | }
26 |
27 | /**
28 | * Magento 2 product exports treats all filterable attributes it thinks came from user input
29 | * as a 'FILTER_TYPE_INPUT', in which case it will filter using a LIKE %...%.
30 | *
31 | * However, any attribute that has its own source model or has 'filter_options' data set, will
32 | * get a stricter 'eq' filter.
33 | *
34 | * It's necessary for us to do strict filtering, because we only want to export a single product
35 | * based on the SKU.
36 | *
37 | * @param Product $product
38 | * @param Collection $collection
39 | * @return Collection
40 | */
41 | public function afterFilterAttributeCollection(Product $product, Collection $collection)
42 | {
43 | $parameters = $this->reflectionHelper->getAccessibleObjectProperty($product, '_parameters')->getValue($product);
44 | if ($parameters['strict_sku_filter'] ?? false) {
45 | $skuAttribute = $collection->getItemByColumnValue('attribute_code', 'sku');
46 | $skuAttribute->setFilterOptions(true);
47 | }
48 | return $collection;
49 | }
50 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Product Maintenance for Magento 2
2 |
3 | Managing your products from the Magento 2 backend can be a tedious process. This module allows easy maintenance of your Magento 2 products by making it easy to import and export (single) products using CSV files.
4 |
5 | You can choose your own product directory, for example a mounted Google Drive folder (using [google-drive-ocamlfuse](https://github.com/astrada/google-drive-ocamlfuse)) from which you can then make quick edits using your favorite editor, like Google Sheets.
6 |
7 | In addition, you can just drop product images in an image folder and they will automatically be added to your product.
8 |
9 | For importing products, we use [FireGento_FastSimpleImport2](https://github.com/firegento/FireGento_FastSimpleImport2).
10 |
11 | ## Installation
12 |
13 | ```bash
14 | $ composer require rubic/magento2-module-product-maintenance
15 | ```
16 |
17 | ## Usage
18 | When opening a product in the backend, you'll have two extra buttons; Export and Import. When clicking Export, a folder is created in the given path in the configuration (`Stores > Configuration > Services > Product Maintenance`)) with the product CSV and images. After editing the CSV, click Import to import the new data.
19 |
20 | These actions can also be found in the product grid.
21 |
22 | ## Extra
23 | Install [FireGento_ExtendedImport2](https://github.com/firegento/FireGento_ExtendedImport2) if you want the importer to automatically add new attribute options.
24 |
25 | ## License
26 |
27 | Copyright 2018 Rubic
28 |
29 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
30 |
31 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
32 |
33 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 |
--------------------------------------------------------------------------------
/src/Controller/Adminhtml/Product/AbstractAction.php:
--------------------------------------------------------------------------------
1 | productRepository = $productRepository;
53 | $this->scopeConfig = $scopeConfig;
54 | }
55 |
56 | /**
57 | * Gets product by product id.
58 | *
59 | * @param int $productId
60 | * @return ProductInterface
61 | * @throws NoSuchEntityException
62 | */
63 | protected function getProductById($productId)
64 | {
65 | return $this->productRepository->getById($productId);
66 | }
67 |
68 | /**
69 | * Gets the product directory from config.
70 | *
71 | * @param string $sku
72 | * @return string
73 | */
74 | protected function getProductDirectory($sku)
75 | {
76 | return $this->scopeConfig->getValue(self::XML_PATH_PRODUCT_DIRECTORY) .
77 | DIRECTORY_SEPARATOR .
78 | $sku .
79 | DIRECTORY_SEPARATOR;
80 | }
81 |
82 | /**
83 | * Gets path to product CSV file.
84 | *
85 | * @param string $sku
86 | * @return string
87 | */
88 | protected function getProductCsvFile($sku)
89 | {
90 | return $this->getProductDirectory($sku) . $sku . '.csv';
91 | }
92 | }
--------------------------------------------------------------------------------
/src/Controller/Adminhtml/Product/Export.php:
--------------------------------------------------------------------------------
1 | productResource = $productResource;
48 | $this->exportFactory = $exportFactory;
49 | }
50 |
51 | /**
52 | * Writes product data to CSV.
53 | *
54 | * @param string $sku
55 | * @param string $data
56 | * @return void
57 | */
58 | private function writeProductData($sku, $data)
59 | {
60 | $productDirectory = $this->getProductDirectory($sku);
61 | @mkdir($productDirectory . 'images', 0777, true);
62 | file_put_contents($this->getProductCsvFile($sku), $data);
63 | }
64 |
65 | /**
66 | * Gets product export data by SKU.
67 | *
68 | * @param string $sku
69 | * @return string
70 | * @throws LocalizedException
71 | */
72 | private function getProductExportData($sku)
73 | {
74 | $exporter = $this->exportFactory->create([
75 | 'data' => [
76 | ExportModel::FILTER_ELEMENT_GROUP => ['sku' => $sku],
77 | 'strict_sku_filter' => true,
78 | 'entity' => 'catalog_product',
79 | 'file_format' => 'csv'
80 | ]
81 | ]);
82 | return $exporter->export();
83 | }
84 |
85 | /**
86 | * Exports product to CSV.
87 | *
88 | * @return ResultInterface|ResponseInterface
89 | * @throws NoSuchEntityException
90 | * @throws LocalizedException
91 | */
92 | public function execute()
93 | {
94 | $productId = $this->_request->getParam('product_id');
95 | /** @var Product $product */
96 | $product = $this->getProductById($productId);
97 | $exportData = $this->getProductExportData($product->getSku());
98 | $this->writeProductData($product->getSku(), $exportData);
99 |
100 | $this->messageManager->addSuccessMessage('Exported product.');
101 | $redirect = $this->resultRedirectFactory->create();
102 |
103 | $returnPath = self::CATALOG_PRODUCT_EDIT_PATH;
104 | $params = ['id' => $productId];
105 |
106 | if ($this->_request->getParam('toGrid')) {
107 | $returnPath = self::CATALOG_PRODUCT_GRID_PATH;
108 | $params = [];
109 | }
110 |
111 | $redirect->setPath($returnPath, $params);
112 | return $redirect;
113 | }
114 | }
--------------------------------------------------------------------------------
/src/Controller/Adminhtml/Product/Import.php:
--------------------------------------------------------------------------------
1 | importer = $importer;
48 | $this->directoryList = $directoryList;
49 | }
50 |
51 | /**
52 | * Reads CSV from path and returns associative array.
53 | *
54 | * @param string $path
55 | * @return array
56 | * @throws \League\Csv\Exception
57 | */
58 | private function readCsv($path)
59 | {
60 | $csv = CsvReader::createFromPath($path);
61 | $csv->setDelimiter(',');
62 | $csv->setHeaderOffset(0);
63 | return iterator_to_array($csv->getRecords(), false);
64 | }
65 |
66 | /**
67 | * Gets the image import directory.
68 | *
69 | * @return string
70 | */
71 | private function getImageImportDirectory()
72 | {
73 | return $this->directoryList->getPath(DirectoryList::MEDIA) .
74 | DIRECTORY_SEPARATOR .
75 | 'import' .
76 | DIRECTORY_SEPARATOR;
77 | }
78 |
79 | /**
80 | * Moves and gets additional images.
81 | *
82 | * @param string $sku
83 | * @return array
84 | */
85 | private function getAdditionalImages($sku)
86 | {
87 | $additionalImages = [];
88 | $images = glob($this->getProductDirectory($sku) . 'images/*');
89 | foreach ($images as $image) {
90 | $fileParts = explode('/', $image);
91 | $fileName = $sku . '_' . end($fileParts);
92 | copy($image, $this->getImageImportDirectory() . $fileName);
93 | $additionalImages[] = $fileName;
94 | }
95 | return $additionalImages;
96 | }
97 |
98 | /**
99 | * Imports product.
100 | *
101 | * @return ResultInterface|ResponseInterface
102 | * @throws NoSuchEntityException
103 | * @throws \League\Csv\Exception
104 | */
105 | public function execute()
106 | {
107 | $productId = $this->_request->getParam('product_id');
108 | /** @var Product $product */
109 | $product = $this->getProductById($productId);
110 | $sku = $product->getSku();
111 | $data = $this->readCsv($this->getProductCsvFile($sku));
112 | $data[0]['additional_images'] = implode(
113 | ImportModel::DEFAULT_GLOBAL_MULTI_VALUE_SEPARATOR,
114 | $this->getAdditionalImages($sku)
115 | );
116 | try {
117 | $this->importer->processImport($data);
118 | $this->messageManager->addSuccessMessage($this->importer->getLogTrace());
119 | } catch (\Exception $e) {
120 | $this->messageManager->addErrorMessage($e->getMessage());
121 | }
122 |
123 | $redirect = $this->resultRedirectFactory->create();
124 |
125 | $returnPath = self::CATALOG_PRODUCT_EDIT_PATH;
126 | $params = ['id' => $productId];
127 |
128 | if ($this->_request->getParam('toGrid')) {
129 | $returnPath = self::CATALOG_PRODUCT_GRID_PATH;
130 | $params = [];
131 | }
132 |
133 | $redirect->setPath($returnPath, $params);
134 | return $redirect;
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/src/Plugin/SeparateAttributeColumnsPlugin.php:
--------------------------------------------------------------------------------
1 | attributeRepository = $attributeRepository;
60 | $this->searchCriteriaBuilder = $searchCriteriaBuilder;
61 | $this->reflectionHelper = $reflectionHelper;
62 | $this->scopeConfig = $scopeConfig;
63 | $this->configHelper = $configHelper;
64 | }
65 |
66 | /**
67 | * Returns an array of user defined product attribute codes.
68 | *
69 | * @return array
70 | */
71 | private function getUserDefinedProductAttributeCodes()
72 | {
73 | $attributes = $this->attributeRepository->getList(
74 | ProductAttributeInterface::ENTITY_TYPE_CODE,
75 | $this->searchCriteriaBuilder->addFilter('is_user_defined', 1)->create()
76 | );
77 | $attributeCodes = [];
78 | foreach ($attributes->getItems() as $attribute) {
79 | $attributeCodes[] = $attribute->getAttributeCode();
80 | }
81 | return $attributeCodes;
82 | }
83 |
84 | /**
85 | * Removes additional_attributes from the header columns.
86 | *
87 | * @param ExportProduct $product
88 | * @param array $result
89 | * @return array
90 | */
91 | public function after_getHeaderColumns(ExportProduct $product, array $result)
92 | {
93 | if ($this->configHelper->shouldUseSeparateAttributeColumns()) {
94 | unset($result[array_search('additional_attributes', $result)]);
95 | }
96 | return $result;
97 | }
98 |
99 | /**
100 | * Change the delimiter for importing.
101 | *
102 | * @param ImportProduct $product
103 | * @param array $values
104 | * @param string $delimiter
105 | * @return array
106 | */
107 | public function beforeParseMultiselectValues(
108 | ImportProduct $product,
109 | $values,
110 | $delimiter = ImportProduct::PSEUDO_MULTI_LINE_SEPARATOR
111 | ) {
112 | return [
113 | $values,
114 | $this->configHelper->shouldUseSeparateAttributeColumns() ?
115 | Import::DEFAULT_GLOBAL_MULTI_VALUE_SEPARATOR : $delimiter
116 | ];
117 | }
118 |
119 | /**
120 | * Adds user defined product attributes to the main attribute codes.
121 | * This gives these attributes an individual column instead of being stuffed into additional_attributes.
122 | *
123 | * @param ExportProduct $product
124 | */
125 | public function beforeExport(ExportProduct $product)
126 | {
127 | if ($this->configHelper->shouldUseSeparateAttributeColumns()) {
128 | $userDefinedAttributeCodes = $this->getUserDefinedProductAttributeCodes();
129 | $mainAttributesProperty = $this->reflectionHelper
130 | ->getAccessibleObjectProperty($product, '_exportMainAttrCodes');
131 | $mainAttributeCodes = $mainAttributesProperty->getValue($product);
132 | $mainAttributeCodes = array_merge(
133 | $mainAttributeCodes,
134 | array_diff($userDefinedAttributeCodes, $mainAttributeCodes)
135 | );
136 | $mainAttributesProperty->setValue($product, $mainAttributeCodes);
137 | }
138 | }
139 | }
--------------------------------------------------------------------------------