Product import
Overview
For the import of products, the plugin provides a generic import pipeline as of version 3.0.0. It handles variants, properties, visibilities, rule prices, translations and the product extension and is adapted to the project via hooks. A custom product module therefore no longer has to be built from scratch (see "Register a new module"). The matching export is created by the ProductAdapterAbstract of the Pimcore bundle (see "Build a product export").
All classes are located in the namespace Twocream\JsonImporter\Core\System\Import\Module\Product.
| Class | Package | Registered by the plugin | Description |
|---|---|---|---|
AbstractProductModule | – | – | Abstract base class for product modules with helper methods for existing products, taxes, currencies, units, manufacturers, stale relations and the deactivation of products |
ProductModule | products | no | Generic import pipeline for products and variants |
CrossSellingModule | cross-selling | yes | Import of the cross-selling |
CategoryAssignmentModule | category-assignments | yes | Assignment of the products to the categories, see Category assignments |
The ProductModule is not registered by the plugin. It has to be registered in the project, either directly or via a subclass. Without a registered module, the import of a file with the package products fails with the message Detected unknown package "products".
Answers to frequently asked questions about error cases and the behaviour of the import (too long texts, invalid values, product number conflicts, skipped batches, deactivation and reactivation, manufacturers, delivery times and more) can be found on the page "Product import: FAQ".
Registering the product module
Project-specific product modules should inherit from the following class: Twocream\JsonImporter\Core\System\Import\Module\Product\ProductModule
Without adjustments, no visibilities and no rule prices are written, as the markets of the JSON cannot be assigned to a sales channel or a rule automatically. For this purpose, the hooks getSalesChannelIdByMarket() and getRuleIdByMarket() have to be implemented:
Implement the hooks before the first import. As relations always mirror the import file (see State synchronisation), the default implementations (null) remove all existing visibilities and rule prices of the imported products.
<?php
namespace MyCustomExtension\Core\System\Import\Module\Product;
use Twocream\JsonImporter\Core\System\Import\Module\Product\ProductModule as BaseProductModule;
class ProductModule extends BaseProductModule
{
protected function getSalesChannelIdByMarket(string $market): ?string
{
return [
'shop' => '0190c5e4d1ef7c6a9a1c2b8e6f3d4a51',
][$market] ?? null;
}
protected function getRuleIdByMarket(string $market): ?string
{
return $market === 'shop' ? '0190c5e4d1ef7c6a9a1c2b8e6f3d4a52' : null;
}
}
The module is registered like every other module with the service tag twocream_json_importer.module (see "Register the module"):
<service id="MyCustomExtension\Core\System\Import\Module\Product\ProductModule" autowire="true">
<tag name="twocream_json_importer.module"/>
</service>
The constructor is the one of AbstractSyncModule (SyncService, EventDispatcherInterface, Connection, DefinitionInstanceRegistry, ModuleService).
If several modules handle the same package, the module registered first is used. Therefore, only one module may be registered for the package products.
Classes and usage in the project
Class overview
The product import is built on the following classes (namespace Twocream\JsonImporter\Core\System\Import\…). A project usually only extends the ProductModule, the methods of the base classes are available in it.
| Class | Namespace | Responsibility |
|---|---|---|
AbstractModule | Module | import() = resetReport(), validate() (validateEntry() per entry, invalid entries are skipped with a warning) and doImport() (deletions, store(), report). Report helpers (getReport(), setReportLogger(), reportRecord()), helpers of the pre-check (sanitizePayload(), toInt(), toFloat(), toBool(), parseDate()), isIdExist(), checkDamImage(), prepareRelations() |
AbstractSyncModule | Module | Writes the operations collected in $syncs via the Shopware sync service: sync(), syncBatchSafely() (batch-wise partial import), getSkippedRecordIds(), resetCachesAfterFailedBatch(), cleanupRelations(), getIndexingBehavior(), getSkipIndexers() |
AbstractProductModule | Module\Product | Base class of the product modules: validation of uuid, id, tax and translations, caches per import (resetImportCaches()), existing products, taxes, currencies, units, delivery times, manufacturers, stale relations and the deactivation (never deletion) including the hook cleanupDeactivatedProducts() |
ProductModule | Module\Product | Generic pipeline for the package products: batches, product number check, variants, properties, visibilities, rule prices, options, configurator settings, translations, product extension, moving of variants and pre-check. Not registered by the plugin |
PayloadSanitizer | Validation | Checks a write payload against the DAL definition before the sync: truncates too long texts, removes invalid values and drops nested entries with an invalid required value. Static helpers toInt(), toFloat(), toBool(), parseDate(), isValidGtin(), truncate() and describeValue() |
The plugin does not create its own tables for ID mappings. The UUID of every entry equals md5(<Pimcore ID>) and is delivered by the source system.
Lifecycle of an import
An import file is handled package by package (sorted by getPackageDependencies()). For the package products, the import runs as follows:
JsonFileHandler
└─ setReportLogger($logger), import($package) chapter is written to the journal, also on exceptions
├─ resetReport() new, empty chapter per file
├─ validate()
│ ├─ resetImportCaches() existing IDs, taxes, currencies, units,
│ │ delivery times, manufacturers
│ └─ validateEntry() per entry missing/invalid required data => entry skipped
│ (WARNING), deletion entries are not validated
└─ doImport()
├─ collect deletion entries (.meta.deleted)
├─ store(): per getBatchSize() (75) main/simple products => storeBatch()
│ ├─ filterProductNumberConflicts() product number of another UUID => skipped
│ │ (number of a delivered product not written yet =>
│ │ deferred, checked again once after all batches)
│ ├─ syncProduct() per entry, recursively for its valid variants
│ │ ├─ prepareVariants() validateEntry() per variant
│ │ ├─ prepareVariantListingConfig() variant-listing-config of main products
│ │ ├─ fetchExistingProduct() + extendCriteriaForExistingProductFetch()
│ │ ├─ prepareRelations(properties), prepareVisibilities(), preparePrices(),
│ │ │ options (variants), prepareVariantOptions()
│ │ ├─ cleanupExistingProduct(), deleteStaleProductOptions(), deleteStaleConfiguratorSettings()
│ │ ├─ prepareProductData() fields, tax, manufacturer, unit, delivery time,
│ │ │ preparePurchasePrices(), prepareCanonicalProduct(),
│ │ │ prepareCmsPage(), prepareFeatureSet(),
│ │ │ price, stock, prepareCustomFields(),
│ │ │ getAdditionalProductData(),
│ │ │ getProductExtensionData()
│ │ ├─ cleanupAdditionalRelations()
│ │ └─ sanitizeProductData() truncate / remove invalid values (WARNING)
│ ├─ sync of the batch (syncBatchSafely) failure: rollback, ERROR, next batch
│ │ └─ index previous main products of moved products again, INFO per move
│ └─ writeCanonicalProducts() after all batches: canonicalProductId of the
│ written products (syncBatchSafely)
└─ deactivateProducts(deletion entries, stale variants) blocks of 100: active = false, remove own
visibilities, cleanupDeactivatedProducts()
Pipeline steps
The products are written in batches via the Shopware sync service. For each product, syncProduct(array $data, ?string $parentId = null): void is called, which then processes the valid variants recursively. Every step can be overridden:
| Step | Signature | Default |
|---|---|---|
| Batch | storeBatch(array $records): ?EntityWrittenContainerEvent | Product number check, syncProduct() per entry, sync of the batch |
| Product numbers | filterProductNumberConflicts(array $records): array | Removes entries whose product number belongs to another UUID (file or Shopware) with a warning. Entries whose number would be released by a delivered product that is not written yet are deferred and checked again once after all batches |
| Variants | prepareVariants(array $data, ?string $parentId): array | [allVariantIds, validVariants, variantListingConfig] |
| Variant listing | prepareVariantListingConfig(array $data, ?string $parentId, array $validVariants, ?array $variantListingConfig): ?array | Delivered keys of variant-listing-config over the default of prepareVariants() (displayParent: true, no mainVariantId, no configuratorGroupConfig; helpers findValidVariantId($variant, array $validVariants): ?string and prepareConfiguratorGroupConfig($groups, string $contextId, string $recordInfo): array), see Variant listing |
| Variant options | prepareVariantOptions(array $data, array $validVariants): array | Configurator settings with the option ID as key |
| Visibilities | prepareVisibilities(array $data): array | Visibilities with the sales channel ID as key |
| Rule prices | preparePrices(array $data, ?string $parentId = null, ?ProductEntity $product = null): array | Rule prices with the price ID as key, gross calculated from net and tax (tax rate of a variant see Variant inheritance). IDs of rule prices with an invalid value or an unknown tax rate are added to $keptRulePriceIds (kept by cleanupExistingProduct()) |
| Custom fields | prepareCustomFields(array $data, ?string $parentId, bool $exists): array | Custom fields per language ID (see Custom fields), written into translations.<languageId>.customFields by prepareProductData() |
| Cleanup | cleanupExistingProduct(ProductEntity $product, array $data, array $propertyIds, array &$visibilities, array $prices, array $allVariantIds): void | Deletes all relations that are not part of the entry and collects stale variants for deactivation |
| Product data | prepareProductData(array $data, ?string $parentId, array $context): array | Data written for the product |
| Purchase price | preparePurchasePrices(array $data, ?string $parentId): array | purchasePrices of purchase-price ([] = not written) |
| Canonical product | prepareCanonicalProduct(array $data, ?string $parentId): array | canonicalProductId: null for null/""/[], a valid UUID is collected for writeCanonicalProducts() ([] = not written now) |
| CMS page | prepareCmsPage(array $data, ?string $parentId): array | cmsPageId of an existing layout of the type PRODUCT_CMS_PAGE_TYPE (product_detail) |
| Feature set | prepareFeatureSet(array $data, ?string $parentId): array | featureSetId of an existing feature set |
| Canonical products | writeCanonicalProducts(): void | After all batches: one update {id, canonicalProductId} per written product whose canonical product is written in this import or exists in Shopware and is not deactivated in this import, in chunks of getBatchSize() via syncBatchSafely(), see Canonical product |
| Pre-check | sanitizeProductData(array $productData, array $data, ?string $parentId): array | PayloadSanitizer, check of maxPurchase and the EAN |
The array $context of prepareProductData() contains the results of the previous steps: exists, detached (bool, an existing variant becomes a standalone product), existingStock (?int), variantListingConfig (?array) as well as propertyIds, visibilities, prices, optionIds and configuratorSettings (arrays that are always written, also when empty).
A main product with the key variants but without a valid variant is skipped and reported with the warning Product is a represent but has no valid variant. Its variants that are no longer delivered are deactivated anyway, the product itself and its delivered variants remain unchanged.
Hooks and helper methods
All hooks are protected and can be overridden in the product module of the project. Call parent:: where the default already does work.
| Hook | Class | Default | Description |
|---|---|---|---|
getSalesChannelIdByMarket(string $market): ?string | ProductModule | null | Sales channel of a market in visibilities, null = warning, the visibility is not linked |
getRuleIdByMarket(string $market): ?string | ProductModule | null | Rule of a market in prices, null = warning, the rule price is not linked. The rule must exist in Shopware |
reportUnresolvedMarket(array $data, string $market, string $area): void | ProductModule | Warning | Reports a market that cannot be resolved ($area is visibility or price) |
getAdditionalProductData(array $data, ?string $parentId): array | ProductModule | [] | Additional fields that are merged into the product data (pre-checked afterwards). translations (keyed by language ID) are merged per language and field, translations.<languageId>.customFields per key – names and custom fields of the import are kept unless the hook returns the same field |
writeUnlocalizedCustomFieldsToAllLanguages(): bool | ProductModule | true | Values of custom-fields are written to all languages of the shop, false = system language only |
getManagedCustomFieldSets(): array | ProductModule | [] | Names of custom field sets whose keys are removed per language if they are not delivered |
convertCustomFieldValue(array $customField, $value) | AbstractProductModule | conversion by type | Converts a delivered value (never null) to the type of the custom field, null = invalid (reported, not written) |
getProductExtensionData(array $data): ?array | ProductModule | built from the two maps, null without maps, without product-extension or without any delivered mapped key | Data of the product extension, null = no product extension is written |
getProductExtensionFieldMap(): array | ProductModule | [] | Key in product-extension => field of the product extension, only written if the key is delivered |
getProductExtensionTranslationKeyMap(): array | ProductModule | [] | Key in product-extension.translations.<locale> => translated field of the product extension |
cleanupAdditionalRelations(ProductEntity $product, array $data): void | ProductModule | – | Cleanup of custom relations to the state of the entry, called after prepareProductData() |
getProductFieldMap(): array | ProductModule | see below | Mapping of JSON key to Shopware field for simple fields |
getProductTranslationKeyMap(): array | ProductModule | see below | Mapping of JSON key to Shopware field for translations |
getBatchSize(): int | ProductModule | 75 | Number of main or simple products per sync batch (including their variants) |
getProductNumberMaxLength(): int | ProductModule | Limit of the DAL definition (64) | Longer product numbers skip the entry |
normalizeProductNumber($productNumber): ?string | ProductModule | trim + lower case | Comparison of product numbers in the conflict check |
sanitizeProductData(array $productData, array $data, ?string $parentId): array | ProductModule | see Pipeline steps | Pre-check of every product and variant row |
getRecordReportContext(array $data, ?string $parentId): array | ProductModule | [readable ID, '(ID: "…")'], variants in the context of the main product | Context of the report messages of an entry |
extendCriteriaForExistingProductFetch(Criteria $criteria): void | AbstractProductModule | – | Additional associations when loading an existing product |
fetchReadableId(string $productId): string | AbstractProductModule | Pimcore ID of the product extension, product number or UUID | ID reported for products without their own entry (e.g. stale variants) |
fetchReadableIds(array $productIds): array | AbstractProductModule | like fetchReadableId(), one query per table; an override of fetchReadableId() is used per ID | Readable IDs of a deactivation block |
cleanupDeactivatedProducts(array $productIds): void | AbstractProductModule | – | Further cleanup of deactivated products (blocks of at most 100 IDs, also already inactive products – must be idempotent) |
getManufacturerMediaId(array $manufacturer, bool $exists): ?string | AbstractProductModule | null | Media ID of the manufacturer image ($manufacturer = delivered structure including id), null or '' = image remains unchanged |
getOrCreateManufacturerIdByName(string $manufacturer, ?string $defaultManufacturerId = null): ?string | AbstractProductModule | calls getOrCreateManufacturerId() | Manufacturers delivered as name |
getOrCreateManufacturerId(string|array $manufacturer, ?string $defaultManufacturerId = null, string $contextId = '', string $recordInfo = ''): ?string | AbstractProductModule | create only, ID md5('manufacturer-' . <name>) | Manufacturers delivered as object (and default for names) |
resolveDeliveryTimeId(string|array $deliveryTime, string $contextId = '', string $recordInfo = ''): ?string | AbstractProductModule | UUID or {min, max, unit} | Delivery time of delivery-time, null = not written |
generateDeliveryTimeName(int $min, int $max, string $unit): string | AbstractProductModule | 1 day, 1-3 days, 2 weeks | Name of a new delivery time without a name in the system language |
resetImportCaches(): void | AbstractProductModule | Resets the caches | Reset own caches per import (call parent::) |
resetCachesAfterFailedBatch(): void | AbstractSyncModule | Resets existing IDs (product modules additionally units, delivery times, manufacturers) | Reset own caches of entities that were queued in a rolled-back batch (call parent::) |
getIndexingBehavior(): ?string / getSkipIndexers(): array | AbstractSyncModule | Indexing queue / [] | Indexing of the sync |
By default, the following simple fields are written: product-number, ean, manufacturer-number, active, is-closeout, shipping-free, min-purchase, max-purchase, purchase-steps, purchase-unit, reference-unit, restock-time, mark-as-topseller, length, width, height, weight and release-date. In addition, tax (as taxId), manufacturer (as manufacturerId, created if missing), unit (as unitId, created if missing), delivery-time (as deliveryTimeId), price (default currency), purchase-price (as purchasePrices, default currency), canonical-product (as canonicalProductId), cms-page (as cmsPageId), feature-set (as featureSetId), variant-listing-config (as variantListingConfig, main products), stock and translations are written.
For translations, the keys name, description, custom-search-keywords, keywords, meta-title, meta-description, pack-unit and pack-unit-plural are adopted by default. Other keys are ignored, but can be added via getProductTranslationKeyMap().
Helper methods
The following methods are final protected and are available in every product module:
| Name | Class | Description |
|---|---|---|
fetchExistingProduct(string $id): ?ProductEntity | AbstractProductModule | Loads an existing product including the associations required for the comparison |
fetchTaxId(float $tax): ?string | AbstractProductModule | Determines the tax for the tax rate (tolerance TAX_RATE_TOLERANCE = 0.001), taxes are never created |
fetchCmsPageType(string $cmsPageId): ?string | AbstractProductModule | Type of an existing CMS layout (loaded once per import), null = not available |
collectProductIdsToDeactivate(array $productIds): array | AbstractProductModule | Ids of the given products that deactivateProducts() deactivates after the batches (deleted entries, variants of deleted main products, stale variants) |
fetchCurrencyId(string $currencyIsoCode): ?string | AbstractProductModule | Determines the currency for the ISO code |
fetchUnitId(string $unit): ?string | AbstractProductModule | Determines the unit md5('unit-' . $unit) and creates it if missing |
deleteStaleProductProperties(ProductEntity $product, array $propertyIds = []): void | AbstractProductModule | Deletes properties that are no longer delivered |
deleteStaleProductVisibilities(ProductEntity $product, array &$visibilities = []): void | AbstractProductModule | Deletes visibilities that are no longer delivered |
deleteStaleProductOptions(ProductEntity $product, array $optionIds = []): void | AbstractProductModule | Deletes variant options that are no longer delivered |
deleteStaleConfiguratorSettings(ProductEntity $product, array &$configuratorSettings = []): void | AbstractProductModule | Deletes configurator settings that are no longer needed |
deactivateProducts(array $deactivations, array $staleVariantIds = []): void | AbstractProductModule | Deactivates products in blocks of 100 (active = false, remove own visibilities, hook) and reports them |
retainProducts(array $productIds): void | AbstractProductModule | Protects delivered but not written products from the deactivation as stale |
removeProductVisibilities(array $productIds): void | AbstractProductModule | Removes the own visibilities of the products |
removeCrossSellingAssignments(array $productIds): void | AbstractProductModule | Removes the own cross-sellings of the products and the products from other cross-sellings, other cross-sellings without assigned products are deactivated |
removeCategoryAssignments(array $productIds): void | AbstractProductModule | Removes the category assignments of the products |
fetchProductIdsByProductNumbers(array $productNumbers): array | ProductModule | Normalised product number => UUID in Shopware (one query) |
fetchExistingOptionIds(array $productIds): array | ProductModule | Determines the variant options of the products that exist in Shopware |
getRelationList(array $data, string $key): array | ProductModule | Returns the list of a relation, a missing key results in an empty list |
getProductCustomFields(): array | AbstractProductModule | Active custom fields of the sets related to products (technical name => type, config, set), loaded once per import |
getCustomFieldOptionValues(array $customField): array | AbstractProductModule | Configured option values of a select field ([] = no options configured) |
isMainProduct(array $data): bool | ProductModule | Checks whether the entry is a main product, i.e. has the key variants |
collectStaleVariantIds(ProductEntity $product, array $allVariantIds): void | ProductModule | Collects existing variants that are not delivered for deactivation |
The deletion and cleanup helpers do not write themselves, they queue sync operations in $syncs. Within cleanupDeactivatedProducts(), these operations are written together with the deactivation of the block.
Further helper methods
| Name | Class | Description |
|---|---|---|
reportRecord(string $level, string $readableId, string $message): void | AbstractModule | Message for an entry in the report (Psr\Log\LogLevel::*) |
sanitizePayload(string $entityName, array $row, string $contextId, string $recordInfo = ''): array | AbstractModule | Pre-check of a row with the PayloadSanitizer, each change is reported as a warning |
getPayloadSanitizer(): PayloadSanitizer | AbstractModule | Instance of the PayloadSanitizer (can be overridden for own value ranges) |
toInt($value): ?int, toFloat($value): ?float, toBool($value): ?bool | AbstractModule | Converts values, null = invalid |
parseDate($value, array $formats = PayloadSanitizer::DEFAULT_DATE_FORMATS): ?string | AbstractModule | Converts a date to Y-m-d\TH:i:sP, null = invalid |
isIdExist(string $id, string $entityName): bool | AbstractModule | Checks whether an ID exists (all IDs of the entity are loaded once per import) |
checkDamImage(?array $image, string $contextId, string $entityName): ?string | AbstractModule | Checks an image {id, uuid}, a missing image is reported as a warning |
syncBatchSafely(array $readableIds, array $additionalReadableIds = [], ?bool &$failed = null, bool $rememberSkipped = true): ?EntityWrittenContainerEvent | AbstractSyncModule | Writes $syncs, a failed batch is skipped and reported as an error |
getSkippedRecordIds(): array | AbstractSyncModule | UUID => readable ID of the entries of skipped batches of the current import |
Example
The following product module of a project maps the markets, adds an own field, writes the product extension, sets the manufacturer image and removes deactivated products from categories and cross-sellings:
<?php
namespace MyCustomExtension\Core\System\Import\Module\Product;
use Shopware\Core\Content\Media\MediaDefinition;
use Twocream\JsonImporter\Core\System\Import\Module\Product\ProductModule as BaseProductModule;
class ProductModule extends BaseProductModule
{
private const SALES_CHANNEL_IDS = [
'shop' => '0190c5e4d1ef7c6a9a1c2b8e6f3d4a51',
'b2b' => '0190c5e4d1ef7c6a9a1c2b8e6f3d4a54',
];
private const RULE_IDS = [
'b2b' => '0190c5e4d1ef7c6a9a1c2b8e6f3d4a52',
];
protected function getSalesChannelIdByMarket(string $market): ?string
{
return self::SALES_CHANNEL_IDS[$market] ?? null;
}
protected function getRuleIdByMarket(string $market): ?string
{
return self::RULE_IDS[$market] ?? null;
}
protected function reportUnresolvedMarket(array $data, string $market, string $area): void
{
// The market "shop" uses the default price, a rule price is not supported on purpose
if ($area === 'price' && $market === 'shop') {
return;
}
parent::reportUnresolvedMarket($data, $market, $area);
}
protected function getProductFieldMap(): array
{
// The export delivers the topseller flag with an own key
return parent::getProductFieldMap() + ['topseller' => 'markAsTopseller'];
}
protected function getAdditionalProductData(array $data, ?string $parentId): array
{
if (!array_key_exists('bulky', $data)) {
return [];
}
// Pre-checked afterwards like all other fields
return ['shippingFree' => $data['bulky'] === null ? null : !$data['bulky']];
}
protected function getManagedCustomFieldSets(): array
{
// Keys of this set that are not delivered for a product are removed
return ['acme_product'];
}
protected function getProductExtensionFieldMap(): array
{
return ['business-area' => 'businessArea'];
}
protected function getProductExtensionTranslationKeyMap(): array
{
return ['subtitle' => 'subtitle'];
}
protected function getManufacturerMediaId(array $manufacturer, bool $exists): ?string
{
// {"name": "ACME", "logo": {"id": 4711, "uuid": "..."}} - the image must already exist in Shopware,
// null keeps the current image (e.g. maintained in the administration)
return $this->checkDamImage(
is_array($manufacturer['logo'] ?? null) ? $manufacturer['logo'] : null,
(string) $manufacturer['name'],
MediaDefinition::ENTITY_NAME
);
}
protected function cleanupDeactivatedProducts(array $productIds): void
{
// Deactivated products are removed from categories and cross-sellings. They only come back if the
// packages "category-assignments" and "cross-selling" deliver them again
$this->removeCategoryAssignments($productIds);
$this->removeCrossSellingAssignments($productIds);
}
}
What cleanupDeactivatedProducts() removes is not restored automatically on reactivation. Categories and cross-sellings only come back if the packages category-assignments or cross-selling deliver the affected entries again – with delta exports this is usually not the case. The hook is therefore empty by default.
State synchronisation
The source system is always leading for products. Products must therefore not be maintained in the administration, changes of relations are lost with the next import.
- Relations always mirror the import file: For every imported entry,
properties,visibilities,prices(rule prices),options(variants), the configurator settings (main product) and the variants are synced to exactly the state of the entry. A missing key is handled like an empty list ([]), all existing relations of that kind are removed – e.g. an entry withoutvisibilitiesremoves all visibilities of the product. This applies to variants as well: a variant withoutproperties,visibilitiesorpricesloses its own entries and then inherits the values of its main product (Shopware inheritance) - Unresolvable references are reported and not linked: Markets that cannot be resolved via the hooks (reported via
reportUnresolvedMarket()), unknown currencies as well as properties and variant options that do not exist in Shopware are reported as a warning per reference. Existing relations that are not part of the resolved set are removed anyway – e.g. if none of the markets ofvisibilitiescan be resolved, all visibilities of the product are removed. A market ofpriceswithoutnetorcurrencyis skipped without a warning, its existing rule price is removed. A delivered rule price with an invalid value (netnot numeric or negative), however, is reported as a warning and the existing rule price of the market remains unchanged (it is not removed) - Simple fields are only written if their key is delivered: Missing keys are not written, existing values in Shopware remain unchanged. An explicitly delivered
nullof a simple field, however, is written (except forstock).stockis only set to0when a product is created and no valid stock is delivered. An explicit"stock": nullis handled like a missing key (0on create, nothing is written on update).translationsare only written if delivered and are handled like simple fields per language – translations of languages that are no longer delivered are kept - Custom fields are written per delivered key (see Custom fields): keys that are not delivered are kept,
nullremoves the own value. Only the sets ofgetManagedCustomFieldSets()are synced to the state of the entry, keys of other sets and of other plugins are never changed - Variants inherit: values of a variant that are delivered as
nullor[]are inherited from its main product (see Variant inheritance) - Variants: Existing variants of a product that are not part of
variantsare deactivated after the import. Variants that are moved in the same import are excluded (see below). A missing keyvariantsandvariants: []deactivate the same (stale) variants. The difference is the product itself: an entry without the keyvariantsis a simple product and is imported normally, a main product withvariants(also[]) but without a valid variant is skipped with a warning - Moving variants: A product always gets the main product of its entry. An existing variant that is delivered as a top-level entry (main product or simple product) is detached from its previous main product. A variant that is delivered under another main product is moved to it (an existing simple product that is delivered as a variant is assigned to the main product). Delivered entries are never deactivated as a stale variant of their previous main product, even if that product is imported in the same file (before or after, in any batch). The previous main product is indexed again (variant count, variant listing, cheapest price) and each move is reported as an info message in the report (
Product %s was moved from parent %s to %s,Product %s was detached from parent %s,Product %s was assigned to parent %s)- A detached variant loses its options (top-level products have none) and has to deliver its complete data because it no longer inherits from its previous main product – Shopware validates the required fields as on create. An existing stock (
stock) is kept if nostockis delivered - Without the key
active, a detached variant is written as active (true) and a moved variant as inheriting (null). A variant that was deactivated as stale in an earlier import is therefore reactivated. An explicitly deliveredactive: nullof a detached variant is written – the product is then not active - The configurator settings of the previous main product are only updated with the next import of that main product
- A main product without a valid variant is not written (see above). An existing variant that is delivered this way is therefore not moved – it remains unchanged at its previous main product and is not deactivated
- A detached variant loses its options (top-level products have none) and has to deliver its complete data because it no longer inherits from its previous main product – Shopware validates the required fields as on create. An existing stock (
- Visibilities of sales channels that are already assigned are updated with the delivered value under their existing id, so a changed visibility value is written
- Deleted products (
.meta.deleted) are deactivated instead of deleted, for a main product including its variants. Products and variants that inheritactive(null) are deactivated as well. Deactivated products (also stale variants) lose their own visibilities, categories and cross-sellings are only removed via the hookcleanupDeactivatedProducts(). An entry that is deleted and delivered in the same file is not deactivated (warning) active: A delivered main or simple product without the keyactiveis written as active (true), a variant as inheriting (null). Products deactivated earlier are therefore reactivated when they are delivered again- The package
attribute-valuesis imported before the products, so the property options ofpropertiesandoptionsare available - Custom relations of the project (
cleanupAdditionalRelations()) should be synced to the state of the entry as well
If a product that has variants in Shopware is delivered as a simple product (without variants), its variants that are not delivered in the same import are deactivated but keep their main product. Variants that are delivered in the same import are moved instead (see above). Shopware still counts the remaining variants as variants, so the product remains a container that cannot be bought until they are deleted. A warning is reported per product with remaining variants (Product has variants in Shopware but is delivered as simple product). Delete the variants manually or via a cleanup in the project.
Markets that are not supported on purpose can be excluded from the warning via reportUnresolvedMarket():
protected function reportUnresolvedMarket(array $data, string $market, string $area): void
{
if ($area === 'price' && in_array($market, ['outlet', 'partner'])) {
return;
}
parent::reportUnresolvedMarket($data, $market, $area);
}
Error handling and partial import
The following rules apply to the product import:
- The source system is leading: relations mirror the import file (see State synchronisation), simple fields are written if their key is delivered. Do not maintain products in the administration
- Products are never deleted: deleted entries, the variants of deleted main products and stale variants are deactivated –
active = false, in addition their own visibilities are removed. Further cleanup (cross-sellings, categories) is done in the project via the hookcleanupDeactivatedProducts() - Former variants are moved and not deactivated (see State synchronisation)
- Product numbers are unique: an entry whose product number belongs to another UUID (earlier in the file or in Shopware) is skipped and reported as a warning. If another delivered product that is not written yet releases the number, the entry is processed again once after all batches. The same UUID means update, reactivation or move
- Invalid data is handled per value, per entry and per batch:
- Too long texts are truncated, invalid single values are not written (Shopware keeps the current value) – each with a warning
- Missing or invalid required data (UUID, ID, product number, for main and simple products additionally tax, price, translations with name and name in the system language for new products) skips the entry with a warning. A skipped entry remains unchanged in Shopware and is not deactivated. Unknown or invalid custom fields never skip an entry, they are reported and not written
- A sync batch that Shopware still cannot write is rolled back and skipped – error with the readable IDs of the batch and the cause, the import continues with the next batch. There is no sync per product. The batch is only written again when its entries are delivered again – with delta exports, re-export the entries listed in the error
- Manufacturers are only created and never changed afterwards, the manufacturer image is only set via the hook
getManufacturerMediaId() - No own plugin tables for ID mappings, the UUID equals
md5(<Pimcore ID>)from the source system
| Level | Meaning |
|---|---|
INFO | Written, deactivated or moved entries |
WARNING | A value, a reference or an entry was not written, the rest of the import is not affected |
ERROR | A batch, a deactivation block or the whole package failed |
Each module with messages writes one chapter per file into the journal (.done), also if the module aborts with an exception. Variants are reported in the context of their main product with (ID: "<variant>", Parent-ID: "<main product>").
A file with skipped entries or batches ends with the resolution success. To monitor the import, evaluate the warnings and errors in the journal, not only the resolution.
Detailed answers on error cases and the behaviour of the import can be found on the page "Product import: FAQ".
Variant inheritance
In Shopware, variants inherit every value they do not have themselves from their main product. In the Pimcore bundle, the product adapter of the project delivers null for the values a variant should inherit (see "Build a product export: Inheritance"):
| Delivered for a variant | Written | Result |
|---|---|---|
| Key missing | nothing | The current value of the variant is kept (a new variant inherits) |
Simple field (ean, min-purchase, release-date, … of getProductFieldMap()) = null | null | inherits |
active = null or missing | null | inherits |
tax = null | taxId = null | inherits (a null never resolves to 0 %) |
price = null | price = null | inherits |
manufacturer, unit, delivery-time = null | null | inherits |
purchase-price, canonical-product, cms-page, feature-set = null | null | inherits |
translations.<locale>.<key> = null | null in that language | inherits |
translations.<locale>.name missing, empty or null, or translations missing | name null in the delivered languages / nothing | inherits |
properties, visibilities, prices = [] or missing | own rows removed | inherits |
custom-fields.<name> = null (also in translations.<locale>.custom-fields) | null in the languages of the value | inherits per key |
stock = null | nothing (0 on create) | stock is not inherited in Shopware |
For a variant, a delivered null inherits, a missing key keeps the current value. Exceptions are active (a missing key inherits) and the relations properties, visibilities and prices (a missing key removes the own entries, the variant then inherits). Values a variant should inherit therefore have to be delivered as null – the Pimcore bundle does not add null automatically.
Always deliver translations for variants (with null names and keys that equal the main product). A missing name is only written as null in a delivered language, a variant without translations keeps its current names in Shopware – only a new variant inherits them.
Variants therefore only require id, uuid and product-number, tax, price and names are optional. A delivered but invalid tax rate (unknown rate, not numeric) or price (not numeric) still skips the variant. Main and simple products keep their required checks: tax and price must be delivered and valid, null skips the entry. The gross rule prices of a variant use its delivered tax, without the key tax its current tax rate in Shopware, with "tax": null (or as new or inheriting variant) the tax rate of its main product. If no tax rate can be determined, the existing rule prices are kept with a warning. A variant that is detached to a top-level product is validated like a main product.
Custom fields
Custom fields are delivered by their technical name in Shopware, non-localized values in custom-fields, localized values in translations.<locale>.custom-fields:
{
"custom-fields": { "acme_is_new": true, "acme_colors": ["red", "blue"], "acme_dimensions": { "a": 1 } },
"translations": {
"de_DE": { "name": "…", "custom-fields": { "acme_claim": "Neu" } },
"en_GB": { "name": "…", "custom-fields": { "acme_claim": "New" } }
}
}
A value is always interpreted by the type of the custom field, also arrays and JSON objects – the shape of a value never decides whether it is localized. If a name is delivered in both places, the localized value applies in its language and all other languages get the non-localized value:
{
"custom-fields": { "acme_claim": "Classic" },
"translations": { "de_DE": { "name": "…", "custom-fields": { "acme_claim": "Klassisch" } } }
}
Result in a shop with the languages de_DE, en_GB (system language) and fr_FR:
| Language | writeUnlocalizedCustomFieldsToAllLanguages() = true (default) | writeUnlocalizedCustomFieldsToAllLanguages() = false |
|---|---|---|
de_DE | Klassisch | Klassisch |
en_GB | Classic | Classic |
fr_FR | Classic | unchanged (falls back to en_GB when read) |
An invalid localized value keeps the current value of its language, the non-localized value is not used there either.
- Names: the names are resolved once per import against the active custom fields of the sets that are related to products. An unknown name is reported (
Custom field "custom-fields/<name>" is not available for products in Shopware) and not written - Types: the values are converted by the type of the custom field:
| Type | Expected value |
|---|---|
int, float, number | Number like other numbers of the import, number with numberType: int as integer |
bool, checkbox, switch | Boolean like other booleans of the import |
datetime, date | Date like other dates of the import |
text, html | String |
select | Checked against the configured options (if options are configured). A multi select expects a list, a single value becomes a list |
entity, media | UUIDs (a list for multi selects) |
price | List of {currencyId, net, gross, linked, listPrice?, regulationPrice?} like the product price, including a price in the default currency |
json and all other types | Unchanged |
- Invalid values: an invalid value is reported (
... was not written because value ... is not valid for the type ..., the current value is kept) and not written, the rest of the entry is imported - Languages: custom fields are translatable in Shopware. Values of
custom-fieldsare written to all languages of the shop (plugins that read the custom fields of a language directly would otherwise not find them), withwriteUnlocalizedCustomFieldsToAllLanguages()=falseto the system language only. Localized values are written to their language - Removing: only delivered keys are written, keys that are not delivered are kept.
nullremoves the own value: Shopware stores the key as JSONnulland skips it when merging the values of variant and main product and of the language chain – the variant inherits the value of its main product, a language falls back to its parent language and then the system language. WithwriteUnlocalizedCustomFieldsToAllLanguages()=false, anullincustom-fieldsonly removes the value of the system language, remove own values of other languages with a localizednull - Own sets: for the sets of
getManagedCustomFieldSets(), the keys that are not delivered for a product in a language are removed in that language. Keys of other sets and of other plugins are never changed getAdditionalProductData(): additional custom fields belong intotranslations.<languageId>.customFieldsand are merged per key with the delivered custom fields. Do not return a top-levelcustomFields, it targets the translation of the system language as well
protected function getManagedCustomFieldSets(): array
{
return ['acme_product'];
}
Variant options
Variants deliver the key options ([{id, uuid}] of the property options). The options of the variant always mirror the key – a variant without options has no options, options that do not exist in Shopware are reported as a warning and not linked. The key options of a main product or a simple product is ignored, existing options of these products are removed.
The configurator settings of a main product are built from the options of
- its valid variants (from the import file) and
- its variants that are invalid in this import but already exist in Shopware. As these variants are not imported, their existing options are taken from Shopware, so their configurator settings are kept
All other configurator settings are removed, a product without variants has no configurator settings.
The step can be overridden via prepareVariantOptions().
Variant listing
Main products always get a variantListingConfig with displayParent: true, no main variant and no configuratorGroupConfig. variant-listing-config of a main product overrides single keys of this default:
| Key | Shopware | Description |
|---|---|---|
display-parent | displayParent | Boolean |
main-variant | mainVariantId | {id, uuid} of a valid variant delivered under this main product in this entry (the UUID wins). Shopware only uses the main variant if display-parent is false (with true the main product is shown in listings), the import writes it anyway |
configurator-group-config | configuratorGroupConfig | [{id?, uuid, representation, expression-for-listings}]: uuid of an existing property group, representation box, select, image or color, expression-for-listings boolean (default false). Controls how the variants are presented in listings. A property group delivered more than once is reported, the first entry wins |
Keys that are not delivered or null keep the default, null for the whole key writes the default. An invalid value of a key keeps the default of the key, invalid entries of configurator-group-config are dropped and unknown keys are ignored – each with a warning. For a variant or a simple product the key is reported (Field "variant-listing-config" is only supported for main products, it is not written …) and not written.
The step can be overridden via prepareVariantListingConfig().
Canonical product
canonical-product is {id, uuid} of another product (uuid = Shopware product id). The canonical product must exist in Shopware or be written in the same import. Because it may follow in a later batch, the canonical products are written after all batches via writeCanonicalProducts() (one update per chunk of getBatchSize() products, a failing chunk is reported as error). The following cases are reported as a warning and not written:
- an unknown product or a product that is skipped in this import and does not exist in Shopware (
Canonical product "<uuid>" is neither available in Shopware nor written in this import, field is not written …) - a value without a valid UUID (
Canonical product <value> is not valid (object with uuid), field is not written …) - the product itself (
Canonical product "<uuid>" is the product itself, field is not written …) - a product that is deactivated by this import, i.e. a deleted entry, a variant of a deleted main product or a stale variant (
Canonical product "<uuid>" is deactivated in this import, field is not written …)
A missing key keeps the assignment, null, "" or [] removes it (variants inherit).
Purchase price, CMS page and feature set
| Field | Shopware | Description |
|---|---|---|
purchase-price | purchasePrices | {net, gross} in the default currency like price ("1,5" is accepted), linked: false. Both values must be numeric and not negative |
cms-page | cmsPageId | UUID of an existing CMS layout of the type product_detail (PRODUCT_CMS_PAGE_TYPE) |
feature-set | featureSetId | UUID of an existing feature set (product_feature_set) |
Layouts and feature sets are never created and are loaded once per import. An invalid or unresolvable value is reported as a warning and not written, the entry is imported anyway. A missing key keeps the value, null (for purchase-price also {} or [], for cms-page and feature-set also "" or []) removes it (variants inherit).
Product extension
If the hook getProductExtensionData() returns an array, it is written as productExtension with id (UUID of the product) and pimcoreId (ID of the entry). This requires a product extension registered in the project (see "Product extension"). For existing products, the association productExtension is loaded automatically once the definition and the extension are registered.
By default, getProductExtensionData() builds the data from two maps:
| Hook | Default | Description |
|---|---|---|
getProductExtensionFieldMap(): array | [] | Key in product-extension => field of the product extension |
getProductExtensionTranslationKeyMap(): array | [] | Key in product-extension.translations.<locale> => translated field of the product extension, the translations are mapped via prepareTranslation() |
- As with simple fields, only mapped keys that are delivered in
product-extensionare written. A missing key keeps the value, an explicitly deliverednullis written, keys that are not mapped are ignored - Without maps, without the block
product-extensionor if none of the mapped keys (including the mapped translation keys) is delivered, no product extension is written - The product extension is pre-checked like the product: too long texts are truncated, invalid values are not written
- The keys of the maps are flat. Nested structures, relations or converted values require an override of
getProductExtensionData()that takes over the result ofparent::
The product adapter of the Pimcore bundle delivers the keys as array under product-extension or product-extension.translations.<locale> (see "Build a product export: Product extension").
protected function getProductExtensionFieldMap(): array
{
return ['business-area' => 'businessArea'];
}
protected function getProductExtensionTranslationKeyMap(): array
{
return ['subtitle' => 'subtitle'];
}
Nested structures are added in an override:
protected function getProductExtensionData(array $data): ?array
{
if (!array_key_exists('price-info', $data['product-extension'] ?? [])) {
return parent::getProductExtensionData($data);
}
// `priceInfo` is a JSON field and is replaced as a whole, sub keys that are not delivered are written as null
return (parent::getProductExtensionData($data) ?? []) + [
'priceInfo' => [
'amount' => $data['product-extension']['price-info']['amount'] ?? null,
'unit' => $data['product-extension']['price-info']['unit'] ?? null,
],
];
}
Category assignments
The CategoryAssignmentModule assigns the delivered products to the categories whose twocream_category_extension has the same identifier. Only assignments of products that are no longer part of the category are deleted. The module can be adapted in a subclass via the following hooks:
| Hook | Default | Description |
|---|---|---|
getRootCategoryId(): ?string | null (all categories) | Only categories below this category (UUID) are handled, the category itself is not part of it |
getCategoryExtensionIdColumn(): string | category_id | Column of twocream_category_extension that references category.id |
<?php
namespace MyCustomExtension\Core\System\Import\Module\Product;
use Twocream\JsonImporter\Core\System\Import\Module\Product\CategoryAssignmentModule as BaseCategoryAssignmentModule;
class CategoryAssignmentModule extends BaseCategoryAssignmentModule
{
protected function getRootCategoryId(): ?string
{
return '0190c5e4d1ef7c6a9a1c2b8e6f3d4a53';
}
}
The subclass replaces the CategoryAssignmentModule registered by the plugin and is therefore registered as decorator of the plugin service without own tag (see "Replace a module of the plugin"):
<service id="MyCustomExtension\Core\System\Import\Module\Product\CategoryAssignmentModule"
decorates="Twocream\JsonImporter\Core\System\Import\Module\Product\CategoryAssignmentModule"
autowire="true"/>
In addition, the property $disableElasticsearchSubProcess can be used in a subclass to suppress the Elasticsearch/OpenSearch processes after the import.
If a separate package is exported for each of several category trees, a separate subclass with an adjusted getHandledPackage() has to be registered with the service tag for each package.
Import JSON contract
The import expects the structure created by the product export of the Pimcore bundle (see "Export JSON contract"):
{
".meta": { "id": "...", "mail": "...", "delta": true },
"<package>": { "<pimcoreId>": { } },
"cross-selling": {
"<pimcoreId>": { "id": 1, "uuid": "...", "items": { "<name>": [ { "id": 2, "uuid": "..." } ] } }
}
}
- The UUID equals
md5(<pimcoreId>) - Deleted entries:
{ "id", "uuid", ".meta": { "deleted": true } }– products are deactivated - The package
relationshas no import module and is not part of the contract
products
| Type | Fields |
|---|---|
| Required | id, uuid, product-number, for main and simple products additionally tax, translations.<locale>.name, price {net, gross} |
| Optional | ean, manufacturer-number, active, manufacturer (name or {name, link?, description? {locale}}), properties [{id, uuid}], stock, is-closeout, shipping-free, min-purchase, max-purchase, purchase-steps, purchase-unit, reference-unit, restock-time, unit, delivery-time (UUID, {uuid} or {min, max, unit, name? {locale}}), purchase-price {net, gross}, canonical-product {id, uuid}, cms-page (UUID), feature-set (UUID), variant-listing-config {display-parent?, main-variant? {id, uuid}, configurator-group-config? [{id?, uuid, representation, expression-for-listings}]} (main products only), mark-as-topseller, length, width, height, weight, release-date, visibilities [{market, visibility}], prices {market: {net, currency}}, variants [...], product-extension {...}, custom-fields {<name>: value} (not localized) |
| Translations | translations.<locale>: name, description, custom-search-keywords, keywords, meta-title, meta-description, pack-unit, pack-unit-plural, custom-fields {<name>: value} (localized) |
- Variants have the same structure and may additionally contain
options [{id, uuid}],optionsof a main or simple product are ignored. Variants only requireid,uuidandproduct-number,nullinherits the value of the main product (alsotax,priceand names) - Optional relations (
properties,visibilities,prices,variants,options) always mirror the state of the entry: a missing key removes the existing relations in Shopware, a missingvariantsdeactivates the existing variants (see State synchronisation) product-extensionis read viagetProductExtensionFieldMap(),getProductExtensionTranslationKeyMap()orgetProductExtensionData()cross-selling-checksumis ignored
cross-selling
{ pimcoreId: { id, uuid, items: { name: [ {id, uuid} ] } } }
category-assignments
{ id, identifier, products: [ {id, uuid} ] }
Upgrade from version 2.x
For an update to version 3.0.0, the following points have to be checked. A detailed version including code examples can be found in the README of the plugin (section "Upgrade Notes").
- Register the product module: The plugin does not import the package
productsby itself. TheProductModuleor a subclass has to be registered with the service tagtwocream_json_importer.module. Without a registered module a file with the packageproductsfails withDetected unknown package "products" - Custom product module: Modules that extend the previous
AbstractProductModuleor have their own abstract product module should extend theProductModuleand remove the duplicated code (getHandledPackage,getEntityName,validateEntry,store,syncProduct,storeProduct,getProductDataas well as own copies ofprepareRelationsandcleanupRelations). Usages ofProductFaultStatehave to be removed. AsfetchExistingProduct()is nowfinal, additional associations have to be added viaextendCriteriaForExistingProductFetch() - Changed defaults:
stockdefaults to0on create and is updated if delivered,minPurchaseandpurchaseUnitno longer have defaults,referenceUnitis written fromreference-unit(waspurchase-unit),mainVariantIdis only written fromvariant-listing-config.main-variantand variant options are only taken fromvariants[].options. Project-specific defaults can be added viagetAdditionalProductData() - Map markets via hooks: sales channels per market in
getSalesChannelIdByMarket(), rules per market ingetRuleIdByMarket(), additional fields ingetAdditionalProductData(), the product extension ingetProductExtensionFieldMap()/getProductExtensionTranslationKeyMap()(flat keys) orgetProductExtensionData()(nested structures) and the cleanup of custom relations incleanupAdditionalRelations(). Only the translation keys ofgetProductTranslationKeyMap()are written, the default additionally mapscustom-search-keywords,pack-unitandpack-unit-plural– override the method to add own keys or to restore the previous map - Signatures: Overridden methods
prepareRelations()andcleanupRelations()have to be adjusted to the new signatures (see "Register a new module") - Category assignments: Own copies of the
CategoryAssignmentModulecan be replaced by the hooksgetRootCategoryId()andgetCategoryExtensionIdColumn(). Anabstractredeclaration of these methods in a subclass (e.g. an own abstract category assignment module) is a fatal error (Cannot make non abstract method ... abstract) – remove it and extend theCategoryAssignmentModuledirectly. If the id of the category extension equals the category id, overridegetCategoryExtensionIdColumn()and return'id' - Product extension: Definitions, entity and extension should inherit from the abstract classes (see "Product extension"). Table and column names remain unchanged, no schema change is needed
- Custom fields: the keys
custom-fieldsandtranslations.<locale>.custom-fieldsare written by the import itself (type-checked, only known custom fields of product sets). Remove own handling of these keys, additional custom fields of the project belong intotranslations.<languageId>.customFieldsofgetAdditionalProductData()(see Custom fields) - Variants:
tax,priceand names are no longer required for variants,nullinherits the value of the main product (see Variant inheritance) - Deleted products are deactivated instead of deleted, also if they inherit
active(null) - State synchronisation of relations (behaviour change): Relations of products always mirror the import file (see State synchronisation). Compared to 2.x, the import now also writes and synchronises visibilities and rule prices, removes variant options that are not delivered, keeps only the configurator settings of the delivered variants (instead of deleting all of them on every update) and deactivates variants that are no longer delivered, also the children of a product without the key
variants. A missing key removes existing relations, unresolved markets, currencies or options do not keep them either. Every entry therefore has to deliver its complete relations. ImplementgetSalesChannelIdByMarket()andgetRuleIdByMarket()before the first import, the default implementations (null) remove all visibilities and rule prices. Do not maintain relations of products in the administration - Main products delivered as simple products: Their variants that are not delivered in the same import are deactivated but not deleted (variants delivered in the same import are moved). The product remains a container that cannot be bought and a warning is reported on every import with remaining variants. If a main product is converted into a simple product, delete its variants manually or via a cleanup in the project
- Moving variants: Variants that are delivered as a top-level entry or under another main product are moved in Shopware (new main product or detached) instead of being deactivated as a stale variant. The previous main product is indexed again. Deliver the complete data and
activefor such entries (see State synchronisation). The context keysdetachedandexistingStockare available for project overrides ofprepareProductData(). If an override (or the sanitizer) leaves outstock, the module writes0for new products and the existing stock for detached variants - Partial import: A sync batch that cannot be written no longer aborts the file, it is skipped and reported as an error. The file ends with the resolution
success, evaluate the errors and warnings in the journal for monitoring (see "Product import: FAQ"). A skipped batch is only written again when its entries are delivered again – with delta exports, re-export the entries listed in the error - Product numbers: Entries whose product number belongs to another UUID (in Shopware or earlier in the file) are skipped with a warning. Free old product numbers of deactivated products in Shopware before they are reused. A number released by another delivered product that is not written yet is checked again once, swapped numbers are not supported
- Report chapter:
import()replaces the chapter of the module (resetReport()) – readgetReport()only afterimport()and set the logger viasetReportLogger() - Default of
active: Delivered entries withoutactiveare active (main products) or inherit (variants). Products deactivated manually in the administration are therefore reactivated with the next delivery, deliveractive: falseif a product has to stay inactive - Deactivation: Deactivated products lose their own visibilities. Implement
cleanupDeactivatedProducts()if category assignments or cross-sellings have to be removed as well - Validation helpers:
checkFieldLengths()andcheckTranslationFieldLengths()are deprecated, usesanitizePayload()instead. Set the logger of the report viasetReportLogger() - Locale mapping:
JsonImportConfiguration::getLocaleMapping()mapsentoen_GBinstead ofen_DEby default. Projects with the Shopware localeen-DEthat receive the keyenmust restore the mapping via theLocaleMappingEventor an ownJsonImportConfiguration(see "Which locales are accepted?"). Exports that already deliveren_DEare not affected. Subclasses of theModuleServicekeep working, the new constructor argument$eventDispatcheris optional - Package order: Subscribers of
PreHandlePackagesEvent::NAMEstill work and receive the already sorted packages. They can be replaced bygetPackageDependencies()in your own modules (see "Dependencies between packages") JsonFileHandler: The new constructor argument$packageDependencySorteris optional, subclasses keep working