001/*
002 *  Copyright 2023 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.forms.statistics;
017
018import java.util.ArrayList;
019import java.util.List;
020import java.util.stream.IntStream;
021
022import javax.jcr.Node;
023import javax.jcr.NodeIterator;
024import javax.jcr.Repository;
025import javax.jcr.Session;
026import javax.jcr.query.Query;
027import javax.jcr.query.QueryManager;
028
029import org.apache.avalon.framework.service.ServiceException;
030import org.apache.avalon.framework.service.ServiceManager;
031import org.apache.avalon.framework.service.Serviceable;
032
033import org.ametys.plugins.forms.content.table.FormTableManager;
034import org.ametys.plugins.repository.provider.AbstractRepository;
035import org.ametys.runtime.i18n.I18nizableText;
036import org.ametys.runtime.plugin.component.PluginAware;
037import org.ametys.runtime.plugins.admin.statistics.Statistics;
038import org.ametys.runtime.plugins.admin.statistics.StatisticsNode;
039import org.ametys.runtime.plugins.admin.statistics.StatisticsProvider;
040import org.ametys.runtime.plugins.admin.statistics.StatisticsValue;
041
042/**
043 * Stats for the "old" content forms 
044 */
045public class ContentFormsStatisticsProvider implements StatisticsProvider, Serviceable, PluginAware
046{
047    private String _id;
048    private FormTableManager _formTableManager;
049    private Repository _repository;
050
051    public void service(ServiceManager manager) throws ServiceException
052    {
053        _repository = (Repository) manager.lookup(AbstractRepository.ROLE);
054        _formTableManager = (FormTableManager) manager.lookup(FormTableManager.ROLE);
055    }
056    
057    public void setPluginInfo(String pluginName, String featureName, String id)
058    {
059        _id = id;
060    }
061    
062    public Statistics getStatistics()
063    {
064        List<Integer> formsSubmissions = _getFormsSubmissions();
065        int submissions = formsSubmissions.stream().flatMapToInt(IntStream::of).sum();
066        
067        return new StatisticsNode(
068                _id,
069                new I18nizableText("plugin.forms", "PLUGINS_FORMS_STATISTICS_CONTENTFORMS_LABEL"),
070                "ametysicon-code-html-form",
071                formsSubmissions.size(),
072                List.of(
073                    new StatisticsNode(
074                        "submissions",
075                        new I18nizableText("plugin.forms", "PLUGINS_FORMS_STATISTICS_CONTENTFORMS_SUBMISSIONS_LABEL"),
076                        "ametysicon-desktop-school-tool",
077                        submissions,
078                        List.of(
079                            new StatisticsValue(
080                                "max",
081                                new I18nizableText("plugin.forms", "PLUGINS_FORMS_STATISTICS_CONTENTFORMS_SUBMISSIONS_MAX_LABEL"),
082                                "ametysicon-sort51",
083                                formsSubmissions.size() > 0 ? formsSubmissions.get(formsSubmissions.size() - 1) : 0
084                            ),
085                            new StatisticsValue(
086                                "median",
087                                new I18nizableText("plugin.forms", "PLUGINS_FORMS_STATISTICS_CONTENTFORMS_SUBMISSIONS_MEDIAN_LABEL"),
088                                "ametysicon-maths-window-symbol-x",
089                                formsSubmissions.size() > 0 ? formsSubmissions.get(formsSubmissions.size() / 2) : 0
090                            )
091                        ),
092                        false
093                    )
094                ),
095                true
096            );
097    }
098    
099    private List<String> _getFormsIds()
100    {
101        Session session = null;
102        try
103        {
104            session = _repository.login();
105            
106            QueryManager queryManager = session.getWorkspace().getQueryManager();
107            @SuppressWarnings("deprecation")
108            Query query = queryManager.createQuery("//element(ametys-internal:forms, nt:unstructured)/*", Query.XPATH);
109            NodeIterator nodeIterator = query.execute().getNodes();
110            
111            List<String> formsIds = new ArrayList<>();
112            while (nodeIterator.hasNext())
113            {
114                Node node = nodeIterator.nextNode();
115                
116                formsIds.add(node.getName());
117            }
118            
119            return formsIds;
120        }
121        catch (Exception e)
122        {
123            throw new IllegalStateException("Cannot get forms", e);
124        }
125        finally
126        {
127            if (session != null)
128            {
129                session.logout();
130            }
131        }        
132    }
133    
134    private List<Integer> _getFormsSubmissions()
135    {
136        try
137        {
138            return _getFormsIds().stream()
139                .map(id -> { 
140                    try 
141                    { 
142                        return _formTableManager.getTotalSubmissions(id); 
143                    } 
144                    catch (Exception e) 
145                    { 
146                        /* ignore */
147                        return 0; 
148                    } 
149                })
150                .sorted()
151                .toList();
152        }
153        catch (Exception e)
154        {
155            throw new IllegalStateException("Cannot compute content forms statistics", e);
156        }
157    }
158}