-
-
Notifications
You must be signed in to change notification settings - Fork 438
/
Product.php
2231 lines (2032 loc) · 82.6 KB
/
Product.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* OpenMage
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available at https://opensource.org/license/osl-3-0-php
*
* @category Mage
* @package Mage_ImportExport
* @copyright Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
* @copyright Copyright (c) 2019-2023 The OpenMage Contributors (https://www.openmage.org)
* @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Import entity product model
*
* @category Mage
* @package Mage_ImportExport
*/
class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Model_Import_Entity_Abstract
{
/**
* Configuration key for product type
*/
public const CONFIG_KEY_PRODUCT_TYPES = 'global/importexport/import_product_types';
/**
* Size of bunch - part of products to save in one step.
*/
public const BUNCH_SIZE = 20;
/**
* Value that means all entities (e.g. websites, groups etc.)
*/
public const VALUE_ALL = 'all';
/**
* Default Scope
*/
public const SCOPE_DEFAULT = 1;
/**
* Website Scope
*/
public const SCOPE_WEBSITE = 2;
/**
* Store Scope
*/
public const SCOPE_STORE = 0;
/**
* Null Scope
*/
public const SCOPE_NULL = -1;
/**
* Permanent column names.
*
* Names that begins with underscore is not an attribute. This name convention is for
* to avoid interference with same attribute name.
*/
public const COL_STORE = '_store';
/**
* Col Attr Set
*/
public const COL_ATTR_SET = '_attribute_set';
/**
* Col Type
*/
public const COL_TYPE = '_type';
/**
* Col Category
*/
public const COL_CATEGORY = '_category';
/**
* Col Root Category
*/
public const COL_ROOT_CATEGORY = '_root_category';
/**
* Col Sku
*/
public const COL_SKU = 'sku';
/**
* Error codes.
*/
public const ERROR_INVALID_SCOPE = 'invalidScope';
/**
* Error - invalid website
*/
public const ERROR_INVALID_WEBSITE = 'invalidWebsite';
/**
* Error - invalid store
*/
public const ERROR_INVALID_STORE = 'invalidStore';
/**
* Error - invalid attr set
*/
public const ERROR_INVALID_ATTR_SET = 'invalidAttrSet';
/**
* Error - invalid type
*/
public const ERROR_INVALID_TYPE = 'invalidType';
/**
* Error - invalid category
*/
public const ERROR_INVALID_CATEGORY = 'invalidCategory';
/**
* Error - value is required
*/
public const ERROR_VALUE_IS_REQUIRED = 'isRequired';
/**
* Error - type changed
*/
public const ERROR_TYPE_CHANGED = 'typeChanged';
/**
* Error - sku is empty
*/
public const ERROR_SKU_IS_EMPTY = 'skuEmpty';
/**
* Error - no default row
*/
public const ERROR_NO_DEFAULT_ROW = 'noDefaultRow';
/**
* Error - change type
*/
public const ERROR_CHANGE_TYPE = 'changeProductType';
/**
* Error - duplicate scope
*/
public const ERROR_DUPLICATE_SCOPE = 'duplicateScope';
/**
* Error - duplicate sku
*/
public const ERROR_DUPLICATE_SKU = 'duplicateSKU';
/**
* Error - change attr set
*/
public const ERROR_CHANGE_ATTR_SET = 'changeAttrSet';
/**
* Error - type unsupported
*/
public const ERROR_TYPE_UNSUPPORTED = 'productTypeUnsupported';
/**
* Error - row is orphan
*/
public const ERROR_ROW_IS_ORPHAN = 'rowIsOrphan';
/**
* Error - invalid tier price qty
*/
public const ERROR_INVALID_TIER_PRICE_QTY = 'invalidTierPriceOrQty';
/**
* Error - invalid tier price site
*/
public const ERROR_INVALID_TIER_PRICE_SITE = 'tierPriceWebsiteInvalid';
/**
* Error - invalid tier price group
*/
public const ERROR_INVALID_TIER_PRICE_GROUP = 'tierPriceGroupInvalid';
/**
* Error - tier data incomplete
*/
public const ERROR_TIER_DATA_INCOMPLETE = 'tierPriceDataIsIncomplete';
/**
* Error - invalid group price site
*/
public const ERROR_INVALID_GROUP_PRICE_SITE = 'groupPriceWebsiteInvalid';
/**
* Error - invalid group price group
*/
public const ERROR_INVALID_GROUP_PRICE_GROUP = 'groupPriceGroupInvalid';
/**
* Error - group price data incompelte
*/
public const ERROR_GROUP_PRICE_DATA_INCOMPLETE = 'groupPriceDataIsIncomplete';
/**
* Error - sku not found for delete
*/
public const ERROR_SKU_NOT_FOUND_FOR_DELETE = 'skuNotFoundToDelete';
/**
* Error - super products sku not found
*/
public const ERROR_SUPER_PRODUCTS_SKU_NOT_FOUND = 'superProductsSkuNotFound';
/**
* Error - invalid product sku
*/
public const ERROR_INVALID_PRODUCT_SKU = 'invalidSku';
/**
* Pairs of attribute set ID-to-name.
*
* @var array
*/
protected $_attrSetIdToName = [];
/**
* Pairs of attribute set name-to-ID.
*
* @var array
*/
protected $_attrSetNameToId = [];
/**
* Categories text-path to ID hash.
*
* @var array
*/
protected $_categories = [];
/**
* Categories text-path to ID hash with roots checking.
*
* @var array
*/
protected $_categoriesWithRoots = [];
/**
* Customer groups ID-to-name.
*
* @var array
*/
protected $_customerGroups = [];
/**
* Attributes with index (not label) value.
*
* @var array
*/
protected $_indexValueAttributes = [
'status',
'tax_class_id',
'visibility',
'gift_message_available',
'custom_design'
];
/**
* Links attribute name-to-link type ID.
*
* @var array
*/
protected $_linkNameToId = [
'_links_related_' => Mage_Catalog_Model_Product_Link::LINK_TYPE_RELATED,
'_links_crosssell_' => Mage_Catalog_Model_Product_Link::LINK_TYPE_CROSSSELL,
'_links_upsell_' => Mage_Catalog_Model_Product_Link::LINK_TYPE_UPSELL
];
/**
* Validation failure message template definitions
*
* @var array
*/
protected $_messageTemplates = [
self::ERROR_INVALID_SCOPE => 'Invalid value in Scope column',
self::ERROR_INVALID_WEBSITE => 'Invalid value in Website column (website does not exists?)',
self::ERROR_INVALID_STORE => 'Invalid value in Store column (store does not exists?)',
self::ERROR_INVALID_ATTR_SET => 'Invalid value for Attribute Set column (set does not exists?)',
self::ERROR_INVALID_TYPE => 'Product Type is invalid or not supported',
self::ERROR_INVALID_CATEGORY => 'Category does not exists',
self::ERROR_VALUE_IS_REQUIRED => "Required attribute '%s' has an empty value",
self::ERROR_TYPE_CHANGED => 'Trying to change type of existing products',
self::ERROR_SKU_IS_EMPTY => 'SKU is empty',
self::ERROR_NO_DEFAULT_ROW => 'Default values row does not exists',
self::ERROR_CHANGE_TYPE => 'Product type change is not allowed',
self::ERROR_DUPLICATE_SCOPE => 'Duplicate scope',
self::ERROR_DUPLICATE_SKU => 'Duplicate SKU',
self::ERROR_CHANGE_ATTR_SET => 'Product attribute set change is not allowed',
self::ERROR_TYPE_UNSUPPORTED => 'Product type is not supported',
self::ERROR_ROW_IS_ORPHAN => 'Orphan rows that will be skipped due default row errors',
self::ERROR_INVALID_TIER_PRICE_QTY => 'Tier Price data price or quantity value is invalid',
self::ERROR_INVALID_TIER_PRICE_SITE => 'Tier Price data website is invalid',
self::ERROR_INVALID_TIER_PRICE_GROUP => 'Tier Price customer group ID is invalid',
self::ERROR_TIER_DATA_INCOMPLETE => 'Tier Price data is incomplete',
self::ERROR_SKU_NOT_FOUND_FOR_DELETE => 'Product with specified SKU not found',
self::ERROR_SUPER_PRODUCTS_SKU_NOT_FOUND => 'Product with specified super products SKU not found',
self::ERROR_INVALID_PRODUCT_SKU => 'Invalid value in SKU column. HTML tags are not allowed'
];
/**
* Dry-runned products information from import file.
*
* [SKU] => array(
* 'type_id' => (string) product type
* 'attr_set_id' => (int) product attribute set ID
* 'entity_id' => (int) product ID (value for new products will be set after entity save)
* 'attr_set_code' => (string) attribute set code
* )
*
* @var array
*/
protected $_newSku = [];
/**
* Existing products SKU-related information in form of array:
*
* [SKU] => array(
* 'type_id' => (string) product type
* 'attr_set_id' => (int) product attribute set ID
* 'entity_id' => (int) product ID
* 'supported_type' => (bool) is product type supported by current version of import module
* )
*
* @var array
*/
protected $_oldSku = [];
/**
* Column names that holds values with particular meaning.
*
* @var array
*/
protected $_particularAttributes = [
'_store', '_attribute_set', '_type', self::COL_CATEGORY, self::COL_ROOT_CATEGORY, '_product_websites',
'_tier_price_website', '_tier_price_customer_group', '_tier_price_qty', '_tier_price_price',
'_links_related_sku', '_group_price_website', '_group_price_customer_group', '_group_price_price',
'_links_related_position', '_links_crosssell_sku', '_links_crosssell_position', '_links_upsell_sku',
'_links_upsell_position', '_custom_option_store', '_custom_option_type', '_custom_option_title',
'_custom_option_is_required', '_custom_option_price', '_custom_option_sku', '_custom_option_max_characters',
'_custom_option_sort_order', '_custom_option_file_extension', '_custom_option_image_size_x',
'_custom_option_image_size_y', '_custom_option_row_title', '_custom_option_row_price',
'_custom_option_row_sku', '_custom_option_row_sort', '_media_attribute_id', '_media_image', '_media_lable',
'_media_position', '_media_is_disabled'
];
/**
* Column names that holds images files names
*
* @var array
*/
protected $_imagesArrayKeys = [
'_media_image', 'image', 'small_image', 'thumbnail'
];
/**
* Permanent entity columns.
*
* @var array
*/
protected $_permanentAttributes = [self::COL_SKU];
/**
* Array of supported product types as keys with appropriate model object as value.
*
* @var array
*/
protected $_productTypeModels = [];
/**
* All stores code-ID pairs.
*
* @var array
*/
protected $_storeCodeToId = [];
/**
* Store ID to its website stores IDs.
*
* @var array
*/
protected $_storeIdToWebsiteStoreIds = [];
/**
* Website code-to-ID
*
* @var array
*/
protected $_websiteCodeToId = [];
/**
* Website code to store code-to-ID pairs which it consists.
*
* @var array
*/
protected $_websiteCodeToStoreIds = [];
/**
* Media files uploader
*
* @var Mage_ImportExport_Model_Import_Uploader|null
*/
protected $_fileUploader;
/**
* url_key attribute id
*
* @var int
*/
protected $_urlKeyAttributeId;
public function __construct()
{
parent::__construct();
$this->_initWebsites()
->_initStores()
->_initAttributeSets()
->_initTypeModels()
->_initCategories()
->_initSkus()
->_initCustomerGroups();
}
/**
* Delete products.
*
* @return $this
*/
protected function _deleteProducts()
{
$productEntityTable = Mage::getModel('importexport/import_proxy_product_resource')->getEntityTable();
while ($bunch = $this->_dataSourceModel->getNextBunch()) {
$idToDelete = [];
foreach ($bunch as $rowNum => $rowData) {
if ($this->validateRow($rowData, $rowNum) && self::SCOPE_DEFAULT == $this->getRowScope($rowData)) {
$idToDelete[] = $this->_oldSku[$rowData[self::COL_SKU]]['entity_id'];
}
}
if ($idToDelete) {
$this->_connection->query(
$this->_connection->quoteInto(
"DELETE FROM `{$productEntityTable}` WHERE `entity_id` IN (?)",
$idToDelete
)
);
}
}
return $this;
}
/**
* Create Product entity from raw data.
*
* @throws Exception
* @return bool Result of operation.
*/
protected function _importData()
{
if (Mage_ImportExport_Model_Import::BEHAVIOR_DELETE == $this->getBehavior()) {
$this->_deleteProducts();
} else {
$this->_saveProducts();
$this->_saveStockItem();
$this->_saveLinks();
$this->_saveCustomOptions();
foreach ($this->_productTypeModels as $productType => $productTypeModel) {
$productTypeModel->saveData();
}
}
Mage::dispatchEvent('catalog_product_import_finish_before', ['adapter' => $this]);
return true;
}
/**
* Initialize attribute sets code-to-id pairs.
*
* @return $this
*/
protected function _initAttributeSets()
{
foreach (Mage::getResourceModel('eav/entity_attribute_set_collection')
->setEntityTypeFilter($this->_entityTypeId) as $attributeSet
) {
/** @var Mage_Eav_Model_Entity_Attribute_Set $attributeSet */
$this->_attrSetNameToId[$attributeSet->getAttributeSetName()] = $attributeSet->getId();
$this->_attrSetIdToName[$attributeSet->getId()] = $attributeSet->getAttributeSetName();
}
return $this;
}
/**
* Initialize categories text-path to ID hash.
*
* @return $this
*/
protected function _initCategories()
{
$collection = Mage::getResourceModel('catalog/category_collection')->addNameToResult();
/** @var Mage_Catalog_Model_Resource_Category_Collection $collection */
foreach ($collection as $category) {
$structure = explode('/', $category->getPath());
$pathSize = count($structure);
if ($pathSize > 1) {
$path = [];
for ($i = 1; $i < $pathSize; $i++) {
$path[] = $collection->getItemById($structure[$i])->getName();
}
$rootCategoryName = array_shift($path);
if (!isset($this->_categoriesWithRoots[$rootCategoryName])) {
$this->_categoriesWithRoots[$rootCategoryName] = [];
}
$index = implode('/', $path);
$this->_categoriesWithRoots[$rootCategoryName][$index] = $category->getId();
if ($pathSize > 2) {
$this->_categories[$index] = $category->getId();
}
}
}
return $this;
}
/**
* Initialize customer groups.
*
* @return $this
*/
protected function _initCustomerGroups()
{
foreach (Mage::getResourceModel('customer/group_collection') as $customerGroup) {
$this->_customerGroups[$customerGroup->getId()] = true;
}
return $this;
}
/**
* Initialize existent product SKUs.
*
* @return $this
*/
protected function _initSkus()
{
$columns = ['entity_id', 'type_id', 'attribute_set_id', 'sku'];
foreach (Mage::getModel('catalog/product')->getProductEntitiesInfo($columns) as $info) {
$typeId = $info['type_id'];
$sku = $info['sku'];
$this->_oldSku[$sku] = [
'type_id' => $typeId,
'attr_set_id' => $info['attribute_set_id'],
'entity_id' => $info['entity_id'],
'supported_type' => isset($this->_productTypeModels[$typeId])
];
}
return $this;
}
/**
* Initialize stores hash.
*
* @return $this
*/
protected function _initStores()
{
foreach (Mage::app()->getStores() as $store) {
$this->_storeCodeToId[$store->getCode()] = $store->getId();
$this->_storeIdToWebsiteStoreIds[$store->getId()] = $store->getWebsite()->getStoreIds();
}
return $this;
}
/**
* Initialize product type models.
*
* @throws Exception
* @return $this
*/
protected function _initTypeModels()
{
$config = Mage::getConfig()->getNode(self::CONFIG_KEY_PRODUCT_TYPES)->asCanonicalArray();
foreach ($config as $type => $typeModel) {
$model = Mage::getModel($typeModel, [$this, $type]);
if (!$model) {
Mage::throwException("Entity type model '{$typeModel}' is not found");
}
if (!$model instanceof Mage_ImportExport_Model_Import_Entity_Product_Type_Abstract) {
Mage::throwException(
Mage::helper('importexport')->__('Entity type model must be an instance of Mage_ImportExport_Model_Import_Entity_Product_Type_Abstract')
);
}
if ($model->isSuitable()) {
$this->_productTypeModels[$type] = $model;
}
$this->_particularAttributes = array_merge(
$this->_particularAttributes,
$model->getParticularAttributes()
);
}
// remove doubles
$this->_particularAttributes = array_unique($this->_particularAttributes);
return $this;
}
/**
* Initialize website values.
*
* @return $this
*/
protected function _initWebsites()
{
foreach (Mage::app()->getWebsites() as $website) {
$this->_websiteCodeToId[$website->getCode()] = $website->getId();
$this->_websiteCodeToStoreIds[$website->getCode()] = array_flip($website->getStoreCodes());
}
return $this;
}
/**
* Check product category validity.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isProductCategoryValid(array $rowData, $rowNum)
{
$emptyCategory = empty($rowData[self::COL_CATEGORY]);
$emptyRootCategory = empty($rowData[self::COL_ROOT_CATEGORY]);
$hasCategory = $emptyCategory ? false : isset($this->_categories[$rowData[self::COL_CATEGORY]]);
$category = $emptyRootCategory ? null : $this->_categoriesWithRoots[$rowData[self::COL_ROOT_CATEGORY]];
if (!$emptyCategory && !$hasCategory
|| !$emptyRootCategory && !isset($category)
|| !$emptyRootCategory && !$emptyCategory && !isset($category[$rowData[self::COL_CATEGORY]])
) {
$this->addRowError(self::ERROR_INVALID_CATEGORY, $rowNum);
return false;
}
return true;
}
/**
* Check product website belonging.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isProductWebsiteValid(array $rowData, $rowNum)
{
if (!empty($rowData['_product_websites']) && !isset($this->_websiteCodeToId[$rowData['_product_websites']])) {
$this->addRowError(self::ERROR_INVALID_WEBSITE, $rowNum);
return false;
}
return true;
}
/**
* Set valid attribute set and product type to rows with all scopes
* to ensure that existing products doesn't changed.
*
* @param array $rowData
* @return array
*/
protected function _prepareRowForDb(array $rowData)
{
$rowData = parent::_prepareRowForDb($rowData);
static $lastSku = null;
if (Mage_ImportExport_Model_Import::BEHAVIOR_DELETE == $this->getBehavior()) {
return $rowData;
}
if (self::SCOPE_DEFAULT == $this->getRowScope($rowData)) {
$lastSku = $rowData[self::COL_SKU];
}
if (isset($this->_oldSku[$lastSku])) {
$rowData[self::COL_ATTR_SET] = $this->_newSku[$lastSku]['attr_set_code'];
$rowData[self::COL_TYPE] = $this->_newSku[$lastSku]['type_id'];
}
return $rowData;
}
/**
* Check tier price data validity.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isTierPriceValid(array $rowData, $rowNum)
{
if ((isset($rowData['_tier_price_website']) && strlen($rowData['_tier_price_website']))
|| (isset($rowData['_tier_price_customer_group']) && strlen($rowData['_tier_price_customer_group']))
|| (isset($rowData['_tier_price_qty']) && strlen($rowData['_tier_price_qty']))
|| (isset($rowData['_tier_price_price']) && strlen($rowData['_tier_price_price']))
) {
if (!isset($rowData['_tier_price_website']) || !isset($rowData['_tier_price_customer_group'])
|| !isset($rowData['_tier_price_qty']) || !isset($rowData['_tier_price_price'])
|| !strlen($rowData['_tier_price_website']) || !strlen($rowData['_tier_price_customer_group'])
|| !strlen($rowData['_tier_price_qty']) || !strlen($rowData['_tier_price_price'])
) {
$this->addRowError(self::ERROR_TIER_DATA_INCOMPLETE, $rowNum);
return false;
} elseif ($rowData['_tier_price_website'] != self::VALUE_ALL
&& !isset($this->_websiteCodeToId[$rowData['_tier_price_website']])
) {
$this->addRowError(self::ERROR_INVALID_TIER_PRICE_SITE, $rowNum);
return false;
} elseif ($rowData['_tier_price_customer_group'] != self::VALUE_ALL
&& !isset($this->_customerGroups[$rowData['_tier_price_customer_group']])
) {
$this->addRowError(self::ERROR_INVALID_TIER_PRICE_GROUP, $rowNum);
return false;
} elseif ($rowData['_tier_price_qty'] <= 0 || $rowData['_tier_price_price'] <= 0) {
$this->addRowError(self::ERROR_INVALID_TIER_PRICE_QTY, $rowNum);
return false;
}
}
return true;
}
/**
* Check group price data validity.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isGroupPriceValid(array $rowData, $rowNum)
{
if ((isset($rowData['_group_price_website']) && strlen($rowData['_group_price_website']))
|| (isset($rowData['_group_price_customer_group']) && strlen($rowData['_group_price_customer_group']))
|| (isset($rowData['_group_price_price']) && strlen($rowData['_group_price_price']))
) {
if (!isset($rowData['_group_price_website']) || !isset($rowData['_group_price_customer_group'])
|| !strlen($rowData['_group_price_website']) || !strlen($rowData['_group_price_customer_group'])
|| !strlen($rowData['_group_price_price'])
) {
$this->addRowError(self::ERROR_GROUP_PRICE_DATA_INCOMPLETE, $rowNum);
return false;
} elseif ($rowData['_group_price_website'] != self::VALUE_ALL
&& !isset($this->_websiteCodeToId[$rowData['_group_price_website']])
) {
$this->addRowError(self::ERROR_INVALID_GROUP_PRICE_SITE, $rowNum);
return false;
} elseif ($rowData['_group_price_customer_group'] != self::VALUE_ALL
&& !isset($this->_customerGroups[$rowData['_group_price_customer_group']])
) {
$this->addRowError(self::ERROR_INVALID_GROUP_PRICE_GROUP, $rowNum);
return false;
}
}
return true;
}
/**
* Check super products SKU
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isSuperProductsSkuValid($rowData, $rowNum)
{
if (!empty($rowData['_super_products_sku'])
&& (
!isset($this->_oldSku[$rowData['_super_products_sku']])
&& !isset($this->_newSku[$rowData['_super_products_sku']])
)
) {
$this->addRowError(self::ERROR_SUPER_PRODUCTS_SKU_NOT_FOUND, $rowNum);
return false;
}
return true;
}
/**
* Check product sku data.
*
* @param array $rowData
* @param int $rowNum
* @return bool
*/
protected function _isProductSkuValid(array $rowData, $rowNum)
{
if (isset($rowData['sku']) && $rowData['sku'] != Mage::helper('core')->stripTags($rowData['sku'])) {
$this->addRowError(self::ERROR_INVALID_PRODUCT_SKU, $rowNum);
return false;
}
return true;
}
/**
* Custom options save.
*
* @return $this
*/
protected function _saveCustomOptions()
{
/** @var Mage_Core_Model_Resource $coreResource */
$coreResource = Mage::getSingleton('core/resource');
$productTable = $coreResource->getTableName('catalog/product');
$optionTable = $coreResource->getTableName('catalog/product_option');
$priceTable = $coreResource->getTableName('catalog/product_option_price');
$titleTable = $coreResource->getTableName('catalog/product_option_title');
$typePriceTable = $coreResource->getTableName('catalog/product_option_type_price');
$typeTitleTable = $coreResource->getTableName('catalog/product_option_type_title');
$typeValueTable = $coreResource->getTableName('catalog/product_option_type_value');
/** @var Mage_ImportExport_Model_Resource_Helper_Mysql4 $helper */
$helper = Mage::getResourceHelper('importexport');
$nextOptionId = $helper->getNextAutoincrement($optionTable);
$nextValueId = $helper->getNextAutoincrement($typeValueTable);
$priceIsGlobal = Mage::helper('catalog')->isPriceGlobal();
$type = null;
$typeSpecific = [
'date' => ['price', 'sku'],
'date_time' => ['price', 'sku'],
'time' => ['price', 'sku'],
'field' => ['price', 'sku', 'max_characters'],
'area' => ['price', 'sku', 'max_characters'],
//'file' => array('price', 'sku', 'file_extension', 'image_size_x', 'image_size_y'),
'drop_down' => true,
'radio' => true,
'checkbox' => true,
'multiple' => true
];
$alreadyUsedProductIds = [];
$lastStoreId = null;
$lastProductId = null;
$currentValueId = null;
while ($bunch = $this->_dataSourceModel->getNextBunch()) {
$customOptions = [
'product_id' => [],
$optionTable => [],
$priceTable => [],
$titleTable => [],
$typePriceTable => [],
$typeTitleTable => [],
$typeValueTable => []
];
$flagNewOption = true;
$firstKeyOption = null;
foreach ($bunch as $rowNum => $rowData) {
$this->_filterRowData($rowData);
if (!$this->isRowAllowedToImport($rowData, $rowNum)) {
continue;
}
if (self::SCOPE_DEFAULT == $this->getRowScope($rowData)) {
$productId = $this->_newSku[$rowData[self::COL_SKU]]['entity_id'];
} elseif (!isset($productId)) {
continue;
}
if ($lastProductId != $productId) {
$lastStoreId = Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;
$currentValueId = null;
$lastProductId = $productId;
}
if (!empty($rowData['_custom_option_store'])) {
if (!isset($this->_storeCodeToId[$rowData['_custom_option_store']])) {
continue;
}
$storeId = $this->_storeCodeToId[$rowData['_custom_option_store']];
} else {
$storeId = Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;
}
if (!empty($rowData['_custom_option_type'])) { // get CO type if its specified
if (!isset($typeSpecific[$rowData['_custom_option_type']])) {
$type = null;
continue;
}
$type = $rowData['_custom_option_type'];
$rowIsMain = true;
} else {
if ($type === null) {
continue;
}
$rowIsMain = false;
}
if (!isset($customOptions['product_id'][$productId])) { // for update product entity table
$customOptions['product_id'][$productId] = [
'entity_id' => $productId,
'has_options' => 0,
'required_options' => 0,
'updated_at' => Varien_Date::now()
];
}
if ($rowIsMain) {
$solidParams = [
'option_id' => $nextOptionId,
'sku' => '',
'max_characters' => 0,
'file_extension' => null,
'image_size_x' => 0,
'image_size_y' => 0,
'product_id' => $productId,
'type' => $type,
'is_require' => empty($rowData['_custom_option_is_required']) ? 0 : 1,
'sort_order' => empty($rowData['_custom_option_sort_order'])
? 0 : abs($rowData['_custom_option_sort_order'])
];
if ($typeSpecific[$type] !== true) { // simple option may have optional params
$priceTableRow = [
'option_id' => $nextOptionId,
'store_id' => Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID,
'price' => 0,
'price_type' => 'fixed'
];
foreach ($typeSpecific[$type] as $paramSuffix) {
$optionSuffix = '_custom_option_' . $paramSuffix;
if (isset($rowData[$optionSuffix])) {
$data = $rowData[$optionSuffix];
if (array_key_exists($paramSuffix, $solidParams)) {
$solidParams[$paramSuffix] = $data;
} elseif ($paramSuffix === 'price') {
if (substr($data, -1) === '%') {
$priceTableRow['price_type'] = 'percent';
}
$priceTableRow['price'] = (float) rtrim($data, '%');
}
}
}
$customOptions[$priceTable][] = $priceTableRow;
}
$customOptions[$optionTable][] = $solidParams;
$customOptions['product_id'][$productId]['has_options'] = 1;
if (!empty($rowData['_custom_option_is_required'])) {
$customOptions['product_id'][$productId]['required_options'] = 1;
}
$prevOptionId = $nextOptionId++; // increment option id, but preserve value for $typeValueTable
}
if ($typeSpecific[$type] === true && !empty($rowData['_custom_option_row_title'])) {
if (empty($rowData['_custom_option_store'])) {
// complex CO option row
$customOptions[$typeValueTable][$prevOptionId][] = [
'option_type_id' => $nextValueId,
'sort_order' => empty($rowData['_custom_option_row_sort'])
? 0 : abs($rowData['_custom_option_row_sort']),
'sku' => !empty($rowData['_custom_option_row_sku'])
? $rowData['_custom_option_row_sku'] : ''
];
if (!isset($customOptions[$typeTitleTable][$nextValueId][0])) { // ensure default title is set
$customOptions[$typeTitleTable][$nextValueId][0] = $rowData['_custom_option_row_title'];
}
$customOptions[$typeTitleTable][$nextValueId][$storeId] = $rowData['_custom_option_row_title'];
if (!empty($rowData['_custom_option_row_price'])) {
$typePriceRow = [
'price' => (float) rtrim($rowData['_custom_option_row_price'], '%'),
'price_type' => 'fixed'
];
if (substr($rowData['_custom_option_row_price'], -1) === '%') {
$typePriceRow['price_type'] = 'percent';
}
if ($priceIsGlobal) {
$customOptions[$typePriceTable][$nextValueId][0] = $typePriceRow;
} else {
// ensure default price is set
if (!isset($customOptions[$typePriceTable][$nextValueId][0])) {
$customOptions[$typePriceTable][$nextValueId][0] = $typePriceRow;
}
$customOptions[$typePriceTable][$nextValueId][$storeId] = $typePriceRow;
}
}
if ($flagNewOption) {
$firstKeyOption = $nextValueId;
$flagNewOption = false;
}
$nextValueId++;
} else {
$flagNewOption = true;
if ($lastStoreId != $storeId) {
if (!$firstKeyOption) {
reset($customOptions[$typeTitleTable]);
$firstKeyOption = key($customOptions[$typeTitleTable]);
}
$currentValueId = $firstKeyOption;
$lastStoreId = $storeId;
} else {