001/*
002 *  Copyright 2020 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.contentio.csv;
017
018import java.io.IOException;
019import java.util.ArrayList;
020import java.util.Arrays;
021import java.util.Collection;
022import java.util.HashMap;
023import java.util.List;
024import java.util.Locale;
025import java.util.Map;
026import java.util.Map.Entry;
027import java.util.Objects;
028import java.util.Optional;
029import java.util.Set;
030import java.util.function.Function;
031import java.util.stream.Collectors;
032import java.util.stream.Stream;
033
034import org.apache.avalon.framework.component.Component;
035import org.apache.avalon.framework.service.ServiceException;
036import org.apache.avalon.framework.service.ServiceManager;
037import org.apache.avalon.framework.service.Serviceable;
038import org.apache.commons.lang3.StringUtils;
039import org.supercsv.io.ICsvListReader;
040import org.supercsv.util.Util;
041
042import org.ametys.cms.ObservationConstants;
043import org.ametys.cms.contenttype.ContentAttributeDefinition;
044import org.ametys.cms.contenttype.ContentType;
045import org.ametys.cms.contenttype.ContentTypeExtensionPoint;
046import org.ametys.cms.data.ContentValue;
047import org.ametys.cms.data.type.AbstractMultilingualStringElementType;
048import org.ametys.cms.data.type.impl.MultilingualStringRepositoryElementType;
049import org.ametys.cms.indexing.solr.SolrIndexHelper;
050import org.ametys.cms.repository.Content;
051import org.ametys.cms.repository.ContentQueryHelper;
052import org.ametys.cms.repository.ModifiableDefaultContent;
053import org.ametys.cms.repository.ModifiableWorkflowAwareContent;
054import org.ametys.cms.workflow.AbstractContentWorkflowComponent;
055import org.ametys.cms.workflow.ContentWorkflowHelper;
056import org.ametys.cms.workflow.CreateContentFunction;
057import org.ametys.core.util.I18nUtils;
058import org.ametys.plugins.contentio.csv.SynchronizeModeEnumerator.ImportMode;
059import org.ametys.plugins.contentio.in.ContentImportException;
060import org.ametys.plugins.repository.AmetysObjectIterable;
061import org.ametys.plugins.repository.AmetysObjectResolver;
062import org.ametys.plugins.repository.data.holder.group.ModelAwareRepeater;
063import org.ametys.plugins.repository.data.holder.group.ModelAwareRepeaterEntry;
064import org.ametys.plugins.repository.data.holder.group.Repeater;
065import org.ametys.plugins.repository.data.holder.values.SynchronizableRepeater;
066import org.ametys.plugins.repository.data.holder.values.SynchronizableValue;
067import org.ametys.plugins.repository.data.holder.values.SynchronizableValue.Mode;
068import org.ametys.plugins.repository.data.type.ModelItemTypeConstants;
069import org.ametys.plugins.repository.metadata.MultilingualString;
070import org.ametys.plugins.repository.metadata.MultilingualStringHelper;
071import org.ametys.plugins.repository.query.expression.AndExpression;
072import org.ametys.plugins.repository.query.expression.Expression.Operator;
073import org.ametys.plugins.repository.query.expression.ExpressionContext;
074import org.ametys.plugins.repository.query.expression.MultilingualStringExpression;
075import org.ametys.plugins.repository.query.expression.StringExpression;
076import org.ametys.runtime.model.ElementDefinition;
077import org.ametys.runtime.model.ModelItem;
078import org.ametys.runtime.model.ModelViewItemGroup;
079import org.ametys.runtime.model.View;
080import org.ametys.runtime.model.ViewElement;
081import org.ametys.runtime.model.ViewElementAccessor;
082import org.ametys.runtime.model.ViewItem;
083import org.ametys.runtime.model.type.ElementType;
084import org.ametys.runtime.plugin.component.AbstractLogEnabled;
085
086import com.opensymphony.workflow.WorkflowException;
087
088/**
089 * Import contents from an uploaded CSV file.
090 */
091public class CSVImporter extends AbstractLogEnabled implements Component, Serviceable
092{
093    
094    /** Avalon Role */
095    public static final String ROLE = CSVImporter.class.getName();
096
097    /** Result key containing updated content's ids */
098    public static final String RESULT_CONTENT_IDS = "contentIds";
099    /** Result key containing number of errors */
100    public static final String RESULT_NB_ERRORS = "nbErrors";
101    /** Result key containing number of warnings */
102    public static final String RESULT_NB_WARNINGS = "nbWarnings";
103
104    private ContentWorkflowHelper _contentWorkflowHelper;
105
106    private ContentTypeExtensionPoint _contentTypeEP;
107    
108    private AmetysObjectResolver _resolver;
109
110    private I18nUtils _i18nUtils;
111
112    private SolrIndexHelper _solrIndexHelper;
113    
114    public void service(ServiceManager smanager) throws ServiceException
115    {
116        _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE);
117        _contentTypeEP = (ContentTypeExtensionPoint) smanager.lookup(ContentTypeExtensionPoint.ROLE);
118        _contentWorkflowHelper = (ContentWorkflowHelper) smanager.lookup(ContentWorkflowHelper.ROLE);
119        _i18nUtils = (I18nUtils) smanager.lookup(I18nUtils.ROLE);
120        _solrIndexHelper = (SolrIndexHelper) smanager.lookup(SolrIndexHelper.ROLE);
121    }
122
123    /**
124     * Extract contents from CSV file
125     * @param mapping mapping of content attributes and CSV file header
126     * @param view View of importing content
127     * @param contentType content type to import
128     * @param listReader mapReader to parse CSV file
129     * @param createAction creation action id
130     * @param editAction edition action id
131     * @param workflowName workflow name
132     * @param language language of created content.
133     * @param importMode The import mode
134     * @return list of created contents
135     * @throws IOException IOException while reading CSV
136     */
137    public Map<String, Object> importContentsFromCSV(Map<String, Object> mapping, View view, ContentType contentType, ICsvListReader listReader, int createAction, int editAction, String workflowName, String language, ImportMode importMode) throws IOException
138    {
139        try
140        {
141            _solrIndexHelper.pauseSolrCommitForEvents(_getIndexationEvents());
142            
143            List<String> contentIds = new ArrayList<>();
144            String[] columns = listReader.getHeader(true);
145            int nbErrors = 0;
146            int nbWarnings = 0;
147            List<String> row = null;
148            
149            while ((row = listReader.read()) != null)
150            {
151                try
152                {
153                    if (listReader.length() != columns.length)
154                    {
155                        getLogger().error("[{}] Import from CSV file: content skipped because of invalid row: {}", contentType.getId(), row);
156                        nbErrors++;
157                        continue;
158                    }
159    
160                    Map<String, String> rowMap = new HashMap<>();
161                    Util.filterListToMap(rowMap, columns, row);
162                    List<ViewItem> errors = new ArrayList<>();
163                    SynchronizeResult synchronizeResult = _processContent(view, rowMap, contentType, mapping, createAction, editAction, workflowName, language, errors, importMode);
164                    Optional<ModifiableWorkflowAwareContent> content = synchronizeResult.content();
165                    
166                    // If we are in CREATE_ONLY mode but content was not created, do not add it to the contents list
167                    if (content.isPresent() && (importMode != ImportMode.CREATE_ONLY || synchronizeResult.isCreated()))
168                    {
169                        contentIds.add(content.get().getId());
170                    }
171                    
172                    if (!errors.isEmpty())
173                    {
174                        nbWarnings++;
175                    }
176                }
177                catch (Exception e)
178                {
179                    nbErrors++;
180                    getLogger().error("[{}] Import from CSV file: error importing the content on line {}", contentType.getId(), listReader.getLineNumber(), e);
181                }
182            }
183            
184            Map<String, Object> results = new HashMap<>();
185            results.put(RESULT_CONTENT_IDS, contentIds);
186            results.put(RESULT_NB_ERRORS, nbErrors);
187            results.put(RESULT_NB_WARNINGS, nbWarnings);
188            return results;
189        }
190        finally
191        {
192            _solrIndexHelper.restartSolrCommitForEvents(_getIndexationEvents());
193        }
194    }
195    
196    private String[] _getIndexationEvents()
197    {
198        return new String[] {
199            ObservationConstants.EVENT_CONTENT_ADDED,
200            ObservationConstants.EVENT_CONTENT_MODIFIED,
201            ObservationConstants.EVENT_CONTENT_WORKFLOW_CHANGED,
202            ObservationConstants.EVENT_CONTENT_VALIDATED
203        };
204    }
205    
206    private SynchronizeResult _processContent(View view, Map<String, String> row, ContentType contentType, Map<String, Object> mapping, int createAction, int editAction, String workflowName, String language, List<ViewItem> errors, ImportMode importMode) throws Exception
207    {
208        @SuppressWarnings("unchecked")
209        List<String> attributeIdNames = (List<String>) mapping.get(ImportCSVFileHelper.NESTED_MAPPING_ID);
210        @SuppressWarnings("unchecked")
211        Map<String, Object> mappingValues = (Map<String, Object>) mapping.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES);
212
213        SynchronizeResult synchronizeResult = _synchronizeContent(row, contentType, view, attributeIdNames, mappingValues, createAction, editAction, workflowName, language, errors, importMode, Optional.empty());
214        return synchronizeResult;
215    }
216
217    private void _editContent(int editAction, View view, Map<String, Object> values, ModifiableWorkflowAwareContent content) throws WorkflowException
218    {
219        Collection<ModelItem> viewItemsDiff = content.getDifferences(view, values);
220        if (!viewItemsDiff.isEmpty())
221        {
222            _contentWorkflowHelper.editContent(content, values, editAction, View.of(viewItemsDiff.toArray(ModelItem[]::new)));
223        }
224    }
225    
226    private Object _getValue(Optional<? extends Content> parentContent, ViewItem viewItem, Map<String, Object> mapping, Map<String, String> row, int createAction, int editAction, String language, List<ViewItem> errors, String prefix, ImportMode importMode) throws Exception
227    {
228        if (viewItem instanceof ViewElement viewElement)
229        {
230            ElementDefinition elementDefinition = viewElement.getDefinition();
231            if (elementDefinition instanceof ContentAttributeDefinition contentAttributeDefinition && viewElement instanceof ViewElementAccessor viewElementAccessor)
232            {
233                return _getContentAttributeDefinitionValues(parentContent, mapping, row, createAction, editAction, language, viewElementAccessor, contentAttributeDefinition, errors, importMode);
234            }
235            else
236            {
237                return _getAttributeDefinitionValues(parentContent, mapping, row, elementDefinition, language, prefix);
238            }
239        }
240        else if (viewItem instanceof ModelViewItemGroup modelViewItemGroup)
241        {
242            List<ViewItem> children = modelViewItemGroup.getViewItems();
243            @SuppressWarnings("unchecked")
244            Map<String, Object> nestedMap = (Map<String, Object>) mapping.get(viewItem.getName());
245            @SuppressWarnings("unchecked")
246            Map<String, Object> nestedMapValues = (Map<String, Object>) (nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES));
247            if (ModelItemTypeConstants.REPEATER_TYPE_ID.equals(modelViewItemGroup.getDefinition().getType().getId()))
248            {
249                return _getRepeaterValues(parentContent, modelViewItemGroup, row, createAction, editAction, language, children, nestedMap, errors, prefix, importMode);
250            }
251            else
252            {
253                return _getCompositeValues(parentContent, viewItem, row, createAction, editAction, language, children, nestedMapValues, errors, prefix, importMode);
254            }
255        }
256        else
257        {
258            errors.add(viewItem);
259            throw new RuntimeException("Import from CSV file: unsupported type of ViewItem for view: " + viewItem.getName());
260        }
261    }
262
263    private Map<String, Object> _getCompositeValues(Optional<? extends Content> parentContent, ViewItem viewItem, Map<String, String> row, int createAction, int editAction,
264            String language, List<ViewItem> children, Map<String, Object> nestedMapValues, List<ViewItem> errors, String prefix, ImportMode importMode)
265    {
266        Map<String, Object> compositeValues = new HashMap<>();
267        for (ViewItem child : children)
268        {
269            try
270            {
271                compositeValues.put(child.getName(), _getValue(parentContent, child, nestedMapValues, row, createAction, editAction, language, errors, prefix + viewItem.getName() + ModelItem.ITEM_PATH_SEPARATOR, importMode));
272            }
273            catch (Exception e)
274            {
275                errors.add(viewItem);
276                getLogger().error("Import from CSV file: error while trying to get values for view: {}", viewItem.getName(), e);
277            }
278        }
279        return compositeValues;
280    }
281
282    private SynchronizableRepeater _getRepeaterValues(Optional<? extends Content> parentContent, ModelViewItemGroup viewItem, Map<String, String> row, int createAction, int editAction, String language,
283            List<ViewItem> children, Map<String, Object> nestedMap, List<ViewItem> errors, String prefix, ImportMode importMode)
284    {
285        @SuppressWarnings("unchecked")
286        Map<String, Object> mappingValues = (Map<String, Object>) nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES);
287        @SuppressWarnings("unchecked")
288        List<String> attributeIdNames = (List<String>) nestedMap.getOrDefault(ImportCSVFileHelper.NESTED_MAPPING_ID, List.of());
289        Map<String, Object> repeaterValues = new HashMap<>();
290        List<Map<String, Object>> repeaterValuesList = new ArrayList<>();
291        List<Integer> indexList = new ArrayList<>();
292
293        Optional<ModelAwareRepeater> repeater = parentContent.map(p -> p.getRepeater(prefix + viewItem.getName()));
294        
295        if (repeater.isPresent() && !attributeIdNames.isEmpty() && _allAttributesFilled(mappingValues, attributeIdNames))
296        {
297            indexList = repeater.get()
298                .getEntries()
299                .stream()
300                .filter(entry ->
301                {
302                    return attributeIdNames.stream()
303                        .allMatch(attributeName ->
304                        {
305                            // Get the entry value
306                            Object entryValue = entry.getValue(attributeName);
307                            
308                            // Get the row value for the attribute (from CSV file)
309                            Object rowValue = Optional.of(attributeName)
310                                    .map(mappingValues::get)
311                                    .map(String.class::cast)
312                                    .map(row::get)
313                                    .orElse(null);
314                            
315                            // Transform the row value to the right type then compare entry value and row value
316                            return Optional.of(attributeName)
317                                .map(viewItem::getModelViewItem)
318                                .map(ViewElement.class::cast)
319                                .map(ViewElement::getDefinition)
320                                .map(ElementDefinition::getType)
321                                .map(def -> def.castValue(rowValue))
322                                .map(value -> value.equals(entryValue))
323                                .orElse(false);
324                        });
325                })
326                .map(ModelAwareRepeaterEntry::getPosition)
327                .collect(Collectors.toList());
328        }
329        
330        // If entries match with attribute ids, we replace the first entries
331        // Else if the repeater exists, we assume we are on the next model item after the last one
332        // Else (the repeater doesn't exist, we set the rowIndex to first index
333        Integer rowIndex = indexList.isEmpty() ? repeater.map(Repeater::getSize).orElse(1) : indexList.get(0);
334        
335        for (ViewItem child : children)
336        {
337            try
338            {
339                Object entryValues = _getValue(parentContent, child, mappingValues, row, createAction, editAction, language, errors, prefix + viewItem.getName() + "[" + rowIndex + "]" + ModelItem.ITEM_PATH_SEPARATOR, importMode);
340                if (entryValues != null)
341                {
342                    repeaterValues.put(child.getName(), entryValues);
343                }
344            }
345            catch (Exception e)
346            {
347                errors.add(viewItem);
348                getLogger().error("Import from CSV file: error while trying to get values for view: {}", viewItem.getName(), e);
349            }
350        }
351        repeaterValuesList.add(repeaterValues);
352        
353        if (indexList.isEmpty())
354        {
355            return SynchronizableRepeater.appendOrRemove(repeaterValuesList, Set.of());
356        }
357        else
358        {
359            // If several rows match the id, only replace the first but add a warning
360            if (indexList.size() > 1)
361            {
362                errors.add(viewItem);
363            }
364            return SynchronizableRepeater.replace(repeaterValuesList, List.of(rowIndex));
365        }
366    }
367    
368    private Object _getContentAttributeDefinitionValues(Optional<? extends Content> parentContent, Map<String, Object> mapping, Map<String, String> row,
369            int createAction, int editAction, String language, ViewElementAccessor viewElementAccessor, ContentAttributeDefinition contentAttributeDefinition, List<ViewItem> errors, ImportMode importMode) throws Exception
370    {
371        String contentTypeId = contentAttributeDefinition.getContentTypeId();
372        ContentType contentType = _contentTypeEP.getExtension(contentTypeId);
373        @SuppressWarnings("unchecked")
374        Map<String, Object> nestedMap = (Map<String, Object>) mapping.get(viewElementAccessor.getName());
375        @SuppressWarnings("unchecked")
376        Map<String, Object> mappingValues = (Map<String, Object>) nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_VALUES);
377        @SuppressWarnings("unchecked")
378        List<String> attributeIdNames = (List<String>) nestedMap.get(ImportCSVFileHelper.NESTED_MAPPING_ID);
379        if (_allAttributesFilled(mappingValues, attributeIdNames))
380        {
381            View view = new View();
382            view.addViewItems(viewElementAccessor.getViewItems());
383            SynchronizeResult synchronizeResult = _synchronizeContent(row, contentType, view, attributeIdNames, mappingValues, createAction, editAction, null, language, errors, importMode, parentContent);
384            
385            Optional<ModifiableWorkflowAwareContent> attachedContent = synchronizeResult.content();
386            
387            if (synchronizeResult.hasKey && attachedContent.isEmpty() && importMode == ImportMode.UPDATE_ONLY)
388            {
389                errors.add(viewElementAccessor);
390            }
391            
392            // If content is multiple, we keep the old value list and we check if content was already inside, and add it otherwise
393            if (attachedContent.isPresent() && contentAttributeDefinition.isMultiple())
394            {
395                Optional<ContentValue[]> multipleContents = parentContent.map(c -> c.getValue(contentAttributeDefinition.getPath()));
396                if (!_containsContent(attachedContent.get(), multipleContents))
397                {
398                    // If there is no list or if it is empty, add it. Otherwise, we have to check if it is inside.
399                    SynchronizableValue syncValue = new SynchronizableValue(List.of(attachedContent.get()));
400                    syncValue.setMode(Mode.APPEND);
401                    return syncValue;
402                }
403                else if (multipleContents.isPresent())
404                {
405                    // return existing values as otherwise the values would be erased
406                    SynchronizableValue syncValue = new SynchronizableValue(Arrays.asList(multipleContents.get()));
407                    syncValue.setMode(Mode.REPLACE);
408                    return syncValue;
409                }
410            }
411            else
412            {
413                return attachedContent.orElse(null);
414            }
415        }
416        return null;
417    }
418    
419    private boolean _containsContent(ModifiableWorkflowAwareContent attachedContent, Optional<ContentValue[]> multipleContents)
420    {
421        return multipleContents
422                .map(Arrays::stream)
423                .orElseGet(Stream::empty)
424                .map(ContentValue::getContentId)
425                .anyMatch(valueFromContent -> valueFromContent.equals(attachedContent.getId()));
426    }
427    
428    private Object _getAttributeDefinitionValues(Optional<? extends Content> parentContent, Map<String, Object> mapping, Map<String, String> row, ElementDefinition elementDefinition, String language, String prefix)
429    {
430        ElementType elementType = elementDefinition.getType();
431        String elementName = elementDefinition.getName();
432        String elementColumn = (String) mapping.get(elementName);
433        String valueAsString = row.get(elementColumn);
434        
435        Object value;
436        if (elementType instanceof AbstractMultilingualStringElementType && !MultilingualStringHelper.matchesMultilingualStringPattern(valueAsString))
437        {
438            MultilingualString multilingualString = new MultilingualString();
439            multilingualString.add(new Locale(language), valueAsString);
440            value = multilingualString;
441        }
442        else
443        {
444            value = elementType.castValue(valueAsString);
445        }
446        
447        if (elementDefinition.isMultiple())
448        {
449            // Build path with index for repeaters.
450            String pathWithIndex = prefix + elementDefinition.getName();
451            
452            Optional<Object[]> values = parentContent.map(c -> c.getValue(pathWithIndex));
453            if (!_containsValue(value, parentContent.map(c -> c.getValue(pathWithIndex))))
454            {
455                // If there is no list or if it is empty, add it. Otherwise, we have to check if it is inside.
456                // If there is no parentContent, still append as we want to fill the values map anyway.
457                SynchronizableValue syncValue = new SynchronizableValue(value != null ? List.of(value) : List.of());
458                syncValue.setMode(Mode.APPEND);
459                return syncValue;
460            }
461            else if (values.isPresent())
462            {
463                // return existing values as otherwise the values would be erased
464                SynchronizableValue syncValue = new SynchronizableValue(Arrays.asList(values.get()));
465                syncValue.setMode(Mode.REPLACE);
466                return syncValue;
467            }
468        }
469        else
470        {
471            return value;
472        }
473        
474        return null;
475    }
476    
477    private boolean _containsValue(Object value, Optional<Object[]> multipleValues)
478    {
479        return multipleValues
480                .map(Arrays::stream)
481                .orElseGet(Stream::empty)
482                .anyMatch(valueFromContent -> valueFromContent.equals(value));
483    }
484
485    private SynchronizeResult _synchronizeContent(Map<String, String> row, ContentType contentType, View view, List<String> attributeIdNames, Map<String, Object> mappingValues, int createAction, int editAction, String workflowName, String language, List<ViewItem> errors, ImportMode importMode, Optional< ? extends Content> parentContent) throws Exception
486    {
487        SynchronizeResult synchronizeResult = _getOrCreateContent(mappingValues, row, contentType, Optional.ofNullable(workflowName), createAction, language, attributeIdNames, parentContent, importMode);
488        Optional<ModifiableWorkflowAwareContent> content = synchronizeResult.content();
489        
490        // If we are on CREATE_ONLY mode and content already exists, or if we are on UPDATE_ONLY mode and content does not exists, stop recursivity
491        if (importMode == ImportMode.CREATE_ONLY && !synchronizeResult.isCreated() || importMode == ImportMode.UPDATE_ONLY && content.isEmpty())
492        {
493            return synchronizeResult;
494        }
495        
496        Map<String, Object> values = _getValues(content, row, view, mappingValues, createAction, editAction, language, errors, importMode);
497        if (!values.isEmpty())
498        {
499            if (content.isEmpty())
500            {
501                // Throw this exception only when values are filled, as an empty content should not trigger any warning
502                throw new ContentImportException("Can't create and fill content of content type '" + contentType.getId() + "' and following values '" + values + "' : at least one of those identifiers is null : " + attributeIdNames);
503            }
504            else
505            {
506                _editContent(editAction, view, values, content.get());
507            }
508        }
509        
510        return synchronizeResult;
511    }
512    
513    private SynchronizeResult _getOrCreateContent(Map<String, Object> mapping, Map<String, String> row, ContentType contentType, Optional<String> workflowName, int createAction, String language, List<String> attributeIdNames, Optional<? extends Content> parentContent, ImportMode importMode) throws ContentImportException, WorkflowException
514    {
515        AndExpression expression = new AndExpression();
516        List<String> values = new ArrayList<>();
517        
518        for (String attributeName : attributeIdNames)
519        {
520            ModelItem modelItem = contentType.getModelItem(attributeName);
521            String attributePath = (String) mapping.get(attributeName);
522            String value = row.get(attributePath);
523            values.add(value);
524            
525            if (value == null)
526            {
527                return new SynchronizeResult(false, Optional.empty(), false);
528            }
529            
530            // Get content
531            if (modelItem.getType() instanceof MultilingualStringRepositoryElementType)
532            {
533                expression.add(new MultilingualStringExpression(attributeName, Operator.EQ, value, language));
534            }
535            else
536            {
537                expression.add(new StringExpression(attributeName, Operator.EQ, value));
538            }
539        }
540
541        expression.add(_contentTypeEP.createHierarchicalCTExpression(contentType.getId()));
542        
543        if (!contentType.isMultilingual())
544        {
545            expression.add(new StringExpression("language", Operator.EQ, language, ExpressionContext.newInstance().withInternal(true)));
546        }
547        
548        String xPathQuery = ContentQueryHelper.getContentXPathQuery(expression);
549        AmetysObjectIterable<ModifiableDefaultContent> matchingContents = _resolver.query(xPathQuery);
550        if (matchingContents.getSize() > 1)
551        {
552            throw new ContentImportException("More than one content found for type " + contentType.getLabel() + " with "
553                    + attributeIdNames + " as identifier and " + values + " as value");
554        }
555        else if (matchingContents.getSize() == 1)
556        {
557            return new SynchronizeResult(false, Optional.of(matchingContents.iterator().next()), true);
558        }
559        else if (importMode == ImportMode.UPDATE_ONLY)
560        {
561            return new SynchronizeResult(false, Optional.empty(), true);
562        }
563        
564        // Create content
565
566        if (contentType.isAbstract())
567        {
568            throw new ContentImportException("Can not create content for type " + contentType.getLabel() + " with "
569                    + attributeIdNames + " as identifier and " + values + " as value, the content type is abstract");
570        }
571        
572        Map<String, Object> result;
573        String title;
574        if (mapping.containsKey("title"))
575        {
576            title = row.get(mapping.get("title"));
577        }
578        else
579        {
580            title = _i18nUtils.translate(contentType.getDefaultTitle(), language);
581        }
582        
583        
584        String finalWorkflowName = workflowName.or(contentType::getDefaultWorkflowName)
585                                               .orElseThrow(() -> new ContentImportException("No workflow specified for content type " + contentType.getLabel() + " with "
586                                                       + attributeIdNames + " as identifier and " + values + " as value"));
587
588        Map<String, Object> inputs = new HashMap<>();
589        inputs.put(CreateContentFunction.INITIAL_VALUE_SUPPLIER, new Function<List<String>, Object>()
590        {
591            public Object apply(List<String> keys)
592            {
593                // Browse the mapping to find the column related to the attribute
594                Object nestedValue = mapping;
595                for (String key : keys)
596                {
597                    nestedValue = ((Map) nestedValue).get(key);
598                    // If nestedValue is null, the attribute is absent from the map, no value can be found
599                    if (nestedValue == null)
600                    {
601                        return null;
602                    }
603                    // If nestedValue is a map, the key is a complex element such a content or a composite,
604                    // we need to keep browsing the map to find the column
605                    if (nestedValue instanceof Map)
606                    {
607                        nestedValue = ((Map) nestedValue).get(ImportCSVFileHelper.NESTED_MAPPING_VALUES);
608                    }
609                }
610                
611                // Get the value of the attribute for the current row
612                return row.get(nestedValue.toString());
613            }
614        });
615        
616        parentContent.ifPresent(content -> inputs.put(CreateContentFunction.PARENT_CONTEXT_VALUE, content.getId()));
617
618        // CONTENTIO-253 To avoid issue with title starting with a non letter character, we prefix the name with the contentTypeId
619        String prefix = StringUtils.substringAfterLast(contentType.getId(), ".").toLowerCase();
620        String contentName = prefix + "-" + title;
621        
622        if (contentType.isMultilingual())
623        {
624            inputs.put(CreateContentFunction.CONTENT_LANGUAGE_KEY, language);
625            result = _contentWorkflowHelper.createContent(finalWorkflowName, createAction, contentName, Map.of(language, title), new String[] {contentType.getId()}, null, inputs);
626        }
627        else
628        {
629            result = _contentWorkflowHelper.createContent(finalWorkflowName, createAction, contentName, title, new String[] {contentType.getId()}, null, language, inputs);
630        }
631        
632        ModifiableWorkflowAwareContent content = (ModifiableWorkflowAwareContent) result.get(AbstractContentWorkflowComponent.CONTENT_KEY);
633        return new SynchronizeResult(true, Optional.of(content), true);
634    }
635    
636    private Map<String, Object> _getValues(Optional<ModifiableWorkflowAwareContent> content, Map<String, String> row, View view, Map<String, Object> mappingValues, int createAction, int editAction, String language, List<ViewItem> errors, ImportMode importMode)
637    {
638        Map<String, Object> values = new HashMap<>();
639        
640        for (ViewItem viewItem : view.getViewItems())
641        {
642            try
643            {
644                Object value = _getValue(content, viewItem, mappingValues, row, createAction, editAction, language, errors, StringUtils.EMPTY, importMode);
645                if (value != null)
646                {
647                    values.put(viewItem.getName(), value);
648                }
649            }
650            catch (Exception e)
651            {
652                errors.add(viewItem);
653                getLogger().error("Import from CSV file: error while trying to get values for item '{}'", viewItem.getName(), e);
654            }
655        }
656        
657        return values;
658    }
659    
660    private boolean _allAttributesFilled(Map<String, Object> mappingValues, List<String> attributeNames)
661    {
662        return mappingValues.entrySet()
663            .stream()
664            .filter(entry -> attributeNames.contains(entry.getKey()))
665            .map(Entry::getValue)
666            .allMatch(Objects::nonNull);
667    }
668    
669    private record SynchronizeResult(boolean isCreated, Optional<ModifiableWorkflowAwareContent> content, boolean hasKey) { /* empty */ }
670    
671}