001/*
002 *  Copyright 2017 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.odfsync.apogee.scc.impl;
017
018import java.util.ArrayList;
019import java.util.HashMap;
020import java.util.List;
021import java.util.Map;
022import java.util.Objects;
023import java.util.Set;
024import java.util.stream.Collectors;
025
026import org.apache.commons.collections4.CollectionUtils;
027import org.slf4j.Logger;
028
029import org.ametys.cms.content.external.ExternalizableMetadataHelper;
030import org.ametys.cms.repository.ModifiableDefaultContent;
031import org.ametys.odf.program.AbstractProgram;
032import org.ametys.plugins.contentio.synchronize.SynchronizableContentsCollection;
033import org.ametys.plugins.odfsync.apogee.scc.AbstractApogeeSynchronizableContentsWithCatalogCollection;
034import org.ametys.plugins.odfsync.apogee.scc.ApogeeSynchronizableContentsCollection;
035import org.ametys.plugins.repository.metadata.ModifiableCompositeMetadata;
036
037
038/**
039 * SCC for program contents.
040 */
041public class ProgramSynchronizableContentsCollection extends AbstractApogeeSynchronizableContentsWithCatalogCollection
042{
043    /** SCC model id */
044    public static final String MODEL_ID = "org.ametys.plugins.odfsync.apogee.scc.program";
045    
046    @Override
047    protected List<Map<String, Object>> _search(Map<String, Object> searchParams, Logger logger)
048    {
049        String dataSourceId = getDataSourceId();
050        
051        List<Map<String, Object>> requestValues = _convertBigDecimal(_apogeeDAO.searchPrograms(dataSourceId, getParameterValues(), searchParams));
052        if (!searchParams.containsKey("__count") && (searchParams.containsKey("apogeeSyncCode") || searchParams.containsKey("parentCode")))
053        {
054            for (Map<String, Object> values : requestValues)
055            {
056                String idValue = values.get(getIdColumn()).toString();
057                
058                Map<String, Object> parameters = new HashMap<>();
059                parameters.put(getIdField(), idValue);
060                
061                // Get the joint orgunits
062                List<Object> orgUnitCodes = new ArrayList<>();
063                List<Map<String, Object>> jointOrgUnitsValues = _apogeeDAO.getJointOrgUnits(dataSourceId, getParameterValues(), parameters);
064                for (Map<String, Object> jointOrgUnitValues : jointOrgUnitsValues)
065                {
066                    orgUnitCodes.add(jointOrgUnitValues.get("COD_ETB"));
067                }
068                values.put("COD_ETB", orgUnitCodes);
069                
070                // Get the modalities
071                List<Map<String, Object>> formofteachingOrgValues = _apogeeDAO.getFormOfTeachingOrg(dataSourceId, getParameterValues(), parameters);
072                List<Object> formofteachingOrgCodes = formofteachingOrgValues.stream()
073                        .filter(Objects::nonNull)
074                        .map(entry -> entry.get("COD_RGI"))
075                        .collect(Collectors.toList());
076                values.put("COD_RGI", formofteachingOrgCodes);
077                
078                // Get the add elements
079                List<Object> presentation = new ArrayList<>();
080                List<Object> teachingOrganization = new ArrayList<>();
081                List<Object> accessCondition = new ArrayList<>();
082                List<Object> educationLanguage = new ArrayList<>();
083                List<Map<String, Object>> addElements = _apogeeDAO.getAddElements(dataSourceId, getParameterValues(), parameters);
084                for (Map<String, Object> addElement : addElements)
085                {
086                    CollectionUtils.addIgnoreNull(presentation, _transformClobToString(addElement.get("EXI_PRG"), idValue, logger));
087                    CollectionUtils.addIgnoreNull(teachingOrganization, _transformClobToString(addElement.get("ORG_ETUDE"), idValue, logger));
088                    CollectionUtils.addIgnoreNull(educationLanguage, _transformClobToString(addElement.get("LNG_CRS_EXM"), idValue, logger));
089                    CollectionUtils.addIgnoreNull(accessCondition, _transformClobToString(addElement.get("CND_ACC"), idValue, logger));
090                }
091                values.put("EXI_PRG", presentation);
092                values.put("ORG_ETUDE", teachingOrganization);
093                values.put("LNG_CRS_EXM", educationLanguage);
094                values.put("CND_ACC", accessCondition);
095
096                // Get the domains
097                List<Map<String, Object>> domainValues = _apogeeDAO.getDomains(dataSourceId, getParameterValues(), parameters);
098                List<Object> domains = domainValues.stream()
099                        .filter(Objects::nonNull)
100                        .map(entry -> entry.get("COD_DFD"))
101                        .collect(Collectors.toList());
102                values.put("COD_DFD", domains);
103            }
104        }
105        return requestValues;
106    }
107
108    @Override
109    protected String getMappingName()
110    {
111        return "program";
112    }
113    
114    @Override
115    protected boolean setAdditionalMetadata(ModifiableDefaultContent content, Map<String, List<Object>> remoteValues, boolean create, Logger logger)
116    {
117        boolean hasChanges = false;
118        
119        // Get the program synchronization code
120        ModifiableCompositeMetadata cm = content.getMetadataHolder();
121        String syncCode = cm.getString(getIdField());
122        
123        // Set orgUnit metadata
124        SynchronizableContentsCollection scc = _sccHelper.getSCCFromModelId(OrgUnitSynchronizableContentsCollection.MODEL_ID);
125        if (scc != null && scc instanceof ApogeeSynchronizableContentsCollection)
126        {
127            List<ModifiableDefaultContent> children = ((ApogeeSynchronizableContentsCollection) scc).importOrSynchronizeContents(Map.of("id_program", syncCode), logger);
128            Map<String, Object> params = Map.of("contentTypes", List.of(getContentType()));
129            boolean isSynchronizable = getLocalAndExternalFields(params).contains(AbstractProgram.ORG_UNITS_REFERENCES);
130            if (isSynchronizable)
131            {
132                ExternalizableMetadataHelper.setExternalMetadata(cm, AbstractProgram.ORG_UNITS_REFERENCES, children.toArray(new ModifiableDefaultContent[children.size()]), create);
133            }
134            else
135            {
136                ExternalizableMetadataHelper.setMetadata(cm, AbstractProgram.ORG_UNITS_REFERENCES, children.toArray(new ModifiableDefaultContent[children.size()]));
137            }
138            hasChanges = true;
139        }
140        
141        return hasChanges;
142    }
143    
144    @Override
145    protected Set<String> getRichTextFields()
146    {
147        return Set.of("presentation", "teachingOrganization", "accessCondition");
148    }
149}