diff --git a/.classpath b/.classpath deleted file mode 100644 index 14cacb1b0..000000000 --- a/.classpath +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index 7b18fed9d..899e6b9fd 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,5 @@ docroot/css/.sass-cache/ docroot/WEB-INF/src/com/liferay/lms/service/base/ docroot/WEB-INF/service/com/liferay/lms/model docroot/WEB-INF/service/com/liferay/lms/service -docroot/WEB-INF/service/com/liferay/lms/NoSuch*.java \ No newline at end of file +docroot/WEB-INF/service/com/liferay/lms/NoSuch*.java +docroot/WEB-INF/sql \ No newline at end of file diff --git a/.project b/.project deleted file mode 100644 index 353686a2f..000000000 --- a/.project +++ /dev/null @@ -1,37 +0,0 @@ - - - liferaylms-portlet - - - - - - org.eclipse.wst.jsdt.core.javascriptValidator - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - - - - org.sonar.ide.eclipse.core.sonarNature - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature - org.eclipse.wst.common.project.facet.core.nature - org.eclipse.jdt.core.javanature - org.eclipse.wst.jsdt.core.jsNature - - diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope deleted file mode 100644 index 840a01d5a..000000000 --- a/.settings/.jsdtscope +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 8ed69664a..000000000 --- a/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -encoding//docroot/WEB-INF/src/content/language-hook.properties=UTF-8 -encoding//docroot/html/resourceExternalActivity/vimeo.jsp=UTF-8 -encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index d17b6724d..000000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,12 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.7 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.7 diff --git a/.settings/org.eclipse.jst.jsp.core.prefs b/.settings/org.eclipse.jst.jsp.core.prefs deleted file mode 100644 index 3a5c98dba..000000000 --- a/.settings/org.eclipse.jst.jsp.core.prefs +++ /dev/null @@ -1,3 +0,0 @@ -eclipse.preferences.version=1 -validateFragments=false -validation.use-project-settings=true diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component deleted file mode 100644 index bcad448bf..000000000 --- a/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml b/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml deleted file mode 100644 index 500dfccb9..000000000 --- a/.settings/org.eclipse.wst.common.project.facet.core.prefs.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index 6deb6539d..000000000 --- a/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a48..000000000 --- a/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6e..000000000 --- a/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/.settings/org.sonar.ide.eclipse.core.prefs b/.settings/org.sonar.ide.eclipse.core.prefs deleted file mode 100644 index eab5b00f2..000000000 --- a/.settings/org.sonar.ide.eclipse.core.prefs +++ /dev/null @@ -1,6 +0,0 @@ -eclipse.preferences.version=1 -extraProperties= -lastAnalysisDate=1436973391000 -projectKey=wemooc -serverUrl=http\://localhost\:9000 -version=2 diff --git a/.tern-project b/.tern-project deleted file mode 100644 index a185ba0d2..000000000 --- a/.tern-project +++ /dev/null @@ -1 +0,0 @@ -{"ide":{"scriptPaths":[]},"plugins":{"aui":{},"liferay":{},"yui":{}},"libs":["ecma5","browser"]} \ No newline at end of file diff --git a/docroot/WEB-INF/liferay-plugin-package.properties b/docroot/WEB-INF/liferay-plugin-package.properties index 4788fd3f1..e12e67cb4 100644 --- a/docroot/WEB-INF/liferay-plugin-package.properties +++ b/docroot/WEB-INF/liferay-plugin-package.properties @@ -1,6 +1,7 @@ name=liferaylms-portlet module-group-id=com.ted.wemooc -module-incremental-version=3.7.4 +module-incremental-version=3.8.0 + tags= short-description= change-log= diff --git a/docroot/WEB-INF/liferay-portlet.xml b/docroot/WEB-INF/liferay-portlet.xml index d05910133..703d90cdf 100644 --- a/docroot/WEB-INF/liferay-portlet.xml +++ b/docroot/WEB-INF/liferay-portlet.xml @@ -10,6 +10,7 @@ content 17.5 com.liferay.lms.asset.LearningActivityAssetRendererFactory + com.liferay.lms.expando.LearningActivityCustomAttributesDisplay false /css/main.css /js/main.js @@ -511,6 +512,7 @@ inscriptionadmin /icon.png + com.liferay.portal.kernel.portlet.DefaultConfigurationAction false /css/main.css @@ -684,6 +686,7 @@ asynchronous-process-dashboard /icon.png + com.liferay.lms.actions.AsynchronousConfigurationAction /css/main.css /js/main.js diff --git a/docroot/WEB-INF/portlet.xml b/docroot/WEB-INF/portlet.xml index 10d8e2b01..77e8fd105 100644 --- a/docroot/WEB-INF/portlet.xml +++ b/docroot/WEB-INF/portlet.xml @@ -1976,6 +1976,10 @@ view-template /html/inscriptionadmin/view.jsp + + config-template + /html/inscriptionadmin/config.jsp + 0 text/html @@ -2189,7 +2193,14 @@ x:themeId + actId moduleId + actionEditing + + actionEditingActivity + actionEditingDetails + actionEditingModule + actionCalifications activityViewer @@ -2572,9 +2583,13 @@ com.liferay.lms.portlet.AsynchronousProcessDashboard - view-jsp + view-template /html/asynchronousprocessdashboard/view.jsp + + config-template + /html/asynchronousprocessdashboard/config/config.jsp + 0 text/html diff --git a/docroot/WEB-INF/service.xml b/docroot/WEB-INF/service.xml index 573a880a4..2e9597016 100644 --- a/docroot/WEB-INF/service.xml +++ b/docroot/WEB-INF/service.xml @@ -816,6 +816,7 @@ + diff --git a/docroot/WEB-INF/service/com/liferay/lms/InscriptionException.java b/docroot/WEB-INF/service/com/liferay/lms/InscriptionException.java new file mode 100644 index 000000000..6fd3e8dee --- /dev/null +++ b/docroot/WEB-INF/service/com/liferay/lms/InscriptionException.java @@ -0,0 +1,21 @@ +package com.liferay.lms; + +import com.liferay.portal.kernel.exception.PortalException; + +public class InscriptionException extends PortalException { + + private String key; + + public InscriptionException(String key, String message) { + super(message); + this.key = key; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } +} diff --git a/docroot/WEB-INF/service/com/liferay/lms/asset/LearningActivityBaseAssetRenderer.java b/docroot/WEB-INF/service/com/liferay/lms/asset/LearningActivityBaseAssetRenderer.java index f29586405..fd8335d87 100644 --- a/docroot/WEB-INF/service/com/liferay/lms/asset/LearningActivityBaseAssetRenderer.java +++ b/docroot/WEB-INF/service/com/liferay/lms/asset/LearningActivityBaseAssetRenderer.java @@ -61,7 +61,6 @@ public abstract class LearningActivityBaseAssetRenderer extends BaseAssetRendere protected static final String ACTIVITY_VIEWER_PORTLET_ID = PortalUtil.getJsSafePortletId("activityViewer"+PortletConstants.WAR_SEPARATOR+ClpSerializer.getServletContextName()); public static final String LMS_EDITACTIVITY_PORTLET_ID = PortalUtil.getJsSafePortletId("editactivity"+PortletConstants.WAR_SEPARATOR+ClpSerializer.getServletContextName()); - private LearningActivity _learningactivity; private String _nameKey; private String _portletId; diff --git a/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionType.java b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionType.java new file mode 100644 index 000000000..718d01737 --- /dev/null +++ b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionType.java @@ -0,0 +1,22 @@ +package com.liferay.lms.course.adminaction; + +import java.util.Locale; +import java.util.Set; + +import javax.portlet.PortletResponse; + +import com.liferay.lms.model.Course; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.upload.UploadRequest; +import com.liferay.portal.service.ServiceContext; + +public interface AdminActionType +{ + public long getTypeId(); + public String getName(Locale locale); + public String getHelpMessage(Locale locale); + public String getPortletId(); + public boolean hasPermission(long userId); + public String getIcon(); +} diff --git a/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionTypeClp.java b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionTypeClp.java new file mode 100644 index 000000000..582a19cf9 --- /dev/null +++ b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionTypeClp.java @@ -0,0 +1,171 @@ +package com.liferay.lms.course.adminaction; + +import java.util.Locale; +import java.util.Set; + +import javax.portlet.PortletResponse; + +import com.liferay.lms.model.Course; +import com.liferay.lms.service.ClpSerializer; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.upload.UploadRequest; +import com.liferay.portal.kernel.util.ClassLoaderProxy; +import com.liferay.portal.kernel.util.MethodHandler; +import com.liferay.portal.kernel.util.MethodKey; +import com.liferay.portal.service.ServiceContext; + +public class AdminActionTypeClp implements AdminActionType { + + private ClassLoaderProxy clp; + + public AdminActionTypeClp(ClassLoaderProxy clp) { + this.clp = clp; + } + + public java.lang.Object invokeMethod(java.lang.String name, + java.lang.String[] parameterTypes, java.lang.Object[] arguments) + throws java.lang.Throwable { + throw new UnsupportedOperationException(); + } + + @SuppressWarnings("deprecation") + public long getTypeId(){ + Object returnObj = null; + + try { + returnObj = clp.invoke("getTypeId", new Object[] {}); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((Long)returnObj).longValue(); + } + + public String getName(Locale locale){ + Object returnObj = null; + + try { + MethodKey getTitleMethod = new MethodKey(clp.getClassName(), "getName", Locale.class); + returnObj = clp.invoke(new MethodHandler(getTitleMethod, locale)); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((String)returnObj); + } + + + public String getHelpMessage(Locale locale){ + Object returnObj = null; + + try { + MethodKey getTitleMethod = new MethodKey(clp.getClassName(), "getHelpMessage", Locale.class); + returnObj = clp.invoke(new MethodHandler(getTitleMethod, locale)); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((String)returnObj); + } + + + public boolean hasPermission(long userId){ + Object returnObj = null; + + try { + MethodKey getTitleMethod = new MethodKey(clp.getClassName(), "hasPermission", long.class); + returnObj = clp.invoke(new MethodHandler(getTitleMethod, userId)); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((Boolean)returnObj).booleanValue(); + } + + + public String getPortletId(){ + Object returnObj = null; + + try { + MethodKey getSuffixMethod = new MethodKey(clp.getClassName(), "getPortletId"); + returnObj = clp.invoke(new MethodHandler(getSuffixMethod)); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((String)returnObj); + } + + + public String getIcon(){ + Object returnObj = null; + + try { + MethodKey getSuffixMethod = new MethodKey(clp.getClassName(), "getIcon"); + returnObj = clp.invoke(new MethodHandler(getSuffixMethod)); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((String)returnObj); + } + + + + +} diff --git a/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionTypeRegistry.java b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionTypeRegistry.java new file mode 100644 index 000000000..31e8d28f4 --- /dev/null +++ b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/AdminActionTypeRegistry.java @@ -0,0 +1,133 @@ +package com.liferay.lms.course.adminaction; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Properties; + +import com.liferay.lms.service.ClpSerializer; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.portlet.PortletClassLoaderUtil; +import com.liferay.portal.kernel.util.AutoResetThreadLocal; +import com.liferay.portal.kernel.util.ClassLoaderProxy; +import com.liferay.portal.kernel.util.PortalClassLoaderUtil; +import com.liferay.portal.kernel.util.PropsUtil; +import com.liferay.portal.kernel.util.UnmodifiableList; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.model.PortletConstants; +import com.liferay.portal.util.PortalUtil; + +public class AdminActionTypeRegistry { + + protected static final String LMS_ACTIVITIES_LIST_PORTLET_ID = PortalUtil.getJsSafePortletId("lmsactivitieslist"+PortletConstants.WAR_SEPARATOR+ClpSerializer.getServletContextName()); + private static Log log = LogFactoryUtil.getLog(AdminActionTypeRegistry.class); + + private static AdminActionType[] _getAdminActionTypes(){ + Properties properties = PropsUtil.getProperties("lms.admin.action.type", true); + AdminActionType[] adminActionTypes = new AdminActionType[properties.size()]; + int currentAdminActionType = 0; + log.debug("PROPERTIES "+properties.size()); + for (Object key:properties.keySet()) { + String type=properties.getProperty(key.toString()); + log.debug("----TYPE "+type); + try { + AdminActionType actionType = (AdminActionType)getPortletClassLoader().loadClass(type).newInstance(); + adminActionTypes[currentAdminActionType++]=actionType; + } catch (ClassNotFoundException e) { + try { + String [] context = ((String) key).split("\\."); + if (Validator.isNotNull(context) && context.length == 2) { + context[1] = LMS_ACTIVITIES_LIST_PORTLET_ID; + } + log.debug("**********************CONTEXTTT "+context[1]); + ClassLoaderProxy classLoaderProxy = new ClassLoaderProxy(Class.forName(type, true, + PortletClassLoaderUtil.getClassLoader(context[1])).newInstance(), type, + PortletClassLoaderUtil.getClassLoader(context[1])); + adminActionTypes[currentAdminActionType++]=new AdminActionTypeClp(classLoaderProxy); + + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + } catch (ClassCastException e) { + e.printStackTrace(); + try { + ClassLoaderProxy classLoaderProxy = new ClassLoaderProxy(Class.forName(type, true, + getPortletClassLoader()).newInstance(), type, + getPortletClassLoader()); + adminActionTypes[currentAdminActionType++]=new AdminActionTypeClp(classLoaderProxy); + } catch (Throwable throwable) { + } + } catch (Throwable throwable) { + } + } + + AdminActionType[] actions = null; + + if(properties.size()==currentAdminActionType) { + actions = adminActionTypes; + } + else { + actions = Arrays.copyOf(adminActionTypes,currentAdminActionType); + } + + Arrays.sort(actions, new Comparator() { + @Override + public int compare(AdminActionType o1, AdminActionType o2) { + return ((Long) o2.getTypeId()).compareTo(o1.getTypeId()); + } + }); + + return actions; + } + + private static ClassLoader _portletClassLoader; + private static ClassLoader getPortletClassLoader() { + if(_portletClassLoader==null) { + ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); + if(currentClassLoader.equals(PortalClassLoaderUtil.getClassLoader())) { + _portletClassLoader=PortletClassLoaderUtil.getClassLoader(LMS_ACTIVITIES_LIST_PORTLET_ID); + } + else { + _portletClassLoader=currentClassLoader; + } + } + return _portletClassLoader; + } + + public AdminActionTypeRegistry() { + _actionTypes = _adminActionTypeThreadLocal.get(); + log.debug("ACTIONS "+_actionTypes); + if(Validator.isNull(_actionTypes)|| _actionTypes.isEmpty()|| !(_actionTypes.get(0) instanceof AdminActionType)) { + AdminActionType[] actionTypes = _getAdminActionTypes(); + _actionTypes=new UnmodifiableList(Arrays.asList(actionTypes)); + _adminActionTypeThreadLocal.set(_actionTypes); + + } + } + + public void refrehTypes(){ + _adminActionTypeThreadLocal.set(null); + } + + + public AdminActionType getAdminActionType(long typeId) { + for (AdminActionType actionType : _actionTypes) { + if(actionType.getTypeId()==typeId){ + return actionType; + } + } + return null; + } + + public List getAdminActionTypes() { + return _actionTypes; + } + + private List _actionTypes; + + private static ThreadLocal> + _adminActionTypeThreadLocal = + new AutoResetThreadLocal>( + AdminActionTypeRegistry.class + "._adminActionTypeThreadLocal"); +} diff --git a/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/BaseAdminActionType.java b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/BaseAdminActionType.java new file mode 100644 index 000000000..ba270e768 --- /dev/null +++ b/docroot/WEB-INF/service/com/liferay/lms/course/adminaction/BaseAdminActionType.java @@ -0,0 +1,37 @@ +package com.liferay.lms.course.adminaction; + +import java.io.Serializable; +import java.util.Locale; + +public class BaseAdminActionType implements AdminActionType, Serializable { + + /** + * + */ + private static final long serialVersionUID = -8299999140131518845L; + public static final long TYPE = 0; + + public long getTypeId(){ + return TYPE; + } + + public String getName(Locale locale){ + return ""; + } + + public String getHelpMessage(Locale locale){ + return ""; + } + + public String getPortletId(){ + return null; + } + + public boolean hasPermission(long userId){ + return true; + } + + public String getIcon(){ + return ""; + } +} diff --git a/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/BaseInscriptionType.java b/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/BaseInscriptionType.java index fb9b93901..76227b8b1 100644 --- a/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/BaseInscriptionType.java +++ b/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/BaseInscriptionType.java @@ -1,7 +1,9 @@ package com.liferay.lms.course.inscriptiontype; import java.io.Serializable; +import java.util.HashSet; import java.util.Locale; +import java.util.Set; import javax.portlet.PortletResponse; @@ -11,12 +13,15 @@ import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.upload.UploadRequest; +import com.liferay.portal.kernel.util.PropsUtil; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.model.GroupConstants; import com.liferay.portal.service.ServiceContext; public class BaseInscriptionType implements InscriptionType, Serializable { public static final long TYPE = 0; - + public long getTypeId(){ return TYPE; } @@ -34,7 +39,7 @@ public String setExtraContent(UploadRequest uploadRequest,PortletResponse portle } public String getPortletId(){ - return ""; + return null; } @Override @@ -56,4 +61,31 @@ public String getTitle(Locale locale) { public boolean canUnsubscribe() { return true; } + + @Override + public Set getGroupTypesAvailable(){ + Set sites = new HashSet(); + String site = PropsUtil.get("lms.site.types"); + if(Validator.isNotNull(site)){ + String[] ssites = site.split(","); + for(int i=0;i getGroupTypesAvailable(); + public boolean isActive(long companyId); } diff --git a/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeClp.java b/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeClp.java index 7fc8ea465..0471c5d0d 100644 --- a/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeClp.java +++ b/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeClp.java @@ -1,6 +1,7 @@ package com.liferay.lms.course.inscriptiontype; import java.util.Locale; +import java.util.Set; import javax.portlet.PortletResponse; @@ -187,7 +188,7 @@ public String getSpecificContentPage() { Object returnObj = null; try { - MethodKey getExpecificContentPageMethod = new MethodKey(clp.getClassName(), "getSpecificContentPage", Locale.class); + MethodKey getExpecificContentPageMethod = new MethodKey(clp.getClassName(), "getSpecificContentPage"); returnObj = clp.invoke(new MethodHandler(getExpecificContentPageMethod)); } catch (Throwable t) { @@ -206,13 +207,12 @@ public String getSpecificContentPage() { } @Override - public String setExtraContent(UploadRequest uploadRequest, - PortletResponse portletResponse, Course course) { + public String setExtraContent(UploadRequest uploadRequest,PortletResponse portletResponse,Course course) { Object returnObj = null; try { - MethodKey getExpecificContentPageMethod = new MethodKey(clp.getClassName(), "setExtraContent", UploadRequest.class, PortletResponse.class, Course.class); - returnObj = clp.invoke(new MethodHandler(getExpecificContentPageMethod, uploadRequest, portletResponse, course)); + MethodKey setExtraContentMethod = new MethodKey(clp.getClassName(), "setExtraContent", UploadRequest.class, PortletResponse.class, Course.class); + returnObj = clp.invoke(new MethodHandler(setExtraContentMethod, uploadRequest, portletResponse, course)); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); @@ -228,7 +228,53 @@ public String setExtraContent(UploadRequest uploadRequest, return ((String)returnObj); } + + @Override + public Set getGroupTypesAvailable() { + Object returnObj = null; + + try { + MethodKey getGroupTypesAvailableMethod = new MethodKey(clp.getClassName(), "getGroupTypesAvailable"); + returnObj = clp.invoke(new MethodHandler(getGroupTypesAvailableMethod)); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((Set)returnObj); + } + + @Override + public boolean isActive(long companyId) { + Object returnObj = null; + + try { + MethodKey isActiveMethod = new MethodKey(clp.getClassName(), "isActive", long.class); + returnObj = clp.invoke(new MethodHandler(isActiveMethod, companyId)); + } + catch (Throwable t) { + t = ClpSerializer.translateThrowable(t); + + if (t instanceof RuntimeException) { + throw (RuntimeException)t; + } + else { + throw new RuntimeException(t.getClass().getName() + + " is not a valid exception"); + } + } + + return ((Boolean)returnObj); + } } diff --git a/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeRegistry.java b/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeRegistry.java index 81da9019a..b75394ea6 100644 --- a/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeRegistry.java +++ b/docroot/WEB-INF/service/com/liferay/lms/course/inscriptiontype/InscriptionTypeRegistry.java @@ -88,10 +88,8 @@ private static ClassLoader getPortletClassLoader() { public InscriptionTypeRegistry() { _inscriptionTypes = _inscriptionTypeThreadLocal.get(); - if((Validator.isNull(_inscriptionTypes))|| - (_inscriptionTypes.isEmpty())|| - (!(_inscriptionTypes.get(0) instanceof InscriptionType))) { - InscriptionType[] inscriptionTypes = _getInscriptionTypes(); + if(Validator.isNull(_inscriptionTypes)|| _inscriptionTypes.isEmpty()|| !(_inscriptionTypes.get(0) instanceof InscriptionType)) { + InscriptionType[] inscriptionTypes = _getInscriptionTypes(); _inscriptionTypes=new UnmodifiableList(Arrays.asList(inscriptionTypes)); _inscriptionTypeThreadLocal.set(_inscriptionTypes); diff --git a/docroot/WEB-INF/src/com/liferay/lms/lar/ExportUtil.java b/docroot/WEB-INF/service/com/liferay/lms/lar/ExportUtil.java similarity index 95% rename from docroot/WEB-INF/src/com/liferay/lms/lar/ExportUtil.java rename to docroot/WEB-INF/service/com/liferay/lms/lar/ExportUtil.java index 35e05cabc..6d13c91e8 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/lar/ExportUtil.java +++ b/docroot/WEB-INF/service/com/liferay/lms/lar/ExportUtil.java @@ -13,7 +13,6 @@ import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.xml.Element; import com.liferay.portlet.documentlibrary.NoSuchFileEntryException; -import com.liferay.portlet.documentlibrary.model.DLFileEntry; import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil; public class ExportUtil { @@ -79,7 +78,7 @@ private static void saveLink(String href, long moduleId, PortletDataContext cont try { file = DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(uuid, Long.parseLong(fileGroupId)); - String pathqu = getEntryPath(context, file); + String pathqu = getEntryPath(context, file.getFileEntryId()); String pathFile = getDescriptionModulePath(context, moduleId); context.addZipEntry(pathqu, file); @@ -126,7 +125,7 @@ private static void saveImagen(String src, long moduleId, PortletDataContext con try { FileEntry file = DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(uuid, Long.parseLong(fileGroupId)); - String pathqu = getEntryPath(context, file); + String pathqu = getEntryPath(context, file.getFileEntryId()); String pathFile = getDescriptionModulePath(context, moduleId); context.addZipEntry(pathqu, file); @@ -158,12 +157,12 @@ private static String getDescriptionModulePath(PortletDataContext context, long return sb.toString(); } - private static String getEntryPath(PortletDataContext context, FileEntry file) { + public static String getEntryPath(PortletDataContext context, long fileEntryId) { StringBundler sb = new StringBundler(4); sb.append(context.getPortletPath("resourceactivity_WAR_liferaylmsportlet")); sb.append("/moduleentries/"); - sb.append(file.getFileEntryId()); + sb.append(fileEntryId); sb.append(".xml"); return sb.toString(); } @@ -184,7 +183,7 @@ public static void addZipEntry(LearningActivity actividad, long assetEntryId, Po public static String changeSpecialCharacter(String str) { String fullName = ""; - if(str.lastIndexOf(".")>0){ + if(str.lastIndexOf(".") > 0 && !str.endsWith(".")){ String name = str.substring(0, str.lastIndexOf(".")); String extension = str.substring(str.lastIndexOf(".")); fullName = name.replaceAll("[^a-zA-Z0-9]", "") + extension; diff --git a/docroot/WEB-INF/service/com/liferay/lms/learningactivity/BaseLearningActivityType.java b/docroot/WEB-INF/service/com/liferay/lms/learningactivity/BaseLearningActivityType.java index 69ad46baf..2a321aa56 100644 --- a/docroot/WEB-INF/service/com/liferay/lms/learningactivity/BaseLearningActivityType.java +++ b/docroot/WEB-INF/service/com/liferay/lms/learningactivity/BaseLearningActivityType.java @@ -8,6 +8,7 @@ import javax.portlet.ActionResponse; import javax.portlet.PortletResponse; +import com.liferay.lms.lar.ExportUtil; import com.liferay.lms.model.LearningActivity; import com.liferay.lms.model.LearningActivityResult; import com.liferay.lms.model.LearningActivityTry; @@ -177,7 +178,6 @@ public String getClassName() { @Override public AssetRenderer getAssetRenderer(LearningActivity larn) throws SystemException, PortalException { - // TODO Auto-generated method stub return null; } @@ -234,11 +234,11 @@ public String addZipEntry(LearningActivity actividad, Long assetEntryId,PortletD } log.info("file Title: " + title); - title = changeSpecialCharacter(title); + title = ExportUtil.changeSpecialCharacter(title); title += extension; log.info("title: " + title); - String pathqu = getEntryPath(context, docfile); + String pathqu = ExportUtil.getEntryPath(context, docfile.getFileEntryId()); String pathFile = getFilePath(context, docfile,actividad.getActId()); Element entryElementfe= entryElementLoc.addElement("dlfileentry"); entryElementfe.addAttribute("path", pathqu); @@ -270,21 +270,7 @@ public String addZipEntry(LearningActivity actividad, Long assetEntryId,PortletD } } - private static String changeSpecialCharacter(String str) { - - str = str.replaceAll("[^a-zA-Z0-9.]", ""); - return str; - } - private static String getEntryPath(PortletDataContext context, DLFileEntry file) { - - StringBundler sb = new StringBundler(4); - sb.append(context.getPortletPath("resourceactivity_WAR_liferaylmsportlet")); - sb.append("/moduleentries/"); - sb.append(file.getFileEntryId()); - sb.append(".xml"); - return sb.toString(); - } private static String getFilePath(PortletDataContext context,DLFileEntry file, long actId) { diff --git a/docroot/WEB-INF/service/com/liferay/lms/util/LmsConstant.java b/docroot/WEB-INF/service/com/liferay/lms/util/LmsConstant.java index e4697fa9a..71c6fbffe 100644 --- a/docroot/WEB-INF/service/com/liferay/lms/util/LmsConstant.java +++ b/docroot/WEB-INF/service/com/liferay/lms/util/LmsConstant.java @@ -32,4 +32,6 @@ public class LmsConstant { public final static String COURSETYPE_ICON_PORTLETFOLDER = "coursetype"; public final static String COURSETYPE_ICON_PORTLETFOLDER_DESCRIPTION = ""; + public static final long DEFAULT_PARENT_COURSE_ID = 0; + } diff --git a/docroot/WEB-INF/sql/indexes.properties b/docroot/WEB-INF/sql/indexes.properties deleted file mode 100644 index af291ba47..000000000 --- a/docroot/WEB-INF/sql/indexes.properties +++ /dev/null @@ -1,176 +0,0 @@ -IX_BD5C2361=Lms_ActivityTriesDeleted.ActIdStatus -IX_9BB02FE8=Lms_ActivityTriesDeleted.GroupId - -IX_6E7EC4FA=Lms_AuditEntry.CN_CP -IX_A9ACD23E=Lms_AuditEntry.CompanyId -IX_6820D040=Lms_AuditEntry.GroupId -IX_E3182346=Lms_AuditEntry.U_G -IX_1E118FED=Lms_AuditEntry.U_G_c -IX_301D31E4=Lms_AuditEntry.UserId - -IX_A9A7E97F=Lms_CheckP2pMailing.actId - -IX_DEF4F10C=Lms_Competence.CompanyId -IX_56DE4A8E=Lms_Competence.GroupId -IX_7E6C7712=Lms_Competence.UUID_G -IX_EA812898=Lms_Competence.Uuid - -IX_AABFFF7A=Lms_Course.CompanyId -IX_C9B5BF5A=Lms_Course.CompanyIdClosed -IX_F944A64E=Lms_Course.CompanyParentCourseId -IX_243A72BA=Lms_Course.FriendlyURL -IX_B852F6C6=Lms_Course.GroupCreatedId -IX_E1561C7C=Lms_Course.GroupId -IX_F367BA5C=Lms_Course.GroupIdClosed -IX_23547F50=Lms_Course.GroupIdParentCourseId -IX_999B22C2=Lms_Course.ParentCourseId -IX_F90F3D64=Lms_Course.UUID_G -IX_D92F6E28=Lms_Course.UserId -IX_684B7382=Lms_Course.UserIdGroupId -IX_97009E06=Lms_Course.Uuid -IX_999B22C2=Lms_Course.parentCourseId - -IX_4AF8B71=Lms_CourseCompetence.CourseCompetenceCondition -IX_F3F3D23D=Lms_CourseCompetence.Uuid -IX_17104179=Lms_CourseCompetence.courseId - -IX_8C107135=Lms_CourseResult.CourseId -IX_E84F40E7=Lms_CourseResult.CourseIdFinished -IX_8CF7C46F=Lms_CourseResult.CourseIdMultipleUserId -IX_388CC221=Lms_CourseResult.CourseIdMultipleUserIdFinished -IX_8CF7C46F=Lms_CourseResult.CourseIdMultipleUserIdStarted -IX_388CC221=Lms_CourseResult.CourseIdNotMultipleUserIdFinished -IX_8CF7C46F=Lms_CourseResult.CourseIdNotMultipleUserIdStarted -IX_BF5FDCB=Lms_CourseResult.CourseIdPassedFinished -IX_E5289353=Lms_CourseResult.CourseIdPassedMultipleUserId -IX_A4AA5B05=Lms_CourseResult.CourseIdPassedMultipleUserIdFinished -IX_E5289353=Lms_CourseResult.CourseIdPassedNotMultipleUserId -IX_A4AA5B05=Lms_CourseResult.CourseIdPassedNotMultipleUserIdFinished -IX_A4AA5B05=Lms_CourseResult.CourseIdPassedNotMultipleUserIdFinished2 -IX_B4BB8BC5=Lms_CourseResult.CourseIdStartDateMultipleUserId -IX_8C107135=Lms_CourseResult.CourseIdStarted -IX_583EFC25=Lms_CourseResult.UserId -IX_E5606419=Lms_CourseResult.c -IX_3F29EDEF=Lms_CourseResult.uc - -IX_B3E69260=Lms_CourseType.CompanyId -IX_9A6B92AC=Lms_CourseType.CourseTypeId - -IX_EB924F40=Lms_CourseTypeCalificationType.CourseTypeCalificationTypeId -IX_C2333876=Lms_CourseTypeCalificationType.CourseTypeId - -IX_B8D93ACB=Lms_CourseTypeCourseEval.CourseTypeCourseEvalId -IX_AAF2A5A3=Lms_CourseTypeCourseEval.CourseTypeId - -IX_E4E5DA7A=Lms_CourseTypeInscriptionType.CourseTypeId -IX_14979B52=Lms_CourseTypeInscriptionType.CourseTypeInscriptionTypeId - -IX_B878E519=Lms_CourseTypeLearningActivity.CourseTypeId -IX_AC299F06=Lms_CourseTypeLearningActivity.CourseTypeLearningActivityId - -IX_A40BAD46=Lms_CourseTypeTemplate.CourseTypeId -IX_5BD857E0=Lms_CourseTypeTemplate.CourseTypeTemplateId - -IX_48E2DCF1=Lms_LearningActivity.CompanyIdTypeId -IX_CA9C7713=Lms_LearningActivity.ModuleIdPriorityGreaterThan -IX_CA9C7713=Lms_LearningActivity.ModuleIdPriorityLessThan -IX_C1A494B8=Lms_LearningActivity.ModuleId_Weightinmodule -IX_7D8395E=Lms_LearningActivity.Precedence -IX_3ABA7B89=Lms_LearningActivity.TypeId -IX_75B864D6=Lms_LearningActivity.UUID_G -IX_A331EE54=Lms_LearningActivity.Uuid -IX_A674914A=Lms_LearningActivity.g -IX_D6755EC7=Lms_LearningActivity.g_m -IX_A26B5373=Lms_LearningActivity.g_t -IX_A907C93B=Lms_LearningActivity.m - -IX_4AEF2D40=Lms_LearningActivityResult.ActIdFinished -IX_2E4B457A=Lms_LearningActivityResult.ActIdMultipleUserId -IX_2E4B457A=Lms_LearningActivityResult.ActIdMultipleUserIdFinished -IX_2E4B457A=Lms_LearningActivityResult.ActIdMultipleUserIdStarted -IX_2E4B457A=Lms_LearningActivityResult.ActIdNotMultipleUserId -IX_2E4B457A=Lms_LearningActivityResult.ActIdNotMultipleUserIdFinished -IX_2E4B457A=Lms_LearningActivityResult.ActIdNotMultipleUserIdStarted -IX_86B3E524=Lms_LearningActivityResult.ActIdPassedFinished -IX_5E5BD95E=Lms_LearningActivityResult.ActIdPassedMultipleUserId -IX_5E5BD95E=Lms_LearningActivityResult.ActIdPassedMultipleUserIdFinished -IX_5E5BD95E=Lms_LearningActivityResult.ActIdPassedNotMultipleUserId -IX_5E5BD95E=Lms_LearningActivityResult.ActIdPassedNotMultipleUserIdFinished -IX_4AEF2D40=Lms_LearningActivityResult.ActIdStarted -IX_8F7CCC6=Lms_LearningActivityResult.UserIdActId -IX_8B143A37=Lms_LearningActivityResult.Uuid -IX_4AEF2D40=Lms_LearningActivityResult.ac -IX_2E4B457A=Lms_LearningActivityResult.act_user -IX_86B3E524=Lms_LearningActivityResult.ap -IX_9F67B375=Lms_LearningActivityResult.apd -IX_678F5817=Lms_LearningActivityResult.user - -IX_BAC99850=Lms_LearningActivityTry.ActIdMultipleUserId -IX_BAC99850=Lms_LearningActivityTry.ActIdMultipleUserIdStarted -IX_BAC99850=Lms_LearningActivityTry.ActIdNotMultipleUserId -IX_BAC99850=Lms_LearningActivityTry.ActIdNotMultipleUserIdStarted -IX_6C40B616=Lms_LearningActivityTry.ActIdStarted -IX_706EEA01=Lms_LearningActivityTry.UserId -IX_AC65C30D=Lms_LearningActivityTry.Uuid -IX_6C40B616=Lms_LearningActivityTry.act -IX_BAC99850=Lms_LearningActivityTry.act_u - -IX_87D5C4C9=Lms_Module.CompanyId -IX_306AE98B=Lms_Module.GroupId -IX_B29B7175=Lms_Module.UUID_G -IX_3ED54339=Lms_Module.UserId -IX_E045C191=Lms_Module.UserIdGroupId -IX_47B362D5=Lms_Module.Uuid - -IX_C5CE7C9=Lms_ModuleResult.ModuleIdFinished -IX_4D202C51=Lms_ModuleResult.ModuleIdMultipleUserId -IX_43FE6703=Lms_ModuleResult.ModuleIdMultipleUserIdFinished -IX_4D202C51=Lms_ModuleResult.ModuleIdNotMultipleUserId -IX_43FE6703=Lms_ModuleResult.ModuleIdNotMultipleUserIdFinished -IX_1767A2AD=Lms_ModuleResult.ModuleIdPassedFinished -IX_6A63F935=Lms_ModuleResult.ModuleIdPassedMultipleUserId -IX_6A63F935=Lms_ModuleResult.ModuleIdPassedMultipleUserIdFinished -IX_6A63F935=Lms_ModuleResult.ModuleIdPassedNotMultipleUserId -IX_6AA1FDE7=Lms_ModuleResult.ModuleIdPassedNotMultipleUserIdFinished -IX_40BB0076=Lms_ModuleResult.UserId -IX_7D47DB17=Lms_ModuleResult.m -IX_A588CBFB=Lms_ModuleResult.mp -IX_A378B6D1=Lms_ModuleResult.mu - -IX_A70D5A07=Lms_P2pActivity.ActId -IX_90AFBB41=Lms_P2pActivity.ActIdAndUserId -IX_8F36C430=Lms_P2pActivity.UserId -IX_E73266FE=Lms_P2pActivity.Uuid -IX_E2E22C19=Lms_P2pActivity.asignationsCompleted - -IX_70AAED8C=Lms_P2pActivityCorrections.ActIdAndUserId -IX_599E425D=Lms_P2pActivityCorrections.P2pActivityId -IX_85BFE7C0=Lms_P2pActivityCorrections.P2pActivityIdAndActIdDateNotNull -IX_86D5ED97=Lms_P2pActivityCorrections.P2pActivityIdAndUserId -IX_86D5ED97=Lms_P2pActivityCorrections.P2pActivityIdAndUserIdDateNotNull -IX_C0C0C045=Lms_P2pActivityCorrections.UserId -IX_331E1449=Lms_P2pActivityCorrections.Uuid - -IX_3AA8B3F6=Lms_Schedule.TeamId - -IX_8B8399FF=Lms_SurveyResult. -IX_ED91C253=Lms_SurveyResult.ActId -IX_2F35042C=Lms_SurveyResult.AnswerIdQuestionId -IX_8B8399FF=Lms_SurveyResult.QuestionId -IX_9AF915DE=Lms_SurveyResult.QuestionIdActId -IX_193F6564=Lms_SurveyResult.UserId -IX_2DB6CF4A=Lms_SurveyResult.Uuid - -IX_43412151=Lms_TestAnswer.Uuid -IX_31C145A=Lms_TestAnswer.ac -IX_558E7458=Lms_TestAnswer.q - -IX_CDBACDE9=Lms_TestQuestion.Uuid -IX_8D95C0F2=Lms_TestQuestion.ac - -IX_40D5BB91=Lms_UserCertificateDownload.UserIdCourseId - -IX_EB2113C1=Lms_UserCompetence.UserId -IX_B2E889B9=Lms_UserCompetence.UserIdCompetenceId -IX_253E9283=Lms_UserCompetence.UserIdCompetenceIdCourseId -IX_E1E7614D=Lms_UserCompetence.Uuid \ No newline at end of file diff --git a/docroot/WEB-INF/sql/indexes.sql b/docroot/WEB-INF/sql/indexes.sql deleted file mode 100644 index af7eb9bed..000000000 --- a/docroot/WEB-INF/sql/indexes.sql +++ /dev/null @@ -1,144 +0,0 @@ -create index IX_BD5C2361 on Lms_ActivityTriesDeleted (actId, status); -create index IX_9BB02FE8 on Lms_ActivityTriesDeleted (groupId); - -create index IX_6E7EC4FA on Lms_AuditEntry (classname, classPK); -create index IX_A9ACD23E on Lms_AuditEntry (companyId); -create index IX_6820D040 on Lms_AuditEntry (groupId); -create index IX_301D31E4 on Lms_AuditEntry (userId); -create index IX_E3182346 on Lms_AuditEntry (userId, groupId); -create index IX_1E118FED on Lms_AuditEntry (userId, groupId, classname); - -create index IX_A9A7E97F on Lms_CheckP2pMailing (actId); - -create index IX_DEF4F10C on Lms_Competence (companyId); -create index IX_56DE4A8E on Lms_Competence (groupId); -create index IX_EA812898 on Lms_Competence (uuid_); -create unique index IX_7E6C7712 on Lms_Competence (uuid_, groupId); - -create index IX_AABFFF7A on Lms_Course (companyId); -create index IX_C9B5BF5A on Lms_Course (companyId, closed); -create unique index IX_243A72BA on Lms_Course (companyId, friendlyURL); -create index IX_F944A64E on Lms_Course (companyId, parentCourseId); -create index IX_B852F6C6 on Lms_Course (groupCreatedId); -create index IX_E1561C7C on Lms_Course (groupId); -create index IX_F367BA5C on Lms_Course (groupId, closed); -create index IX_23547F50 on Lms_Course (groupId, parentCourseId); -create index IX_999B22C2 on Lms_Course (parentCourseId); -create index IX_D92F6E28 on Lms_Course (userId); -create index IX_684B7382 on Lms_Course (userId, groupId); -create index IX_97009E06 on Lms_Course (uuid_); -create unique index IX_F90F3D64 on Lms_Course (uuid_, groupId); - -create unique index IX_4AF8B71 on Lms_CourseCompetence (courseId, competenceId, condition_); -create index IX_17104179 on Lms_CourseCompetence (courseId, condition_); -create index IX_F3F3D23D on Lms_CourseCompetence (uuid_); - -create index IX_8C107135 on Lms_CourseResult (courseId); -create index IX_E5606419 on Lms_CourseResult (courseId, passed); -create index IX_BF5FDCB on Lms_CourseResult (courseId, passed, passedDate); -create index IX_A4AA5B05 on Lms_CourseResult (courseId, passed, passedDate, userId); -create index IX_E5289353 on Lms_CourseResult (courseId, passed, userId); -create index IX_E84F40E7 on Lms_CourseResult (courseId, passedDate); -create index IX_388CC221 on Lms_CourseResult (courseId, passedDate, userId); -create index IX_B4BB8BC5 on Lms_CourseResult (courseId, startDate, userId); -create index IX_8CF7C46F on Lms_CourseResult (courseId, userId); -create index IX_583EFC25 on Lms_CourseResult (userId); -create unique index IX_3F29EDEF on Lms_CourseResult (userId, courseId); - -create index IX_B3E69260 on Lms_CourseType (companyId); -create index IX_9A6B92AC on Lms_CourseType (courseTypeId); - -create index IX_EB924F40 on Lms_CourseTypeCalificationType (courseTypeCalificationTypeId); -create index IX_C2333876 on Lms_CourseTypeCalificationType (courseTypeId); - -create index IX_B8D93ACB on Lms_CourseTypeCourseEval (courseTypeEvalutationTypeId); -create index IX_AAF2A5A3 on Lms_CourseTypeCourseEval (courseTypeId); - -create index IX_E4E5DA7A on Lms_CourseTypeInscriptionType (courseTypeId); -create index IX_14979B52 on Lms_CourseTypeInscriptionType (courseTypeInscriptionTypeId); - -create index IX_B878E519 on Lms_CourseTypeLearningActivity (courseTypeId); -create index IX_AC299F06 on Lms_CourseTypeLearningActivity (courseTypeLearningActivityId); - -create index IX_A40BAD46 on Lms_CourseTypeTemplate (courseTypeId); -create index IX_5BD857E0 on Lms_CourseTypeTemplate (courseTypeTemplateId); - -create index IX_48E2DCF1 on Lms_LearningActivity (companyId, typeId); -create index IX_A674914A on Lms_LearningActivity (groupId); -create index IX_A26B5373 on Lms_LearningActivity (groupId, typeId); -create index IX_D6755EC7 on Lms_LearningActivity (groupId, weightinmodule); -create index IX_A907C93B on Lms_LearningActivity (moduleId); -create index IX_CA9C7713 on Lms_LearningActivity (moduleId, priority); -create index IX_C1A494B8 on Lms_LearningActivity (moduleId, weightinmodule); -create index IX_7D8395E on Lms_LearningActivity (precedence); -create index IX_3ABA7B89 on Lms_LearningActivity (typeId); -create index IX_A331EE54 on Lms_LearningActivity (uuid_); -create unique index IX_75B864D6 on Lms_LearningActivity (uuid_, groupId); - -create index IX_4AEF2D40 on Lms_LearningActivityResult (actId); -create index IX_86B3E524 on Lms_LearningActivityResult (actId, passed); -create index IX_9F67B375 on Lms_LearningActivityResult (actId, passed, endDate); -create index IX_5E5BD95E on Lms_LearningActivityResult (actId, passed, userId); -create index IX_2E4B457A on Lms_LearningActivityResult (actId, userId); -create index IX_678F5817 on Lms_LearningActivityResult (userId); -create unique index IX_8F7CCC6 on Lms_LearningActivityResult (userId, actId); -create index IX_8B143A37 on Lms_LearningActivityResult (uuid_); - -create index IX_6C40B616 on Lms_LearningActivityTry (actId); -create index IX_BAC99850 on Lms_LearningActivityTry (actId, userId); -create index IX_706EEA01 on Lms_LearningActivityTry (userId); -create index IX_AC65C30D on Lms_LearningActivityTry (uuid_); - -create index IX_87D5C4C9 on Lms_Module (companyId); -create index IX_306AE98B on Lms_Module (groupId); -create index IX_3ED54339 on Lms_Module (userId); -create index IX_E045C191 on Lms_Module (userId, groupId); -create index IX_47B362D5 on Lms_Module (uuid_); -create unique index IX_B29B7175 on Lms_Module (uuid_, groupId); - -create index IX_7D47DB17 on Lms_ModuleResult (moduleId); -create index IX_A588CBFB on Lms_ModuleResult (moduleId, passed); -create index IX_1767A2AD on Lms_ModuleResult (moduleId, passed, passedDate); -create index IX_6AA1FDE7 on Lms_ModuleResult (moduleId, passed, passedDate, userId); -create index IX_6A63F935 on Lms_ModuleResult (moduleId, passed, userId); -create index IX_C5CE7C9 on Lms_ModuleResult (moduleId, passedDate); -create index IX_43FE6703 on Lms_ModuleResult (moduleId, passedDate, userId); -create index IX_4D202C51 on Lms_ModuleResult (moduleId, userId); -create index IX_40BB0076 on Lms_ModuleResult (userId); -create unique index IX_A378B6D1 on Lms_ModuleResult (userId, moduleId); - -create index IX_A70D5A07 on Lms_P2pActivity (actId); -create index IX_90AFBB41 on Lms_P2pActivity (actId, userId); -create index IX_E2E22C19 on Lms_P2pActivity (asignationsCompleted); -create index IX_8F36C430 on Lms_P2pActivity (userId); -create index IX_E73266FE on Lms_P2pActivity (uuid_); - -create index IX_70AAED8C on Lms_P2pActivityCorrections (actId, userId); -create index IX_599E425D on Lms_P2pActivityCorrections (p2pActivityId); -create index IX_85BFE7C0 on Lms_P2pActivityCorrections (p2pActivityId, actId); -create index IX_86D5ED97 on Lms_P2pActivityCorrections (p2pActivityId, userId); -create index IX_C0C0C045 on Lms_P2pActivityCorrections (userId); -create index IX_331E1449 on Lms_P2pActivityCorrections (uuid_); - -create index IX_3AA8B3F6 on Lms_Schedule (teamId); - -create index IX_ED91C253 on Lms_SurveyResult (actId); -create index IX_2F35042C on Lms_SurveyResult (answerId, questionId); -create index IX_8B8399FF on Lms_SurveyResult (questionId); -create index IX_9AF915DE on Lms_SurveyResult (questionId, actId); -create index IX_193F6564 on Lms_SurveyResult (userId); -create index IX_2DB6CF4A on Lms_SurveyResult (uuid_); - -create index IX_31C145A on Lms_TestAnswer (actId); -create index IX_558E7458 on Lms_TestAnswer (questionId); -create index IX_43412151 on Lms_TestAnswer (uuid_); - -create index IX_8D95C0F2 on Lms_TestQuestion (actId); -create index IX_CDBACDE9 on Lms_TestQuestion (uuid_); - -create index IX_40D5BB91 on Lms_UserCertificateDownload (userId, courseId); - -create index IX_EB2113C1 on Lms_UserCompetence (userId); -create index IX_B2E889B9 on Lms_UserCompetence (userId, competenceId); -create unique index IX_253E9283 on Lms_UserCompetence (userId, competenceId, courseId); -create index IX_E1E7614D on Lms_UserCompetence (uuid_); \ No newline at end of file diff --git a/docroot/WEB-INF/sql/sequences.sql b/docroot/WEB-INF/sql/sequences.sql deleted file mode 100644 index e69de29bb..000000000 diff --git a/docroot/WEB-INF/sql/tables.sql b/docroot/WEB-INF/sql/tables.sql deleted file mode 100644 index 87c3e9508..000000000 --- a/docroot/WEB-INF/sql/tables.sql +++ /dev/null @@ -1,361 +0,0 @@ -create table Lms_ActitityTriesDeleted ( - activityTriesDeletedId LONG not null primary key, - actId LONG, - userId LONG, - startDate DATE null, - endDate DATE null, - status INTEGER -); - -create table Lms_ActivityTriesDeleted ( - activityTriesDeletedId LONG not null primary key, - groupId LONG, - actId LONG, - userId LONG, - startDate DATE null, - endDate DATE null, - status INTEGER -); - -create table Lms_AsynchronousProcessAudit ( - asynchronousProcessAuditId LONG not null primary key, - companyId LONG, - type_ VARCHAR(75) null, - classNameId LONG, - classPK LONG, - userId LONG, - createDate DATE null, - endDate DATE null, - status INTEGER, - statusMessage STRING null -); - -create table Lms_AuditEntry ( - auditId LONG not null primary key, - auditDate DATE null, - companyId LONG, - groupId LONG, - userId LONG, - classname VARCHAR(75) null, - action VARCHAR(75) null, - extradata TEXT null, - classPK LONG, - associationClassPK LONG -); - -create table Lms_CheckP2pMailing ( - checkP2pId LONG not null primary key, - actId LONG, - date_ DATE null -); - -create table Lms_Competence ( - uuid_ VARCHAR(75) null, - competenceId LONG not null primary key, - companyId LONG, - groupId LONG, - userId LONG, - status INTEGER, - statusByUserId LONG, - statusByUserName VARCHAR(75) null, - statusDate DATE null, - title STRING null, - description STRING null, - page VARCHAR(75) null, - generateCertificate BOOLEAN, - diplomaTemplate STRING null, - diplomaBackground LONG, - diplomaAdditional LONG -); - -create table Lms_Course ( - uuid_ VARCHAR(75) null, - courseId LONG not null primary key, - parentCourseId LONG, - companyId LONG, - groupId LONG, - userId LONG, - userName VARCHAR(75) null, - groupCreatedId LONG, - createDate DATE null, - modifiedDate DATE null, - status INTEGER, - statusByUserId LONG, - statusByUserName VARCHAR(75) null, - statusDate DATE null, - title STRING null, - description STRING null, - friendlyURL VARCHAR(100) null, - startDate DATE null, - endDate DATE null, - icon LONG, - CourseEvalId LONG, - CourseExtraData TEXT null, - closed BOOLEAN, - maxusers LONG, - calificationType LONG, - inscriptionType LONG, - welcome BOOLEAN, - welcomeMsg TEXT null, - welcomeSubject VARCHAR(75) null, - deniedInscription BOOLEAN, - deniedInscriptionMsg TEXT null, - deniedInscriptionSubject VARCHAR(75) null, - goodbye BOOLEAN, - goodbyeMsg TEXT null, - goodbyeSubject VARCHAR(75) null, - isLinked BOOLEAN, - executionStartDate DATE null, - executionEndDate DATE null -); - -create table Lms_CourseCompetence ( - uuid_ VARCHAR(75) null, - CourcompetenceId LONG not null primary key, - courseId LONG, - competenceId LONG, - condition_ BOOLEAN -); - -create table Lms_CourseResult ( - crId LONG not null primary key, - courseId LONG, - result LONG, - comments TEXT null, - userId LONG, - passed BOOLEAN, - startDate DATE null, - passedDate DATE null, - allowStartDate DATE null, - allowFinishDate DATE null, - extraData TEXT null -); - -create table Lms_CourseType ( - courseTypeId LONG not null primary key, - companyId LONG, - userId LONG, - groupId LONG, - userName VARCHAR(75) null, - createDate DATE null, - modifiedDate DATE null, - name STRING null, - description STRING null, - iconId LONG -); - -create table Lms_CourseTypeCalificationType ( - courseTypeCalificationTypeId LONG not null primary key, - courseTypeId LONG, - calificationType LONG -); - -create table Lms_CourseTypeCourseEval ( - courseTypeEvalutationTypeId LONG not null primary key, - courseTypeId LONG, - courseEvalId VARCHAR(75) null -); - -create table Lms_CourseTypeInscriptionType ( - courseTypeInscriptionTypeId LONG not null primary key, - courseTypeId LONG, - inscriptionType LONG -); - -create table Lms_CourseTypeLearningActivity ( - courseTypeLearningActivityId LONG not null primary key, - courseTypeId LONG, - learningActivityTypeId LONG -); - -create table Lms_CourseTypeTemplate ( - courseTypeTemplateId LONG not null primary key, - courseTypeId LONG, - templateId LONG -); - -create table Lms_LearningActivity ( - uuid_ VARCHAR(75) null, - actId LONG not null primary key, - companyId LONG, - userId LONG, - groupId LONG, - userName VARCHAR(75) null, - createDate DATE null, - modifiedDate DATE null, - status INTEGER, - statusByUserId LONG, - statusByUserName VARCHAR(75) null, - statusDate DATE null, - title STRING null, - description STRING null, - typeId INTEGER, - startdate DATE null, - enddate DATE null, - precedence LONG, - tries LONG, - passpuntuation INTEGER, - priority LONG, - moduleId LONG, - extracontent TEXT null, - feedbackCorrect VARCHAR(1000) null, - feedbackNoCorrect VARCHAR(1000) null, - weightinmodule LONG, - commentsActivated BOOLEAN, - linkedActivityId LONG -); - -create table Lms_LearningActivityResult ( - uuid_ VARCHAR(75) null, - larId LONG not null primary key, - actId LONG, - userId LONG, - result LONG, - startDate DATE null, - endDate DATE null, - latId LONG, - comments TEXT null, - passed BOOLEAN -); - -create table Lms_LearningActivityTry ( - uuid_ VARCHAR(75) null, - latId LONG not null primary key, - actId LONG, - userId LONG, - startDate DATE null, - result LONG, - endDate DATE null, - endUserDate DATE null, - tryData VARCHAR(75) null, - tryResultData TEXT null, - comments TEXT null -); - -create table Lms_LmsPrefs ( - companyId LONG not null primary key, - teacherRole LONG, - editorRole LONG, - lmsTemplates VARCHAR(75) null, - activities VARCHAR(75) null, - courseevals VARCHAR(75) null, - scoretranslators VARCHAR(75) null, - inscriptionTypes VARCHAR(75) null, - usersResults LONG, - debugScorm BOOLEAN, - hasAPILicence BOOLEAN, - showHideActivity BOOLEAN, - viewCoursesFinished BOOLEAN -); - -create table Lms_Module ( - uuid_ VARCHAR(75) null, - moduleId LONG not null primary key, - companyId LONG, - groupId LONG, - userId LONG, - userName VARCHAR(75) null, - createDate DATE null, - modifiedDate DATE null, - title STRING null, - description STRING null, - ordern LONG, - startDate DATE null, - endDate DATE null, - icon LONG, - precedence LONG, - allowedTime LONG -); - -create table Lms_ModuleResult ( - moduleId LONG, - result LONG, - comments VARCHAR(75) null, - userId LONG, - startDate DATE null, - passed BOOLEAN, - mrId LONG not null primary key, - passedDate DATE null -); - -create table Lms_P2pActivity ( - uuid_ VARCHAR(75) null, - p2pActivityId LONG not null primary key, - actId LONG, - userId LONG, - fileEntryId LONG, - countCorrections LONG, - description TEXT null, - date_ DATE null, - asignationsCompleted BOOLEAN -); - -create table Lms_P2pActivityCorrections ( - uuid_ VARCHAR(75) null, - p2pActivityCorrectionsId LONG not null primary key, - p2pActivityId LONG, - userId LONG, - actId LONG, - description TEXT null, - date_ DATE null, - fileEntryId LONG, - result LONG -); - -create table Lms_Schedule ( - secheduleId LONG not null primary key, - teamId LONG, - startDate DATE null, - endDate DATE null -); - -create table Lms_SurveyResult ( - uuid_ VARCHAR(75) null, - surveyResultId LONG not null primary key, - actId LONG, - latId LONG, - questionId LONG, - answerId LONG, - userId LONG, - freeAnswer TEXT null -); - -create table Lms_TestAnswer ( - uuid_ VARCHAR(75) null, - answerId LONG not null primary key, - questionId LONG, - actId LONG, - precedence LONG, - answer TEXT null, - isCorrect BOOLEAN, - feedbackCorrect VARCHAR(1000) null, - feedbacknocorrect VARCHAR(1000) null -); - -create table Lms_TestQuestion ( - uuid_ VARCHAR(75) null, - questionId LONG not null primary key, - actId LONG, - text_ TEXT null, - questionType LONG, - weight LONG, - penalize BOOLEAN, - extracontent TEXT null -); - -create table Lms_UserCertificateDownload ( - userId LONG not null, - courseId LONG not null, - competenceId LONG not null, - downloadDate DATE null, - primary key (userId, courseId, competenceId) -); - -create table Lms_UserCompetence ( - uuid_ VARCHAR(75) null, - usercompId LONG not null primary key, - userId LONG, - competenceId LONG, - compDate DATE null, - courseId LONG -); \ No newline at end of file diff --git a/docroot/WEB-INF/src/META-INF/portlet-hbm.xml b/docroot/WEB-INF/src/META-INF/portlet-hbm.xml index 4f135e2ce..d19b054d4 100644 --- a/docroot/WEB-INF/src/META-INF/portlet-hbm.xml +++ b/docroot/WEB-INF/src/META-INF/portlet-hbm.xml @@ -57,6 +57,7 @@ + diff --git a/docroot/WEB-INF/src/META-INF/portlet-model-hints.xml b/docroot/WEB-INF/src/META-INF/portlet-model-hints.xml index 50e39650f..bb0aca5a7 100644 --- a/docroot/WEB-INF/src/META-INF/portlet-model-hints.xml +++ b/docroot/WEB-INF/src/META-INF/portlet-model-hints.xml @@ -21,6 +21,7 @@ + diff --git a/docroot/WEB-INF/src/META-INF/portlet-orm.xml b/docroot/WEB-INF/src/META-INF/portlet-orm.xml index 008346f96..aff48d8df 100644 --- a/docroot/WEB-INF/src/META-INF/portlet-orm.xml +++ b/docroot/WEB-INF/src/META-INF/portlet-orm.xml @@ -44,6 +44,7 @@ + diff --git a/docroot/WEB-INF/src/com/liferay/lms/BaseCourseAdminPortlet.java b/docroot/WEB-INF/src/com/liferay/lms/BaseCourseAdminPortlet.java index 17c5573e3..3542d6507 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/BaseCourseAdminPortlet.java +++ b/docroot/WEB-INF/src/com/liferay/lms/BaseCourseAdminPortlet.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; @@ -531,6 +532,7 @@ public void closeCourse(ActionRequest actionRequest, ActionResponse actionRespon public void openCourse(ActionRequest actionRequest,ActionResponse actionResponse) throws Exception { long courseId = ParamUtil.getLong(actionRequest, "courseId", 0); + log.debug("::OPEN COURSE:: courseId "+courseId); if (courseId > 0) { CourseLocalServiceUtil.openCourse(courseId); } @@ -575,8 +577,10 @@ public void saveCourse(ActionRequest actionRequest, ActionResponse actionRespons } Map titleMap = LmsLocaleUtil.getLocalizationMap(uploadRequest, "title"); + if(!localeDefault.equals(themeDisplay.getLocale())) + titleMap.put(localeDefault, titleMap.get(themeDisplay.getLocale())); - if(titleMap == null || Validator.isNull(titleMap.get(localeDefault))){ + if(titleMap == null || Validator.isNull(titleMap.get(themeDisplay.getLocale()))){ SessionErrors.add(actionRequest, "title-required"); actionResponse.setRenderParameter("courseId", String.valueOf(courseId)); actionResponse.setRenderParameter("redirect", redirect); @@ -1506,266 +1510,308 @@ protected void doDispatch(RenderRequest renderRequest, public void serveResource(ResourceRequest request, ResourceResponse response)throws PortletException, IOException { ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); - String action = ParamUtil.getString(request, "action"); - - if(action.equals("exportCourse")){ - JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); - try { - - ServiceContext serviceContext = ServiceContextFactory.getInstance(Course.class.getName(), request); - long groupId = ParamUtil.getLong(request, "groupId", 0); - - - if (themeDisplay.getPermissionChecker().hasPermission(groupId, Course.class.getName(), groupId, ActionKeys.UPDATE)) { - String fileName = ParamUtil.getString(request, "exportFileName", "New course exported"); - if(fileName.contains("/")){ - fileName=fileName.replaceAll("/", "-"); - } - if(!(Validator.isNotNull(fileName)) || !(fileName.length()>0) || !(fileName.contains(".lar")) ) - jsonObject.put("error", LanguageUtil.get(themeDisplay.getLocale(), "course.export.badformat")); - else{ - ClusterNode nodo = ClusterExecutorUtil.getLocalClusterNode(); - String clusterNodoId = nodo == null ? StringPool.DASH : nodo.getClusterNodeId(); - - String key = ParamUtil.getString(request, "key", null); - String newKey = clusterNodoId + StringPool.UNDERLINE + themeDisplay.getCompanyId() + StringPool.UNDERLINE + groupId; - - if (!StringPool.DASH.equals(clusterNodoId) && !ClusterExecutorUtil.isClusterNodeAlive(clusterNodoId)) { - jsonObject.put("error", "deadnode"); - } else { - if (Validator.isNull(key) && MultiVMPoolUtil.get("exportCourseCache", key) != null) { // Pide exportacion pero ya hay una en curso - jsonObject.put("status", "generating"); - jsonObject.put("key", newKey); - } else if (Validator.isNull(key) && MultiVMPoolUtil.get("exportCourseCache", key) == null) { // Pide exportacion y no hay ninguna en curso - AsynchronousProcessAudit process = AsynchronousProcessAuditLocalServiceUtil.addAsynchronousProcessAudit(themeDisplay.getCompanyId(), themeDisplay.getUserId(), Course.class.getName(), "liferay/lms/courseExport"); - Message message=new Message(); - message.put("asynchronousProcessAuditId", process.getAsynchronousProcessAuditId()); - message.put("groupId", groupId); - message.put("fileName", fileName); - message.put("key", key); - message.put("themeDisplay", themeDisplay); - message.put("serviceContext", serviceContext); - MessageBusUtil.sendMessage("liferay/lms/courseExport", message); - jsonObject.put("status", "generating"); - jsonObject.put("key", newKey); - } else if (Validator.isNotNull(key) && MultiVMPoolUtil.get("exportCourseCache", key) == null){ // Ha pedido exportacion y ya ha acabado - SessionMessages.add(request, "courseadmin.export.confirmation.success"); - jsonObject.put("status", "ready"); - jsonObject.put("key", key); - } else { // Ha pedido una exportacion y aun esta trabajando - jsonObject.put("status", "generating"); - jsonObject.put("key", key); - } - } + if(request.getResourceID() != null && request.getResourceID().equals("searchGroupTypes") ){ + long inscriptionTypeId = ParamUtil.getLong(request, "inscriptionTypeId",0); + log.debug("inscriptionTypeId: "+inscriptionTypeId); + + JSONArray jsonArray = JSONFactoryUtil.createJSONArray(); + + InscriptionTypeRegistry inscription = new InscriptionTypeRegistry(); + InscriptionType inscriptionType = inscription.getInscriptionType(inscriptionTypeId); + if (inscriptionType != null) { + Set groupTypeIds = inscriptionType.getGroupTypesAvailable(); + + for (Integer groupTypeId : groupTypeIds) { + JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); + switch(groupTypeId){ + case GroupConstants.TYPE_SITE_OPEN: + jsonObject.put("id", GroupConstants.TYPE_SITE_OPEN); + jsonObject.put("name", LanguageUtil.get(themeDisplay.getLocale(), GroupConstants.TYPE_SITE_OPEN_LABEL)); + break; + case GroupConstants.TYPE_SITE_RESTRICTED: + jsonObject.put("id", GroupConstants.TYPE_SITE_RESTRICTED); + jsonObject.put("name", LanguageUtil.get(themeDisplay.getLocale(), GroupConstants.TYPE_SITE_RESTRICTED_LABEL)); + break; + case GroupConstants.TYPE_SITE_PRIVATE: + jsonObject.put("id", GroupConstants.TYPE_SITE_PRIVATE); + jsonObject.put("name", LanguageUtil.get(themeDisplay.getLocale(), GroupConstants.TYPE_SITE_PRIVATE_LABEL)); + break; } - - } else { - jsonObject.put("error", "bad-permission"); - } - }catch(Exception e){ - //log.debug(" Error: "+e.getMessage()); - e.printStackTrace(); - jsonObject.put("error", e.getMessage()); - } finally { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json;charset=UTF-8"); - - PrintWriter writer = response.getWriter(); - writer.write(jsonObject.toString()); - } - } else if(action.equals("export")){ - - Role commmanager = null; - LmsPrefs prefs = null; - try { - commmanager = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.SITE_MEMBER); - prefs=LmsPrefsLocalServiceUtil.getLmsPrefs(themeDisplay.getCompanyId()); - } catch (PortalException e) { - if(log.isDebugEnabled()){ - e.printStackTrace(); - } - } catch (SystemException e) { - if(log.isDebugEnabled()){ - e.printStackTrace(); + jsonArray.put(jsonObject); } } - - - long courseId = ParamUtil.getLong(request, "courseId",0); - long roleId = ParamUtil.getLong(request, "roleId",0); - - List users = new ArrayList(); - - UserDisplayTerms displayTerms = new UserDisplayTerms(request); - - if(roleId==commmanager.getRoleId()){ - users = displayTerms.getStudents(courseId, QueryUtil.ALL_POS, QueryUtil.ALL_POS); - }else if(roleId == prefs.getTeacherRole()){ - users = displayTerms.getTeachers(courseId, QueryUtil.ALL_POS, QueryUtil.ALL_POS); - }else if(roleId == prefs.getEditorRole()){ - users = displayTerms.getEditors(courseId, QueryUtil.ALL_POS, QueryUtil.ALL_POS); - } + + log.debug("groupTypeIds: "+jsonArray.length()); response.setCharacterEncoding("UTF-8"); - response.setContentType(ContentTypes.TEXT_CSV_UTF8); - response.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=users.csv"); - - byte b[] = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; - - response.getPortletOutputStream().write(b); + response.setContentType("application/json;charset=UTF-8"); + + PrintWriter writer = response.getWriter(); + writer.write(jsonArray.toString()); + }else{ - CSVWriter writer = new CSVWriter(new OutputStreamWriter( - response.getPortletOutputStream(), StringPool.UTF8),CharPool.SEMICOLON); + String action = ParamUtil.getString(request, "action"); - String authType = PropsUtil.get(PropsKeys.COMPANY_SECURITY_AUTH_TYPE); - try { - Company company = CompanyLocalServiceUtil.getCompany(themeDisplay.getCompanyId()); - if (Validator.isNotNull(company)) { - authType = company.getAuthType(); + if(action.equals("exportCourse")){ + JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); + try { + + ServiceContext serviceContext = ServiceContextFactory.getInstance(Course.class.getName(), request); + long groupId = ParamUtil.getLong(request, "groupId", 0); + + + if (themeDisplay.getPermissionChecker().hasPermission(groupId, Course.class.getName(), groupId, ActionKeys.UPDATE)) { + String fileName = ParamUtil.getString(request, "exportFileName", "New course exported"); + if(fileName.contains("/")){ + fileName=fileName.replaceAll("/", "-"); + } + if(!(Validator.isNotNull(fileName)) || !(fileName.length()>0) || !(fileName.contains(".lar")) ) + jsonObject.put("error", LanguageUtil.get(themeDisplay.getLocale(), "course.export.badformat")); + else{ + ClusterNode nodo = ClusterExecutorUtil.getLocalClusterNode(); + String clusterNodoId = nodo == null ? StringPool.DASH : nodo.getClusterNodeId(); + + String key = ParamUtil.getString(request, "key", null); + String newKey = clusterNodoId + StringPool.UNDERLINE + themeDisplay.getCompanyId() + StringPool.UNDERLINE + groupId; + + if (!StringPool.DASH.equals(clusterNodoId) && !ClusterExecutorUtil.isClusterNodeAlive(clusterNodoId)) { + jsonObject.put("error", "deadnode"); + } else { + if (Validator.isNull(key) && MultiVMPoolUtil.get("exportCourseCache", key) != null) { // Pide exportacion pero ya hay una en curso + jsonObject.put("status", "generating"); + jsonObject.put("key", newKey); + } else if (Validator.isNull(key) && MultiVMPoolUtil.get("exportCourseCache", key) == null) { // Pide exportacion y no hay ninguna en curso + AsynchronousProcessAudit process = AsynchronousProcessAuditLocalServiceUtil.addAsynchronousProcessAudit(themeDisplay.getCompanyId(), themeDisplay.getUserId(), Course.class.getName(), "liferay/lms/courseExport"); + Message message=new Message(); + message.put("asynchronousProcessAuditId", process.getAsynchronousProcessAuditId()); + message.put("groupId", groupId); + message.put("fileName", fileName); + message.put("key", key); + message.put("themeDisplay", themeDisplay); + message.put("serviceContext", serviceContext); + MessageBusUtil.sendMessage("liferay/lms/courseExport", message); + jsonObject.put("status", "generating"); + jsonObject.put("key", newKey); + } else if (Validator.isNotNull(key) && MultiVMPoolUtil.get("exportCourseCache", key) == null){ // Ha pedido exportacion y ya ha acabado + SessionMessages.add(request, "courseadmin.export.confirmation.success"); + jsonObject.put("status", "ready"); + jsonObject.put("key", key); + } else { // Ha pedido una exportacion y aun esta trabajando + jsonObject.put("status", "generating"); + jsonObject.put("key", key); + } + } + } + + } else { + jsonObject.put("error", "bad-permission"); + } + }catch(Exception e){ + //log.debug(" Error: "+e.getMessage()); + e.printStackTrace(); + jsonObject.put("error", e.getMessage()); + } finally { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json;charset=UTF-8"); + + PrintWriter writer = response.getWriter(); + writer.write(jsonObject.toString()); } - } catch (PortalException e) { - log.error("Se ha producido un error al obtener el tipo de login de usuario (authType) para companyId=" + themeDisplay.getCompanyId(), e); - } catch (SystemException e) { - log.error("Se ha producido un error al obtener el tipo de login de usuario (authType) para companyId=" + themeDisplay.getCompanyId(), e); - } - - String[] header = new String[5]; - - if (CompanyConstants.AUTH_TYPE_SN.equalsIgnoreCase(authType)) { - header[0] = LanguageUtil.get(themeDisplay.getLocale(), "screen-name"); - }else if(CompanyConstants.AUTH_TYPE_EA.equalsIgnoreCase(authType)){ - header[0] = LanguageUtil.get(themeDisplay.getLocale(), "email-address"); - }else{ - header[0] = LanguageUtil.get(themeDisplay.getLocale(), "user-id"); - } - - header[1] = LanguageUtil.get(themeDisplay.getLocale(), "first-name"); - header[2] = LanguageUtil.get(themeDisplay.getLocale(), "last-name"); - header[3] = LanguageUtil.get(themeDisplay.getLocale(), "start-date"); - header[4] = LanguageUtil.get(themeDisplay.getLocale(), "end-date"); - - writer.writeNext(header); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - - CourseResult courseResult = null; - String fechaIni,fechaFin = new String(); - - for(User user:users){ + + } else if(action.equals("export")){ + + Role commmanager = null; + LmsPrefs prefs = null; try { - courseResult=CourseResultLocalServiceUtil.getCourseResultByCourseAndUser(courseId, user.getUserId()); + commmanager = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.SITE_MEMBER); + prefs=LmsPrefsLocalServiceUtil.getLmsPrefs(themeDisplay.getCompanyId()); + } catch (PortalException e) { + if(log.isDebugEnabled()){ + e.printStackTrace(); + } } catch (SystemException e) { - if(log.isDebugEnabled())e.printStackTrace(); + if(log.isDebugEnabled()){ + e.printStackTrace(); + } } - fechaIni = (courseResult!=null&&courseResult.getAllowStartDate() != null)?sdf.format(courseResult.getAllowStartDate()):StringPool.BLANK; - fechaFin = (courseResult!=null&&courseResult.getAllowFinishDate() != null)?sdf.format(courseResult.getAllowFinishDate()):StringPool.BLANK; - - String[] result = new String[5]; + + long courseId = ParamUtil.getLong(request, "courseId",0); + long roleId = ParamUtil.getLong(request, "roleId",0); + + List users = new ArrayList(); + + UserDisplayTerms displayTerms = new UserDisplayTerms(request); + + if(roleId==commmanager.getRoleId()){ + users = displayTerms.getStudents(courseId, QueryUtil.ALL_POS, QueryUtil.ALL_POS); + }else if(roleId == prefs.getTeacherRole()){ + users = displayTerms.getTeachers(courseId, QueryUtil.ALL_POS, QueryUtil.ALL_POS); + }else if(roleId == prefs.getEditorRole()){ + users = displayTerms.getEditors(courseId, QueryUtil.ALL_POS, QueryUtil.ALL_POS); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType(ContentTypes.TEXT_CSV_UTF8); + response.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=users.csv"); + + byte b[] = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; + + response.getPortletOutputStream().write(b); + + CSVWriter writer = new CSVWriter(new OutputStreamWriter( + response.getPortletOutputStream(), StringPool.UTF8),CharPool.SEMICOLON); + + String authType = PropsUtil.get(PropsKeys.COMPANY_SECURITY_AUTH_TYPE); + try { + Company company = CompanyLocalServiceUtil.getCompany(themeDisplay.getCompanyId()); + if (Validator.isNotNull(company)) { + authType = company.getAuthType(); + } + } catch (PortalException e) { + log.error("Se ha producido un error al obtener el tipo de login de usuario (authType) para companyId=" + themeDisplay.getCompanyId(), e); + } catch (SystemException e) { + log.error("Se ha producido un error al obtener el tipo de login de usuario (authType) para companyId=" + themeDisplay.getCompanyId(), e); + } + + String[] header = new String[5]; if (CompanyConstants.AUTH_TYPE_SN.equalsIgnoreCase(authType)) { - result[0] = user.getScreenName(); + header[0] = LanguageUtil.get(themeDisplay.getLocale(), "screen-name"); }else if(CompanyConstants.AUTH_TYPE_EA.equalsIgnoreCase(authType)){ - result[0] = user.getEmailAddress(); + header[0] = LanguageUtil.get(themeDisplay.getLocale(), "email-address"); }else{ - result[0] = String.valueOf(user.getUserId()); + header[0] = LanguageUtil.get(themeDisplay.getLocale(), "user-id"); } - result[1] = user.getFirstName(); - result[2] = user.getLastName(); - result[3] = fechaIni; - result[4] = fechaFin; - - writer.writeNext(result); - } - - writer.flush(); - writer.close(); - response.getPortletOutputStream().flush(); - response.getPortletOutputStream().close(); - }else if(action.equals("getCourses")){ - JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray(); - - String courseTitle = ParamUtil.getString(request, "courseTitle"); - long courseId = ParamUtil.getLong(request, "courseId"); - long selectedGroupId = ParamUtil.get(request,"selectedGroupId",-1); - int state = ParamUtil.getInteger(request, "state",WorkflowConstants.STATUS_APPROVED); - long columnId = ParamUtil.getLong(request, "columnId"); - String expandoValue = ParamUtil.getString(request, "expandoValue"); - - boolean isAdmin = false; - try { - isAdmin = RoleLocalServiceUtil.hasUserRole(themeDisplay.getUserId(), RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.ADMINISTRATOR).getRoleId()) - || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.UPDATE) - || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.DELETE) - || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.PERMISSIONS) - || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "PUBLISH") - || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "COURSEEDITOR") - || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "ASSIGN_MEMBERS"); + header[1] = LanguageUtil.get(themeDisplay.getLocale(), "first-name"); + header[2] = LanguageUtil.get(themeDisplay.getLocale(), "last-name"); + header[3] = LanguageUtil.get(themeDisplay.getLocale(), "start-date"); + header[4] = LanguageUtil.get(themeDisplay.getLocale(), "end-date"); - } catch (SystemException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (PortalException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - long groupId = themeDisplay.getScopeGroupId(); - if(selectedGroupId>-1){ - groupId = selectedGroupId; - } - - int closed = -1; - if(state!=WorkflowConstants.STATUS_ANY){ - if(state==WorkflowConstants.STATUS_APPROVED){ - closed = 0; + writer.writeNext(header); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + + CourseResult courseResult = null; + String fechaIni,fechaFin = new String(); + + for(User user:users){ + try { + courseResult=CourseResultLocalServiceUtil.getCourseResultByCourseAndUser(courseId, user.getUserId()); + } catch (SystemException e) { + if(log.isDebugEnabled())e.printStackTrace(); + } + + fechaIni = (courseResult!=null&&courseResult.getAllowStartDate() != null)?sdf.format(courseResult.getAllowStartDate()):StringPool.BLANK; + fechaFin = (courseResult!=null&&courseResult.getAllowFinishDate() != null)?sdf.format(courseResult.getAllowFinishDate()):StringPool.BLANK; + + String[] result = new String[5]; + + if (CompanyConstants.AUTH_TYPE_SN.equalsIgnoreCase(authType)) { + result[0] = user.getScreenName(); + }else if(CompanyConstants.AUTH_TYPE_EA.equalsIgnoreCase(authType)){ + result[0] = user.getEmailAddress(); + }else{ + result[0] = String.valueOf(user.getUserId()); + } + + result[1] = user.getFirstName(); + result[2] = user.getLastName(); + result[3] = fechaIni; + result[4] = fechaFin; + + writer.writeNext(result); } - else if(state==WorkflowConstants.STATUS_INACTIVE){ - closed = 1; + + writer.flush(); + writer.close(); + response.getPortletOutputStream().flush(); + response.getPortletOutputStream().close(); + }else if(action.equals("getCourses")){ + JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray(); + + String courseTitle = ParamUtil.getString(request, "courseTitle"); + long courseId = ParamUtil.getLong(request, "courseId"); + long selectedGroupId = ParamUtil.get(request,"selectedGroupId",-1); + int state = ParamUtil.getInteger(request, "state",WorkflowConstants.STATUS_APPROVED); + long columnId = ParamUtil.getLong(request, "columnId"); + String expandoValue = ParamUtil.getString(request, "expandoValue"); + + boolean isAdmin = false; + try { + isAdmin = RoleLocalServiceUtil.hasUserRole(themeDisplay.getUserId(), RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.ADMINISTRATOR).getRoleId()) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.UPDATE) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.DELETE) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.PERMISSIONS) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "PUBLISH") + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "COURSEEDITOR") + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "ASSIGN_MEMBERS"); + + } catch (SystemException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (PortalException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } + + long groupId = themeDisplay.getScopeGroupId(); + if(selectedGroupId>-1){ + groupId = selectedGroupId; + } + + int closed = -1; + if(state!=WorkflowConstants.STATUS_ANY){ + if(state==WorkflowConstants.STATUS_APPROVED){ + closed = 0; + } + else if(state==WorkflowConstants.STATUS_INACTIVE){ + closed = 1; + } + } + + String[] templates = getCourseTemplates(request.getPreferences(), themeDisplay.getCompanyId()); + + log.debug("courseTitle: " + courseTitle); + log.debug("closed: " + closed); + log.debug("templates: " + templates); + log.debug("columnId: " + columnId); + log.debug("expandoValue: " + expandoValue); + log.debug("courseId: " + courseId); + log.debug("themeDisplay.getCompanyId(): " + themeDisplay.getCompanyId()); + log.debug("groupId: " + groupId); + log.debug("isAdmin: " + isAdmin); + + LinkedHashMap params = new LinkedHashMap(); + if(templates != null && templates.length > 0){ + params.put(CourseParams.PARAM_TEMPLATES, templates); + } + if(columnId > 0){ + Object[] expandoValues = {columnId, expandoValue}; + params.put(CourseParams.PARAM_CUSTOM_ATTRIBUTE, expandoValues); + } + if(!isAdmin){ + params.put(CourseParams.PARAM_PERMISSIONS_ADMIN, themeDisplay.getUserId()); + } + + List listCourse = CourseLocalServiceUtil.searchCourses(themeDisplay.getCompanyId(), courseTitle, themeDisplay.getLanguageId(), state, courseId, groupId, params, -1, -1, null); + + log.debug("Listado de cursos obtenido"); + + JSONObject userJSON = null; + + for (Course course : listCourse) { + userJSON = JSONFactoryUtil.createJSONObject(); + userJSON.put("courseTitle", course.getTitle(themeDisplay.getLocale())); + userJSON.put("courseDescription", course.getDescription(themeDisplay.getLocale())); + usersJSONArray.put(userJSON); + } + + PrintWriter out = response.getWriter(); + out.println(usersJSONArray.toString()); } - - String[] templates = getCourseTemplates(request.getPreferences(), themeDisplay.getCompanyId()); - - log.debug("courseTitle: " + courseTitle); - log.debug("closed: " + closed); - log.debug("templates: " + templates); - log.debug("columnId: " + columnId); - log.debug("expandoValue: " + expandoValue); - log.debug("courseId: " + courseId); - log.debug("themeDisplay.getCompanyId(): " + themeDisplay.getCompanyId()); - log.debug("groupId: " + groupId); - log.debug("isAdmin: " + isAdmin); - - LinkedHashMap params = new LinkedHashMap(); - if(templates != null && templates.length > 0){ - params.put(CourseParams.PARAM_TEMPLATES, templates); - } - if(columnId > 0){ - Object[] expandoValues = {columnId, expandoValue}; - params.put(CourseParams.PARAM_CUSTOM_ATTRIBUTE, expandoValues); - } - if(!isAdmin){ - params.put(CourseParams.PARAM_PERMISSIONS_ADMIN, themeDisplay.getUserId()); - } - - List listCourse = CourseLocalServiceUtil.searchCourses(themeDisplay.getCompanyId(), courseTitle, themeDisplay.getLanguageId(), state, courseId, groupId, params, -1, -1, null); - - log.debug("Listado de cursos obtenido"); - - JSONObject userJSON = null; - - for (Course course : listCourse) { - userJSON = JSONFactoryUtil.createJSONObject(); - userJSON.put("courseTitle", course.getTitle(themeDisplay.getLocale())); - userJSON.put("courseDescription", course.getDescription(themeDisplay.getLocale())); - usersJSONArray.put(userJSON); - } - - PrintWriter out = response.getWriter(); - out.println(usersJSONArray.toString()); } } diff --git a/docroot/WEB-INF/src/com/liferay/lms/CourseAdmin.java b/docroot/WEB-INF/src/com/liferay/lms/CourseAdmin.java index 33a9dca3c..10a895a20 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/CourseAdmin.java +++ b/docroot/WEB-INF/src/com/liferay/lms/CourseAdmin.java @@ -22,6 +22,7 @@ import javax.portlet.ResourceResponse; import javax.portlet.ResourceURL; +import com.liferay.lms.course.adminaction.AdminActionTypeRegistry; import com.liferay.lms.model.AsynchronousProcessAudit; import com.liferay.lms.model.Course; import com.liferay.lms.model.CourseType; @@ -185,6 +186,8 @@ private void showViewDefault(RenderRequest renderRequest,RenderResponse renderRe searchCourses(renderRequest, renderResponse); + AdminActionTypeRegistry registry = new AdminActionTypeRegistry(); + renderRequest.setAttribute("adminActionTypes", registry.getAdminActionTypes()); include(this.viewJSP, renderRequest, renderResponse); } diff --git a/docroot/WEB-INF/src/com/liferay/lms/CourseStats.java b/docroot/WEB-INF/src/com/liferay/lms/CourseStats.java index 31a411f48..807f34c5a 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/CourseStats.java +++ b/docroot/WEB-INF/src/com/liferay/lms/CourseStats.java @@ -26,18 +26,16 @@ import com.liferay.lms.model.Module; import com.liferay.lms.model.Schedule; import com.liferay.lms.service.CourseLocalServiceUtil; -import com.liferay.lms.service.CourseResultLocalServiceUtil; import com.liferay.lms.service.LearningActivityLocalServiceUtil; import com.liferay.lms.service.LearningActivityResultLocalServiceUtil; import com.liferay.lms.service.ModuleLocalServiceUtil; import com.liferay.lms.service.ModuleResultLocalServiceUtil; import com.liferay.lms.service.ScheduleLocalServiceUtil; -import com.liferay.lms.views.ActivityStatsView; +import com.liferay.lms.views.ActivityStatsView; import com.liferay.lms.views.CourseStatsView; import com.liferay.lms.views.ModuleStatsView; import com.liferay.portal.kernel.dao.search.SearchContainer; import com.liferay.portal.kernel.exception.NestableException; -import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.log.Log; @@ -48,7 +46,6 @@ import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.WebKeys; -import com.liferay.portal.kernel.workflow.WorkflowConstants; import com.liferay.portal.model.Team; import com.liferay.portal.model.User; import com.liferay.portal.service.TeamLocalServiceUtil; @@ -125,7 +122,7 @@ private void showViewDefault(ThemeDisplay themeDisplay, RenderRequest renderRequ } log.debug("CourseStats::showViewDefault::Lista de usuarios obtenida"); - CourseStatsView courseStats = getCourseStats(course, teamId, themeDisplay.getLocale(), userExcludedIds, userIds); + CourseStatsView courseStats = new CourseStatsView(course.getCourseId(), themeDisplay.getLocale(), teamId, userExcludedIds, userIds,false); List courseStatsViews = new ArrayList(); courseStatsViews.add(courseStats); @@ -255,31 +252,6 @@ private long[] getUsersStudentsTeam(Course course, long companyId, long teamId) return userIds; } - - private CourseStatsView getCourseStats (Course course, long teamId, Locale locale, long[] userExcludedIds, long[] userIds) throws PortalException, SystemException{ - log.debug("CourseStats::getCourseStats::Obtenemos las estadísticas del curso"); - //Se construye la vista de las estadisticas del curso - CourseStatsView courseStats = new CourseStatsView(course.getCourseId(), course.getTitle(locale)); - - if(teamId > 0){ - courseStats.setRegistered(userIds.length); - courseStats.setStarted(CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsStarted(course.getCourseId(), userIds)); - courseStats.setFinished(CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsFinished(course.getCourseId(), userIds)); - courseStats.setPassed(CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsPassed(course.getCourseId(), userIds)); - courseStats.setFailed(CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsFailed(course.getCourseId(), userIds)); - }else{ - courseStats.setRegistered(CourseLocalServiceUtil.countStudentsStatus(course.getCourseId(), course.getCompanyId(), null, null, null, null, WorkflowConstants.STATUS_ANY, false)); - courseStats.setStarted(CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsStarted(course.getCourseId(), userExcludedIds)); - courseStats.setFinished(CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsFinished(course.getCourseId(), userExcludedIds)); - courseStats.setPassed(CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsPassed(course.getCourseId(), userExcludedIds)); - courseStats.setFailed(CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsFailed(course.getCourseId(), userExcludedIds)); - } - log.debug("CourseStats::getCourseStats::Estadísticas del curso obtenidas"); - - return courseStats; - } - - private ModuleStatsView getModuleStats(Module module, long teamId, Locale locale, TimeZone timeZone, Schedule sch, long[] userExcludedIds, long[] userIds) throws SystemException{ ModuleStatsView moduleStats = new ModuleStatsView(module.getModuleId(), module.getTitle(locale), timeZone); @@ -356,6 +328,10 @@ private ActivityStatsView getActivityStats(LearningActivity activity, Locale loc boolean hasPrecedence = false; if(activity.getPrecedence() > 0){ hasPrecedence = true; + LearningActivity precedence = LearningActivityLocalServiceUtil.fetchLearningActivity(activity.getPrecedence()); + if(precedence != null){ + activityStats.setDependency(precedence.getTitle(locale)); + } } activityStats.setPrecedence(LanguageUtil.get(locale,"dependencies."+String.valueOf(hasPrecedence))); activityStats.setType(LanguageUtil.get(locale,classTypes.get((long)activity.getTypeId()))); @@ -410,7 +386,7 @@ private void exportCourse(ResourceResponse resourceResponse, long courseId, userExcludedIds = CourseLocalServiceUtil.getTeachersAndEditorsIdsFromCourse(course); } - CourseStatsView courseView = getCourseStats(course, teamId, themeDisplay.getLocale(), userExcludedIds, userIds); + CourseStatsView courseView = new CourseStatsView(course.getCourseId(), themeDisplay.getLocale(), teamId, userExcludedIds, userIds,false); List modules = ModuleLocalServiceUtil.findAllInGroup(course.getGroupCreatedId()); CSVWriter writer = initCsv(resourceResponse); diff --git a/docroot/WEB-INF/src/com/liferay/lms/GeneralStats.java b/docroot/WEB-INF/src/com/liferay/lms/GeneralStats.java index dfdda2fc5..9b28594ce 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/GeneralStats.java +++ b/docroot/WEB-INF/src/com/liferay/lms/GeneralStats.java @@ -2,30 +2,52 @@ import java.io.IOException; import java.io.OutputStreamWriter; -import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.List; import javax.portlet.PortletException; +import javax.portlet.PortletRequestDispatcher; +import javax.portlet.PortletSession; +import javax.portlet.PortletURL; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; +import javax.portlet.ResourceURL; import au.com.bytecode.opencsv.CSVWriter; import com.liferay.lms.model.Course; import com.liferay.lms.service.CourseLocalServiceUtil; -import com.liferay.lms.service.CourseResultLocalServiceUtil; -import com.liferay.lms.service.LearningActivityLocalServiceUtil; -import com.liferay.lms.service.ModuleLocalServiceUtil; +import com.liferay.lms.util.CourseParams; +import com.liferay.lms.views.CourseStatsView; +import com.liferay.portal.kernel.dao.search.SearchContainer; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.servlet.HttpHeaders; +import com.liferay.portal.kernel.util.ArrayUtil; import com.liferay.portal.kernel.util.LocaleUtil; +import com.liferay.portal.kernel.util.OrderByComparator; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; +import com.liferay.portal.kernel.workflow.WorkflowConstants; +import com.liferay.portal.model.RoleConstants; +import com.liferay.portal.security.permission.ActionKeys; +import com.liferay.portal.service.RoleLocalServiceUtil; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.ServiceContextFactory; import com.liferay.portal.theme.ThemeDisplay; +import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; import com.liferay.util.bridges.mvc.MVCPortlet; +import com.tls.lms.util.CourseOrderByCreationDate; +import com.tls.lms.util.CourseOrderByTitle; /** * Portlet implementation class GeneralStats @@ -33,20 +55,349 @@ public class GeneralStats extends MVCPortlet { private static Log log = LogFactoryUtil.getLog(GeneralStats.class); + + private String viewJSP = null; + + public void init() throws PortletException { + viewJSP = getInitParameter("view-template"); + } + + + + public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { + ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); + renderRequest.getPreferences().setValue("showSearchTags", renderRequest.getPreferences().getValue("showSearchTagsGeneralStats", "false")); + renderRequest.getPreferences().setValue("categories", renderRequest.getPreferences().getValue("showSearchCategoriesGeneralStats", "true")); + long courseId = ParamUtil.getLong(renderRequest, "courseId", 0); + String search = ParamUtil.getString(renderRequest, "search",""); + String freetext = ParamUtil.getString(renderRequest, "freetext",""); + String tags = ParamUtil.getString(renderRequest, "tags",""); + int state = ParamUtil.getInteger(renderRequest, "state",WorkflowConstants.STATUS_APPROVED); + long selectedGroupId = ParamUtil.get(renderRequest,"selectedGroupId",-1); + long catId=ParamUtil.getLong(renderRequest, "categoryId",0); + + + //*****************************************Cogemos los tags************************************// + String[] tagsSel = null; + long[] tagsSelIds = null; + try { + ServiceContext sc = ServiceContextFactory.getInstance(renderRequest); + tagsSel = sc.getAssetTagNames(); + + if(tagsSel != null){ + long[] groups = new long[]{themeDisplay.getScopeGroupId()}; + tagsSelIds = AssetTagLocalServiceUtil.getTagIds(groups, tagsSel); + } + } catch (PortalException e1) { + e1.printStackTrace(); + } catch (SystemException e1) { + e1.printStackTrace(); + } + + + //*****************************************Cogemos las categorias************************************// + Enumeration pnames =renderRequest.getParameterNames(); + ArrayList tparams = new ArrayList(); + ArrayList assetCategoryIds = new ArrayList(); + + + + while(pnames.hasMoreElements()){ + String name = pnames.nextElement(); + if(name.length()>16&&name.substring(0,16).equals("assetCategoryIds")){ + tparams.add(name); + String value = renderRequest.getParameter(name); + String[] values = value.split(","); + for(String valuet : values){ + try{ + assetCategoryIds.add(Long.parseLong(valuet)); + }catch(Exception e){ + } + } + + } + } + + //***************************Si estás buscando te guarda los parámetros en la sesión, si no estás buscando te los coge de la sesión****************************// + + PortletSession portletSession = renderRequest.getPortletSession(); + String prefix = ""; + if(courseId > 0){ + prefix = String.valueOf(courseId); + } + if(ParamUtil.getString(renderRequest, "search").equals("search")){ + portletSession.setAttribute(prefix+"freetext", freetext); + portletSession.setAttribute(prefix+"state", state); + portletSession.setAttribute(prefix+"assetCategoryIds", assetCategoryIds); + portletSession.setAttribute(prefix+"assetTagIds", tagsSelIds); + + + + }else{ + try{ + String freetextTemp = (String)portletSession.getAttribute(prefix+"freetext"); + if(freetextTemp!=null){ + freetext = freetextTemp; + } + }catch(Exception e){ + log.debug(e); + } + try{ + ArrayList assetCategoryIdsTemp = (ArrayList)portletSession.getAttribute(prefix+"assetCategoryIds"); + if(assetCategoryIdsTemp!=null){ + assetCategoryIds = assetCategoryIdsTemp; + } + }catch(Exception e){ + log.debug(e); + } + try{ + Integer stateTemp = (Integer)portletSession.getAttribute(prefix+"state"); + if(stateTemp!=null){ + state = stateTemp; + } + }catch(Exception e){} + + } + + long[] catIds=ParamUtil.getLongValues(renderRequest, "categoryIds"); + + StringBuffer sb = new StringBuffer(); + for(long cateId : assetCategoryIds){ + sb.append(cateId); + sb.append(","); + } + String catIdsText = sb.toString(); + + if((catIds==null||catIds.length<=0)&&(assetCategoryIds!=null&&assetCategoryIds.size()>0)){ + catIds = new long[assetCategoryIds.size()]; + for(int i=0;i16&&name.substring(0,16).equals("assetCategoryIds")){ + portletURL.setParameter(name,renderRequest.getParameter(name)); + } + } + for(String param : tparams){ + portletURL.setParameter(param,renderRequest.getParameter(param)); + } + portletURL.setParameter("search","search"); + + + if(courseId > 0){ + portletURL.setParameter("courseId", String.valueOf(courseId)); + portletURL.setParameter("view", "editions"); + } + + long[] categoryIds = ArrayUtil.toArray(assetCategoryIds.toArray(new Long[assetCategoryIds.size()])); + + int closed = -1; + if(state!=WorkflowConstants.STATUS_ANY){ + if(state==WorkflowConstants.STATUS_APPROVED){ + closed = 0; + } + else if(state==WorkflowConstants.STATUS_INACTIVE){ + closed = 1; + } + } + + boolean isAdmin = false; + try { + isAdmin = RoleLocalServiceUtil.hasUserRole(themeDisplay.getUserId(), RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(), RoleConstants.ADMINISTRATOR).getRoleId()) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.UPDATE) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.DELETE) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, ActionKeys.PERMISSIONS) + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "PUBLISH") + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "COURSEEDITOR") + || themeDisplay.getPermissionChecker().hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(), 0, "ASSIGN_MEMBERS"); + } catch (SystemException e) { + e.printStackTrace(); + } catch (PortalException e) { + e.printStackTrace(); + } + + long groupId = themeDisplay.getScopeGroupId(); + log.debug("SELECTED GROUP ID " + selectedGroupId); + if(selectedGroupId>-1){ + groupId = selectedGroupId; + } + + String emptyResultsMessage = "there-are-no-courses"; + if(courseId > 0){ + emptyResultsMessage = "there-are-no-editions"; + } + + SearchContainer searchContainer = new SearchContainer(renderRequest, null, null, SearchContainer.DEFAULT_CUR_PARAM, + SearchContainer.DEFAULT_DELTA, portletURL, + null, emptyResultsMessage); + + log.debug("freetext: " + freetext); + log.debug("closed: " + closed); + log.debug("categoryIds: " + categoryIds); + log.debug("tagsSelIds: " + tagsSelIds); + log.debug("courseId: " + courseId); + log.debug("themeDisplay.getCompanyId(): " + themeDisplay.getCompanyId()); + log.debug("groupId: " + groupId); + log.debug("isAdmin: " + isAdmin); + + LinkedHashMap params = new LinkedHashMap(); + if(categoryIds != null && categoryIds.length > 0){ + params.put(CourseParams.PARAM_AND_CATEGORIES, categoryIds); + } + if(tagsSelIds != null && tagsSelIds.length > 0){ + params.put(CourseParams.PARAM_TAGS, tagsSelIds); + } + if(!isAdmin){ + params.put(CourseParams.PARAM_PERMISSIONS_ADMIN, themeDisplay.getUserId()); + } + + String orderByCol = ParamUtil.getString(renderRequest, "orderByCol"); + String orderByType = ParamUtil.getString(renderRequest, "orderByType"); + + if (Validator.isNull(orderByCol) || + Validator.isNull(orderByType)){ + orderByCol = "title"; + orderByType = "asc"; + } + + OrderByComparator obc = null; + if(Validator.isNotNull(orderByCol) && orderByCol.equals("title")){ + obc = new CourseOrderByTitle(themeDisplay, orderByType.equals("asc")); + }else if(Validator.isNotNull(orderByCol) && orderByCol.equals("createDate")){ + obc = new CourseOrderByCreationDate(orderByType.equals("asc")); + } + + searchContainer.setOrderByCol(orderByCol); + searchContainer.setOrderByType(orderByType); + searchContainer.setOrderByComparator(obc); + List courses = CourseLocalServiceUtil.searchCourses(themeDisplay.getCompanyId(), freetext, themeDisplay.getLanguageId(), state, courseId, -1, params, + searchContainer.getStart(), searchContainer.getEnd(), searchContainer.getOrderByComparator()); + List courseStats = new ArrayList(); + CourseStatsView courseStatView=null; + long[] userExcludedIds; + for(Course course:courses){ + userExcludedIds = CourseLocalServiceUtil.getTeachersAndEditorsIdsFromCourse(course); + courseStatView = new CourseStatsView(course.getCourseId(),themeDisplay.getLocale(), 0, userExcludedIds, null,true); + courseStats.add(courseStatView); + } + searchContainer.setResults(courseStats); + searchContainer.setTotal(CourseLocalServiceUtil.countCourses(themeDisplay.getCompanyId(), freetext, themeDisplay.getLanguageId(), state, courseId, -1, params)); + + renderRequest.setAttribute("searchContainer", searchContainer); + renderRequest.setAttribute("catIds", catIds); + renderRequest.setAttribute("noAssetCategoryIds", assetCategoryIds == null || assetCategoryIds.size() == 0); + renderRequest.setAttribute("catId", catId); + renderRequest.setAttribute("search", search); + renderRequest.setAttribute("freetext", freetext); + renderRequest.setAttribute("tags", tags); + renderRequest.setAttribute("state", state); + renderRequest.setAttribute("catIdsText", catIdsText); + + renderRequest.setAttribute("STATUS_APPROVED", WorkflowConstants.STATUS_APPROVED); + renderRequest.setAttribute("STATUS_INACTIVE", WorkflowConstants.STATUS_INACTIVE); + renderRequest.setAttribute("STATUS_ANY", WorkflowConstants.STATUS_ANY); + ResourceURL exportReportURL = renderResponse.createResourceURL(); + exportReportURL.setResourceID("exportReport"); + renderRequest.setAttribute("exportReportURL", exportReportURL.toString()); + include(this.viewJSP, renderRequest, renderResponse); + } + + protected void include(String path, RenderRequest renderRequest, + RenderResponse renderResponse) throws IOException, PortletException { + + PortletRequestDispatcher portletRequestDispatcher = getPortletContext() + .getRequestDispatcher(path); + + if (portletRequestDispatcher == null) { + // do nothing + // _log.error(path + " is not a valid include"); + } else { + portletRequestDispatcher.include(renderRequest, renderResponse); + } + } + @Override public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException { - String action = ParamUtil.getString(resourceRequest, "action"); - long[] courseIds=ParamUtil.getLongValues(resourceRequest, "courseIds"); - ThemeDisplay themeDisplay =(ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY); + String action = resourceRequest.getResourceID(); - if(log.isDebugEnabled()){ - log.debug("::generalstats:: action :: " + action); - log.debug("::generalstats:: courseIds.length :: " + courseIds.length); - } - - if(action.equals("export")){ + if(action.equals("exportReport")){ + + ThemeDisplay themeDisplay =(ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY); + String freetext = ParamUtil.getString(resourceRequest, "freetext",""); + int state = ParamUtil.getInteger(resourceRequest, "state",WorkflowConstants.STATUS_APPROVED); + + + //*****************************************Cogemos los tags************************************// + String[] tagsSel = null; + long[] tagsSelIds = null; + try { + ServiceContext sc = ServiceContextFactory.getInstance(resourceRequest); + tagsSel = sc.getAssetTagNames(); + + if(tagsSel != null){ + long[] groups = new long[]{themeDisplay.getScopeGroupId()}; + tagsSelIds = AssetTagLocalServiceUtil.getTagIds(groups, tagsSel); + } + } catch (PortalException e1) { + e1.printStackTrace(); + } catch (SystemException e1) { + e1.printStackTrace(); + } + + + //*****************************************Cogemos las categorias************************************// + Enumeration pnames =resourceRequest.getParameterNames(); + ArrayList tparams = new ArrayList(); + ArrayList assetCategoryIds = new ArrayList(); + + + + while(pnames.hasMoreElements()){ + String name = pnames.nextElement(); + if(name.length()>16&&name.substring(0,16).equals("assetCategoryIds")){ + tparams.add(name); + String value = resourceRequest.getParameter(name); + String[] values = value.split(","); + for(String valuet : values){ + try{ + assetCategoryIds.add(Long.parseLong(valuet)); + }catch(Exception e){ + } + } + + } + } + long[] categoryIds = ArrayUtil.toArray(assetCategoryIds.toArray(new Long[assetCategoryIds.size()])); + + LinkedHashMap params = new LinkedHashMap(); + if(categoryIds != null && categoryIds.length > 0){ + params.put(CourseParams.PARAM_AND_CATEGORIES, categoryIds); + } + if(tagsSelIds != null && tagsSelIds.length > 0){ + params.put(CourseParams.PARAM_TAGS, tagsSelIds); + } + + List courses = CourseLocalServiceUtil.searchCourses(themeDisplay.getCompanyId(), freetext, themeDisplay.getLanguageId(), state, 0, -1, params, + WorkflowConstants.STATUS_ANY, WorkflowConstants.STATUS_ANY, null); + if(log.isDebugEnabled()){ + log.debug("::generalstats:: action :: " + action); + log.debug("::generalstats:: courseIds.length :: " + courses.size()); + } + try { String charset = LanguageUtil.getCharset(themeDisplay.getLocale()); @@ -62,43 +413,35 @@ public void serveResource(ResourceRequest resourceRequest, resourceResponse.getPortletOutputStream().write(b); } CSVWriter writer = new CSVWriter(new OutputStreamWriter(resourceResponse.getPortletOutputStream(),charset),';'); - String[] linea=new String[8]; + String[] linea=new String[10]; linea[0]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.name"); linea[1]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.registered"); - linea[2]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.starts.course"); - linea[3]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.ends.course"); - linea[4]=LanguageUtil.get(themeDisplay.getLocale(),"closed"); - linea[5]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulestats.marks.average"); - linea[6]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulecounter"); - linea[7]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.activitiescounter"); + linea[2]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.start.student"); + linea[3]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.end.student"); + linea[4]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.passed"); + linea[5]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.failed"); + linea[6]=LanguageUtil.get(themeDisplay.getLocale(),"closed"); + linea[7]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulestats.marks.average"); + linea[8]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.modulecounter"); + linea[9]=LanguageUtil.get(themeDisplay.getLocale(),"coursestats.activitiescounter"); + writer.writeNext(linea); long[] userExcludedIds = null; - for(long courseId:courseIds) - { - Course course=CourseLocalServiceUtil.getCourse(courseId); + CourseStatsView courseStatView = null; + for(Course course:courses){ userExcludedIds = CourseLocalServiceUtil.getTeachersAndEditorsIdsFromCourse(course); - linea=new String[8]; - linea[0]=course.getTitle(themeDisplay.getLocale()); - - long registered=CourseLocalServiceUtil.countStudents(courseId, themeDisplay.getCompanyId(), null, null, null, null, false); - long iniciados = (registered > 0) ? CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsStarted(courseId, userExcludedIds) : 0; - long finalizados = (registered > 0) ? CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsFinished(courseId, userExcludedIds) : 0; - double avgResult=0; - if(finalizados>0){ - avgResult=CourseResultLocalServiceUtil.avgResultByCourseIdUserExcludedIds(course.getCourseId(), true, userExcludedIds); - } - long activitiesCount=LearningActivityLocalServiceUtil.countLearningActivitiesOfGroup(course.getGroupCreatedId()); - long modulesCount=ModuleLocalServiceUtil.countByGroupId(course.getGroupCreatedId()); - String closed=course.getClosed()?LanguageUtil.get(themeDisplay.getLocale(),"yes"):LanguageUtil.get(themeDisplay.getLocale(),"no"); - - linea[1]=Long.toString(registered); - linea[2]=Long.toString(iniciados); - linea[3]=Long.toString(finalizados); - DecimalFormat df = new DecimalFormat("#.#"); - linea[4]=closed; - linea[5]=df.format(avgResult); - linea[6]=Long.toString(modulesCount); - linea[7]=Long.toString(activitiesCount); + courseStatView = new CourseStatsView(course.getCourseId(), themeDisplay.getLocale(), 0, userExcludedIds, null, true); + linea=new String[10]; + linea[0]=courseStatView.getCourseTitle(); + linea[1]=Long.toString(courseStatView.getRegistered()); + linea[2]=Long.toString(courseStatView.getStarted()); + linea[3]=Long.toString(courseStatView.getFinished()); + linea[4]=Long.toString(courseStatView.getPassed()); + linea[5]=Long.toString(courseStatView.getFailed()); + linea[6]=courseStatView.getClosed(); + linea[7]=courseStatView.getAvgResult(); + linea[8]= Long.toString(courseStatView.getModules()); + linea[9]=Long.toString(courseStatView.getActivities()); writer.writeNext(linea); //resourceResponse.getPortletOutputStream().write(b); } diff --git a/docroot/WEB-INF/src/com/liferay/lms/LmsActivitiesList.java b/docroot/WEB-INF/src/com/liferay/lms/LmsActivitiesList.java index 3a086970d..c23fef953 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/LmsActivitiesList.java +++ b/docroot/WEB-INF/src/com/liferay/lms/LmsActivitiesList.java @@ -47,6 +47,7 @@ import com.liferay.lms.service.AsynchronousProcessAuditLocalServiceUtil; import com.liferay.lms.service.ClpSerializer; import com.liferay.lms.service.LearningActivityLocalServiceUtil; +import com.liferay.lms.service.LearningActivityResultLocalServiceUtil; import com.liferay.lms.service.LearningActivityServiceUtil; import com.liferay.lms.service.LearningActivityTryLocalServiceUtil; import com.liferay.lms.service.ModuleLocalServiceUtil; @@ -67,6 +68,7 @@ import com.liferay.portal.kernel.portlet.LiferayWindowState; import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.servlet.SessionMessages; +import com.liferay.portal.kernel.upload.UploadPortletRequest; import com.liferay.portal.kernel.upload.UploadRequest; import com.liferay.portal.kernel.util.ArrayUtil; import com.liferay.portal.kernel.util.HttpUtil; @@ -191,7 +193,7 @@ public void deleteMyTries(ActionRequest actionRequest, ActionResponse actionResp } public void saveActivity(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { - UploadRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest); + UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest); if(log.isDebugEnabled()){ Enumeration parNames2= uploadRequest.getParameterNames(); @@ -201,30 +203,8 @@ public void saveActivity(ActionRequest actionRequest, ActionResponse actionRespo } } - ServiceContext serviceContext = ServiceContextFactory.getInstance(LearningActivity.class.getName(), actionRequest); - - List assetCategoryIdsList = new ArrayList(); - boolean updateAssetCategoryIds = false; - - for (String name:Collections.list((Enumeration)uploadRequest.getParameterNames())){ - if (name.startsWith("assetCategoryIds")) { - updateAssetCategoryIds = true; - for (long assetCategoryId : StringUtil.split( - ParamUtil.getString(uploadRequest, name), 0L)) { - assetCategoryIdsList.add(assetCategoryId); - } - } - } - - if (updateAssetCategoryIds) { - serviceContext.setAssetCategoryIds(ArrayUtil.toArray( - assetCategoryIdsList.toArray( - new Long[assetCategoryIdsList.size()]))); - } + ServiceContext serviceContext = ServiceContextFactory.getInstance(LearningActivity.class.getName(), uploadRequest); - String assetTagNames = uploadRequest.getParameter("assetTagNames"); - - long maxSize = ParamUtil.getLong(uploadRequest, "maxSize", -1); if(maxSize<0){ @@ -232,10 +212,6 @@ public void saveActivity(ActionRequest actionRequest, ActionResponse actionRespo return; } - if (assetTagNames != null) { - serviceContext.setAssetTagNames(StringUtil.split(assetTagNames)); - } - ThemeDisplay themeDisplay = (ThemeDisplay) uploadRequest.getAttribute(WebKeys.THEME_DISPLAY); PermissionChecker permissionChecker=themeDisplay.getPermissionChecker(); String redirect = ParamUtil.getString(uploadRequest, "redirect"); @@ -410,6 +386,11 @@ public void saveActivity(ActionRequest actionRequest, ActionResponse actionRespo LearningActivity.class.getName(), actId,tmp.getUserId(), ActionKeys.UPDATE)) { + if(moduleId != tmp.getModuleId() && LearningActivityResultLocalServiceUtil.countByActId(tmp.getActId())>0) + { + SessionErrors.add(actionRequest, "activity.move-activity-with-result"); + return; + } String extraContentTmp = tmp.getExtracontent(); diff --git a/docroot/WEB-INF/src/com/liferay/lms/ModuleNavigation.java b/docroot/WEB-INF/src/com/liferay/lms/ModuleNavigation.java index 5200de05d..b139663e3 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/ModuleNavigation.java +++ b/docroot/WEB-INF/src/com/liferay/lms/ModuleNavigation.java @@ -1,6 +1,7 @@ package com.liferay.lms; import java.io.IOException; +import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; @@ -13,9 +14,19 @@ import javax.xml.namespace.QName; import com.liferay.lms.events.ThemeIdEvent; +import com.liferay.lms.model.LearningActivity; +import com.liferay.lms.service.LearningActivityLocalServiceUtil; +import com.liferay.portal.kernel.dao.orm.DynamicQuery; +import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil; +import com.liferay.portal.kernel.dao.orm.OrderFactoryUtil; +import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.WebKeys; +import com.liferay.portal.security.permission.ActionKeys; +import com.liferay.portal.theme.ThemeDisplay; import com.liferay.util.bridges.mvc.MVCPortlet; /** @@ -23,10 +34,13 @@ */ public class ModuleNavigation extends MVCPortlet { + private static Log log = LogFactoryUtil.getLog(ModuleNavigation.class); + public void goToModule(ActionRequest actionRequest, ActionResponse actionResponse)throws Exception { ThemeIdEvent themeIdEvent = new ThemeIdEvent(); themeIdEvent.setModuleId(ParamUtil.getLong(actionRequest, "moduleId",0)); - themeIdEvent.setThemeId(ParamUtil.getLong(actionRequest, "themeId",1)); + themeIdEvent.setThemeId(ParamUtil.getLong(actionRequest, "themeId",1)); + themeIdEvent.setActId(ParamUtil.getLong(actionRequest, "actId",0)); actionResponse.setEvent(new QName("http://www.wemooc.com/" , "themeId"), themeIdEvent); } @@ -46,17 +60,85 @@ else if((moduleId==0)&&(themeIdEvent.getModuleId()==ThemeIdEvent.EVALUATION_THEM } @Override - public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { + public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException{ + + ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); + boolean actionEditingDetails = ParamUtil.getBoolean(renderRequest, "actionEditingDetails", false); + boolean actionEditingActivity = ParamUtil.getBoolean(renderRequest, "actionEditingActivity", false); + boolean actionEditingModule = ParamUtil.getBoolean(renderRequest, "actionEditingModule", false); + boolean actionCalifications = ParamUtil.getBoolean(renderRequest, "actionCalifications", false); + + log.debug("actionEditingDetails:"+actionEditingDetails); + log.debug("actionEditingActivity:"+actionEditingActivity); + log.debug("actionEditingModule:"+actionEditingModule); + log.debug("actionCalifications:"+actionCalifications); - if(ParamUtil.getLong(renderRequest, "moduleId", 0) == 0){ + //Cuando no tenemos actividad ni modulo, ocultamos el portlet. + if( (ParamUtil.getLong(renderRequest, "actId", 0) == 0 && ParamUtil.getLong(renderRequest, "moduleId", 0) == 0) + || actionEditingDetails || actionEditingActivity || actionEditingModule || actionCalifications){ renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); } if(ParamUtil.getBoolean(renderRequest, WebKeys.PORTLET_CONFIGURATOR_VISIBILITY,true)) { - super.doView(renderRequest, renderResponse); - } - else { - renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); + + + long moduleId = ParamUtil.getLong(renderRequest,"moduleId",0); + long currentActId = ParamUtil.getLong(renderRequest,"actId",0); + log.debug("******doView - currentActId: " + currentActId); + + //ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY); + + //obtener la primera y la ultima actividad del modulo, si es la primera y hay un modulo anterior, mostrar el enlace del modulo anterior, + //si es la ultima actividad y hay siguiente modulo, mostrar el enlace del siguiente modulo. + long firstActId = 0L; + long lastActId = 0L; + if (moduleId > 0){ + try{ + DynamicQuery q = DynamicQueryFactoryUtil.forClass(LearningActivity.class); + q.add(RestrictionsFactoryUtil.eq("moduleId", moduleId)); + q.addOrder(OrderFactoryUtil.asc("priority")); + List lActivitiesByModuleId = LearningActivityLocalServiceUtil.dynamicQuery(q); + if (lActivitiesByModuleId!= null && lActivitiesByModuleId.size()>0){ + + for (int i=0;i=0;z--){ + log.debug("2-for: " + z+ " - themeDisplay.getUserId(): " + themeDisplay.getUserId()); + if (lastActId == 0L && themeDisplay.getPermissionChecker().hasPermission(lActivitiesByModuleId.get(z).getGroupId(),LearningActivity.class.getName(),lActivitiesByModuleId.get(z).getActId(), ActionKeys.VIEW)){ + log.debug("if canBeView"); + lastActId = lActivitiesByModuleId.get(z).getActId(); + break; + } + } + + } + log.debug("****** doView - first actId: " + firstActId + " -- lastActId: " + lastActId); + }catch (Exception e){ + e.printStackTrace(); + } + } + + renderRequest.setAttribute("firstActId", Long.toString(firstActId)); + renderRequest.setAttribute("lastActId", Long.toString(lastActId)); + + + if(ParamUtil.getLong(renderRequest, "moduleId", 0) == 0){ + renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); + } + + if(ParamUtil.getBoolean(renderRequest, WebKeys.PORTLET_CONFIGURATOR_VISIBILITY,true)) { + super.doView(renderRequest, renderResponse); + } + else { + renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); + } } } } diff --git a/docroot/WEB-INF/src/com/liferay/lms/OnlineActivity.java b/docroot/WEB-INF/src/com/liferay/lms/OnlineActivity.java index c65b62f69..16a2e7b73 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/OnlineActivity.java +++ b/docroot/WEB-INF/src/com/liferay/lms/OnlineActivity.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Iterator; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; @@ -13,8 +14,6 @@ import javax.portlet.RenderResponse; import com.liferay.lms.asset.LearningActivityAssetRendererFactory; -import com.liferay.lms.auditing.AuditConstants; -import com.liferay.lms.auditing.AuditingLogFactory; import com.liferay.lms.learningactivity.calificationtype.CalificationType; import com.liferay.lms.learningactivity.calificationtype.CalificationTypeRegistry; import com.liferay.lms.model.Course; @@ -45,25 +44,23 @@ import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.kernel.xml.Document; +import com.liferay.portal.kernel.xml.DocumentException; import com.liferay.portal.kernel.xml.Element; +import com.liferay.portal.kernel.xml.Node; import com.liferay.portal.kernel.xml.SAXReaderUtil; import com.liferay.portal.model.ResourceConstants; import com.liferay.portal.model.User; import com.liferay.portal.service.ResourcePermissionLocalServiceUtil; -import com.liferay.portal.service.RoleLocalServiceUtil; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.ServiceContextFactory; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; -import com.liferay.portlet.asset.model.AssetEntry; import com.liferay.portlet.asset.model.AssetRenderer; -import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; import com.liferay.portlet.documentlibrary.model.DLFileEntry; import com.liferay.portlet.documentlibrary.model.DLFolder; import com.liferay.portlet.documentlibrary.model.DLFolderConstants; import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil; -import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil; import com.liferay.util.bridges.mvc.MVCPortlet; @@ -100,10 +97,6 @@ public class OnlineActivity extends MVCPortlet { "WHERE User_.userId = lms_learningactivityresult.userId AND lms_learningactivityresult.actId = ? AND lms_learningactivityresult.endDate IS NOT NULL ))"; - //public static final String ACTIVITY_RESULT_NO_CALIFICATION_SQL = "WHERE (EXISTS (SELECT 1 FROM lms_learningactivityresult " + - // "WHERE User_.userId = lms_learningactivityresult.userId AND lms_learningactivityresult.endDate =lms_learningactivityresult.startDate AND lms_learningactivityresult.actId = ? ))"; - - public static final String TEXT_XML= "text"; public static final String RICH_TEXT_XML = "richText"; public static final String FILE_XML = "file"; @@ -203,10 +196,6 @@ public void setGrades(ActionRequest request, ActionResponse response){ } - - - - private void updateLearningActivityTryAndResult( LearningActivityTry learningActivityTry) throws PortalException, SystemException { @@ -238,7 +227,7 @@ protected void doDispatch(RenderRequest renderRequest, public void setActivity(ActionRequest actionRequest, - ActionResponse actionResponse) throws IOException, NestableException { + ActionResponse actionResponse) throws IOException, NestableException, DocumentException { long actId = ParamUtil.getLong(actionRequest, "actId"); UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest); String text = ParamUtil.getString(uploadRequest, "text"); @@ -246,89 +235,118 @@ public void setActivity(ActionRequest actionRequest, User user = UserLocalServiceUtil.getUser(themeDisplay.getUserId()); boolean isSetTextoEnr = StringPool.TRUE.equals(LearningActivityLocalServiceUtil.getExtraContentValue(actId,"textoenr")); boolean isSetFichero = StringPool.TRUE.equals(LearningActivityLocalServiceUtil.getExtraContentValue(actId,"fichero")); + + if(log.isDebugEnabled()){ + log.debug("::setActivity:: actId :: " + actId); + log.debug("::setActivity:: text :: " + text); + log.debug("::setActivity:: isSetTextoEnr :: " + isSetTextoEnr); + log.debug("::setActivity:: isSetFichero :: " + isSetFichero); + } LearningActivity learningActivity = LearningActivityLocalServiceUtil.getLearningActivity(actId); LearningActivityTryLocalServiceUtil.getTriesCountByActivityAndUser(actId, user.getUserId()); - log.debug("TEXTO "+text); - if((learningActivity.getTries()!=0)&&(learningActivity.getTries()<=LearningActivityTryLocalServiceUtil.getTriesCountByActivityAndUser(actId, user.getUserId()))) { - //TODO + LearningActivityResult result = LearningActivityResultLocalServiceUtil.getByActIdAndUserId(actId, user.getUserId()); + //Si el result no tiene end date es que aún no está corregida + if(Validator.isNotNull(result) && Validator.isNotNull(result.getEndDate()) && (learningActivity.getTries()!=0)&&(learningActivity.getTries()<=LearningActivityTryLocalServiceUtil.getTriesCountByActivityAndUser(actId, user.getUserId()))) { SessionErrors.add(actionRequest, "onlineActivity.max-tries"); - } - else { - - //ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); - + if(log.isDebugEnabled()) + log.debug("::setActivity:: MAX TRIES :: "); + } else { Element resultadosXML=SAXReaderUtil.createElement("results"); Document resultadosXMLDoc=SAXReaderUtil.createDocument(resultadosXML); + String fileName = null; if(isSetFichero) { - String fileName = uploadRequest.getFileName("fileName"); + fileName = uploadRequest.getFileName("fileName"); + if(log.isDebugEnabled()) + log.debug("::setActivity:: fileName :: " + fileName); File file = uploadRequest.getFile("fileName"); String mimeType = uploadRequest.getContentType("fileName"); - if (Validator.isNull(fileName)) { + //Si no se ha subido archivo y no hay un intento previo con archivo subido + if ((Validator.isNull(fileName) || fileName.equals(StringPool.BLANK)) && Validator.isNull(result)) { + if(log.isDebugEnabled()) + log.debug("::setActivity:: MANDATORYFILE :: "); SessionErrors.add(actionRequest, "onlineActivity.mandatory.file"); actionRequest.setAttribute("actId", actId); actionResponse.setRenderParameter("text", text); return; } - if( file.getName().endsWith(".bat") - || file.getName().endsWith(".com") - || file.getName().endsWith(".exe") - || file.getName().endsWith(".msi") ){ - - SessionErrors.add(actionRequest, "onlineActivity-error-file-type"); - actionResponse.setRenderParameter("text", text); - actionRequest.setAttribute("actId", actId); - return; - } - - long repositoryId = DLFolderConstants.getDataRepositoryId(themeDisplay.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID); - long folderId = createDLFolders(user.getUserId(), repositoryId, actionRequest); - FileEntry document; - try{ - //Subimos el Archivo en la Document Library - ServiceContext serviceContext= ServiceContextFactory.getInstance( DLFileEntry.class.getName(), actionRequest); - //Damos permisos al archivo para usuarios de comunidad. - //serviceContext.setAddGroupPermissions(true); - document = DLAppLocalServiceUtil.addFileEntry( - themeDisplay.getUserId(), repositoryId , folderId , fileName, mimeType, fileName, StringPool.BLANK, StringPool.BLANK, file , serviceContext ) ; - }catch(Exception e){ - actionResponse.setRenderParameter("text", text); - actionRequest.setAttribute("actId", actId); - throw(e); - } - LmsPrefs prefs = LmsPrefsLocalServiceUtil.fetchLmsPrefs(themeDisplay.getCompanyId()); - try{ - ResourcePermissionLocalServiceUtil.setResourcePermissions(themeDisplay.getCompanyId(), DLFileEntry.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(document.getFileEntryId()) , prefs.getTeacherRole(), new String[]{"VIEW"}); - ResourcePermissionLocalServiceUtil.setResourcePermissions(themeDisplay.getCompanyId(), DLFileEntry.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(document.getFileEntryId()) , prefs.getEditorRole(), new String[]{"VIEW"}); - }catch(Exception e){ - e.printStackTrace(); - } - //serviceContext.setGroupPermissions(groupPermissions); - Element fileXML=SAXReaderUtil.createElement(FILE_XML); - fileXML.addAttribute("id", Long.toString(document.getFileEntryId())); - resultadosXML.add(fileXML); + if(Validator.isNotNull(fileName)){ + if( file.getName().endsWith(".bat") + || file.getName().endsWith(".com") + || file.getName().endsWith(".exe") + || file.getName().endsWith(".msi") ){ + + if(log.isDebugEnabled()) + log.debug("::setActivity:: ERROR TYPE FILE :: "); + SessionErrors.add(actionRequest, "onlineActivity-error-file-type"); + actionResponse.setRenderParameter("text", text); + actionRequest.setAttribute("actId", actId); + return; + } + long repositoryId = DLFolderConstants.getDataRepositoryId(themeDisplay.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID); + long folderId = createDLFolders(user.getUserId(), repositoryId, actionRequest); + FileEntry document; + try{ + //Subimos el Archivo en la Document Library + ServiceContext serviceContext= ServiceContextFactory.getInstance( DLFileEntry.class.getName(), actionRequest); + //Damos permisos al archivo para usuarios de comunidad. + //serviceContext.setAddGroupPermissions(true); + document = DLAppLocalServiceUtil.addFileEntry( + themeDisplay.getUserId(), repositoryId , folderId , fileName, mimeType, fileName, StringPool.BLANK, StringPool.BLANK, file , serviceContext ) ; + }catch(Exception e){ + actionResponse.setRenderParameter("text", text); + actionRequest.setAttribute("actId", actId); + throw(e); + } + LmsPrefs prefs = LmsPrefsLocalServiceUtil.fetchLmsPrefs(themeDisplay.getCompanyId()); + try{ + ResourcePermissionLocalServiceUtil.setResourcePermissions(themeDisplay.getCompanyId(), DLFileEntry.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(document.getFileEntryId()) , prefs.getTeacherRole(), new String[]{"VIEW"}); + ResourcePermissionLocalServiceUtil.setResourcePermissions(themeDisplay.getCompanyId(), DLFileEntry.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(document.getFileEntryId()) , prefs.getEditorRole(), new String[]{"VIEW"}); + }catch(Exception e){ + e.printStackTrace(); + } + Element fileXML=SAXReaderUtil.createElement(FILE_XML); + fileXML.addAttribute("id", Long.toString(document.getFileEntryId())); + resultadosXML.add(fileXML); + } } if(isSetTextoEnr){ Element richTextXML=SAXReaderUtil.createElement(RICH_TEXT_XML); richTextXML.setText(text); resultadosXML.add(richTextXML); - } - else { + } else { Element textXML=SAXReaderUtil.createElement(TEXT_XML); textXML.setText(text); resultadosXML.add(textXML); } - - LearningActivityTry learningActivityTry = LearningActivityTryLocalServiceUtil.createLearningActivityTry(actId,ServiceContextFactory.getInstance(actionRequest)); + + LearningActivityTry learningActivityTry = null; + if(Validator.isNotNull(result) && Validator.isNull(result.getEndDate())){ + //Si hay resultado sin corregir se actualiza el último try + learningActivityTry = LearningActivityTryLocalServiceUtil.getLastLearningActivityTryByActivityAndUser(actId, user.getUserId()); + //Si no se ha subido un archivo nuevo vuelvo a guardar el archivo que estaba guardado previamente + if(isSetFichero && Validator.isNull(fileName)){ + Iterator nodeItr = SAXReaderUtil.read(learningActivityTry.getTryResultData()).getRootElement().nodeIterator(); + while(nodeItr.hasNext()) { + Node element = nodeItr.next(); + if(OnlineActivity.FILE_XML.equals(element.getName())) { + Element fileXML=SAXReaderUtil.createElement(FILE_XML); + fileXML.addAttribute("id", ((Element)element).attributeValue("id")); + resultadosXML.add(fileXML); + } + } + } + } + if(Validator.isNull(learningActivityTry)) + //Si no se encuentra ningún intento previo se crea + learningActivityTry = LearningActivityTryLocalServiceUtil.createLearningActivityTry(actId,ServiceContextFactory.getInstance(actionRequest)); + learningActivityTry.setTryResultData(resultadosXMLDoc.formattedString()); - //learningActivityTry.setEndDate(new Date()); - //learningActivityTry.setResult(0); LearningActivityTryLocalServiceUtil.updateLearningActivityTry(learningActivityTry); SessionMessages.add(actionRequest, "onlinetaskactivity.updating"); } - } @@ -388,9 +406,7 @@ public void edit(ActionRequest actionRequest,ActionResponse actionResponse)throw actionResponse.setRenderParameters(actionRequest.getParameterMap()); if(ParamUtil.getLong(actionRequest, "actId", 0)==0) - { actionResponse.setRenderParameter("jspPage", "/html/onlinetaskactivity/admin/edit.jsp"); - } } public void editactivity(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException, Exception { @@ -408,43 +424,29 @@ public void editactivity(ActionRequest actionRequest, ActionResponse actionRespo @Override public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException { + ThemeDisplay themeDisplay =(ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); long actId=0; - if(ParamUtil.getBoolean(renderRequest, "actionEditingDetails", false)){ - actId=ParamUtil.getLong(renderRequest, "resId", 0); renderResponse.setProperty("clear-request-parameters",Boolean.TRUE.toString()); - } - else{ + }else actId=ParamUtil.getLong(renderRequest, "actId", 0); - } - if(actId==0)// TODO Auto-generated method stub - { + if(actId==0) renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); - } - else - { - LearningActivity activity; - try { - - //auditing - ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY); - - activity = LearningActivityLocalServiceUtil.getLearningActivity(actId); - long typeId=activity.getTypeId(); - - if(typeId==6) - { - super.render(renderRequest, renderResponse); - } - else - { - renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); - } - } catch (PortalException e) { - } catch (SystemException e) { - } + else { + LearningActivity activity; + try { + activity = LearningActivityLocalServiceUtil.getLearningActivity(actId); + long typeId=activity.getTypeId(); + + if(typeId==6) + super.render(renderRequest, renderResponse); + else + renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); + } catch (PortalException | SystemException e) { + e.printStackTrace(); + } } } diff --git a/docroot/WEB-INF/src/com/liferay/lms/P2PAssignations.java b/docroot/WEB-INF/src/com/liferay/lms/P2PAssignations.java index c362b563c..8b8727ff8 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/P2PAssignations.java +++ b/docroot/WEB-INF/src/com/liferay/lms/P2PAssignations.java @@ -115,9 +115,10 @@ public void asignCorrectionP2PActivity(P2pActivity activity){ //Get assignation Number try { String validations = LearningActivityLocalServiceUtil.getExtraContentValue(actId,"validaciones"); - numAsigns = Integer.valueOf(validations); + if(Validator.isNotNull(validations)){ + numAsigns = Integer.valueOf(validations); + } } catch (SystemException e1) { - // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e) { e.printStackTrace(); diff --git a/docroot/WEB-INF/src/com/liferay/lms/QuestionsAdmin.java b/docroot/WEB-INF/src/com/liferay/lms/QuestionsAdmin.java index ec5336238..898fd97ea 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/QuestionsAdmin.java +++ b/docroot/WEB-INF/src/com/liferay/lms/QuestionsAdmin.java @@ -38,6 +38,9 @@ import au.com.bytecode.opencsv.CSVWriter; import com.liferay.counter.service.CounterLocalServiceUtil; +import com.liferay.lms.learningactivity.ResourceExternalLearningActivityType; +import com.liferay.lms.learningactivity.SurveyLearningActivityType; +import com.liferay.lms.learningactivity.TestLearningActivityType; import com.liferay.lms.learningactivity.questiontype.QuestionType; import com.liferay.lms.learningactivity.questiontype.QuestionTypeRegistry; import com.liferay.lms.learningactivity.questiontype.SurveyHorizontalOptionsQuestionType; @@ -87,7 +90,7 @@ public class QuestionsAdmin extends MVCPortlet{ private static Log log = LogFactoryUtil.getLog(QuestionsAdmin.class); - + public static final Pattern DOCUMENT_EXCEPTION_MATCHER = Pattern.compile("Error on line (\\d+) of document ([^ ]+) : (.*)"); public static final String TIMES_NEW_ROMAN = "Times New Roman"; public static final int COLUMN_INDEX_QUESTION_TITLE = 0; @@ -97,49 +100,49 @@ public class QuestionsAdmin extends MVCPortlet{ public static final int COLUMN_INDEX_ANSWER_IS_CORRECT = 4; public static final int COLUMN_INDEX_ANSWER_FEEDBACK_CORRECT = 5; public static final int COLUMN_INDEX_ANSWER_FEEDBACK_INCORRECT = 6; - - + + HashMap answersMap = new HashMap(); - - + + @SuppressWarnings("unchecked") public void moveQuestion(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { - + ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); PermissionChecker permissionChecker=themeDisplay.getPermissionChecker(); - + long questionId = ParamUtil.getLong(actionRequest, "pageId"), - prevQuestionId = ParamUtil.getLong(actionRequest, "prevPageId"), - nextQuestionId = ParamUtil.getLong(actionRequest, "nextPageId"); + prevQuestionId = ParamUtil.getLong(actionRequest, "prevPageId"), + nextQuestionId = ParamUtil.getLong(actionRequest, "nextPageId"); TestQuestion question = TestQuestionLocalServiceUtil.getTestQuestion(questionId); if(questionId>0){ if(permissionChecker.hasPermission(themeDisplay.getScopeGroupId(), LearningActivity.class.getName(), questionId, ActionKeys.UPDATE)){ TestQuestionLocalServiceUtil.moveQuestion(questionId, prevQuestionId, nextQuestionId); } } - + String orderByCol = ParamUtil.getString(actionRequest, "orderByCol"); - if(orderByCol==null || orderByCol=="") - orderByCol = "weight"; - actionRequest.setAttribute("orderByCol", orderByCol); - //Create an instance of BeanComparator telling it wich is the order column - //Get the type of ordering, asc or desc - String orderByType = ParamUtil.getString(actionRequest, "orderByType"); - if(orderByType==null || orderByType=="") - orderByType = "asc"; - actionRequest.setAttribute("orderByType", orderByType); - TestQuestion questions = TestQuestionLocalServiceUtil.getTestQuestion(questionId); - List listaAux = TestQuestionLocalServiceUtil.getQuestions(questions.getActId()); - List listaTotal = new LinkedList(); - listaTotal = ListUtil.copy(listaAux); - //Sort - BeanComparator beanComparator = new BeanComparator(orderByCol); - if(orderByType.equals("asc")){ - Collections.sort(listaTotal, beanComparator); - } - else { - Collections.sort(listaTotal, Collections.reverseOrder(beanComparator)); - } + if(orderByCol==null || orderByCol=="") + orderByCol = "weight"; + actionRequest.setAttribute("orderByCol", orderByCol); + //Create an instance of BeanComparator telling it wich is the order column + //Get the type of ordering, asc or desc + String orderByType = ParamUtil.getString(actionRequest, "orderByType"); + if(orderByType==null || orderByType=="") + orderByType = "asc"; + actionRequest.setAttribute("orderByType", orderByType); + TestQuestion questions = TestQuestionLocalServiceUtil.getTestQuestion(questionId); + List listaAux = TestQuestionLocalServiceUtil.getQuestions(questions.getActId()); + List listaTotal = new LinkedList(); + listaTotal = ListUtil.copy(listaAux); + //Sort + BeanComparator beanComparator = new BeanComparator(orderByCol); + if(orderByType.equals("asc")){ + Collections.sort(listaTotal, beanComparator); + } + else { + Collections.sort(listaTotal, Collections.reverseOrder(beanComparator)); + } //Return the orderer list actionRequest.setAttribute("total", listaTotal.size()); actionRequest.setAttribute("listaAux", listaTotal); @@ -147,20 +150,20 @@ public void moveQuestion(ActionRequest actionRequest, ActionResponse actionRespo actionResponse.setRenderParameter("resId", Long.toString(question.getActId())); actionResponse.setRenderParameter("jsp", "/html/questions/admin/orderQuestions.jsp"); } - + public void upquestion(ActionRequest actionRequest, ActionResponse actionResponse) - throws Exception { + throws Exception { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); - + PermissionChecker permissionChecker=themeDisplay.getPermissionChecker(); - + long actId = ParamUtil.getLong(actionRequest, "actId",0); long testQuestionId = ParamUtil.getLong(actionRequest, "questionId"); - + if(actId>0) { LearningActivity larn = LearningActivityLocalServiceUtil.getLearningActivity(actId); - + if(permissionChecker.hasPermission(larn.getGroupId(), LearningActivity.class.getName(), larn.getActId(), ActionKeys.UPDATE)|| permissionChecker.hasOwnerPermission(larn.getCompanyId(), LearningActivity.class.getName(), larn.getActId(),larn.getUserId(), ActionKeys.UPDATE)) @@ -169,20 +172,20 @@ public void upquestion(ActionRequest actionRequest, ActionResponse actionRespons } } } - + public void downquestion(ActionRequest actionRequest, ActionResponse actionResponse) - throws Exception { - ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); - + throws Exception { + ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); + PermissionChecker permissionChecker=themeDisplay.getPermissionChecker(); - + long actId = ParamUtil.getLong(actionRequest, "actId",0); long testQuestionId = ParamUtil.getLong(actionRequest, "questionId"); - + if(actId>0) { LearningActivity larn = LearningActivityLocalServiceUtil.getLearningActivity(actId); - + if(permissionChecker.hasPermission(larn.getGroupId(), LearningActivity.class.getName(), larn.getActId(), ActionKeys.UPDATE)|| permissionChecker.hasOwnerPermission(larn.getCompanyId(), LearningActivity.class.getName(), larn.getActId(),larn.getUserId(), ActionKeys.UPDATE)) @@ -191,34 +194,34 @@ public void downquestion(ActionRequest actionRequest, ActionResponse actionRespo } } } - + public void editQuestion(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { - + long questionId = ParamUtil.getLong(actionRequest, "questionId", 0); long actid = ParamUtil.getLong(actionRequest, "resId"); long questionType = ParamUtil.getLong(actionRequest, "typeId", -1); String questionText = ParamUtil.get(actionRequest, "text", ""); - + boolean penalize = false; String partialCorrection = StringPool.BLANK; - + penalize = ParamUtil.getBoolean(actionRequest, "penalize"); log.debug("***penalize:"+penalize); partialCorrection = ParamUtil.getString(actionRequest, "partialcorrection", "false"); if(Boolean.parseBoolean(partialCorrection)){ penalize = false; } - - + + log.debug("***questionId:"+questionId); log.debug("***penalize:"+penalize); - + String backUrl = ParamUtil.get(actionRequest, "backUrl", ""); String formatType = ParamUtil.getString(actionRequest, "formattype", PropsUtil.get("lms.question.formattype.normal")); Document document = null; Element rootElement = null; - + log.debug("questionType: " + questionType); if(questionType == 6 && PropsUtil.get("lms.question.formattype.horizontal").equals(formatType)){ SurveyHorizontalOptionsQuestionType horizontalType = new SurveyHorizontalOptionsQuestionType(); @@ -228,9 +231,9 @@ public void editQuestion(ActionRequest actionRequest, ActionResponse actionRespo questionType = verticalType.getTypeId(); } log.debug("questionType: " + questionType); - + LearningActivityLocalServiceUtil.setExtraContentValue(actid, "isBank", "false"); - + ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); if(Validator.isNotNull(questionText)){//porque no se permite vacio ya que eliminar pregunta va por otro lado TestQuestion question = null; @@ -241,7 +244,7 @@ public void editQuestion(ActionRequest actionRequest, ActionResponse actionRespo question.setQuestionType(questionType); question.setActId(actid); question.setWeight(question.getQuestionId()); - + document = SAXReaderUtil.createDocument(); rootElement = document.addElement("question"); Element elem = SAXReaderUtil.createElement("formattype"); @@ -252,7 +255,7 @@ public void editQuestion(ActionRequest actionRequest, ActionResponse actionRespo rootElement.add(elem); question.setExtracontent(document.formattedString()); TestQuestionLocalServiceUtil.addTestQuestion(question); - + }else{//Pregunta existente question = TestQuestionLocalServiceUtil.getTestQuestion(questionId); log.debug("questionType: " + questionType); @@ -262,7 +265,7 @@ public void editQuestion(ActionRequest actionRequest, ActionResponse actionRespo question = TestQuestionLocalServiceUtil.updateTestQuestion(question); log.debug("question.getQuestionType(): " + question.getQuestionType()); } - + String typeOrderBefore = "false"; String partialCorrectionBefore = "false"; try{ @@ -415,7 +418,7 @@ public void editQuestion(ActionRequest actionRequest, ActionResponse actionRespo SessionErrors.add(actionRequest, "execactivity.editquestions.newquestion.error.text.required"); actionResponse.setRenderParameter("message", LanguageUtil.get(themeDisplay.getLocale(), "execactivity.editquestions.newquestion")); } - + log.debug("questionType: " + questionType); if(SessionErrors.size(actionRequest)==0) SessionMessages.add(actionRequest, "question-modified-successfully"); @@ -427,13 +430,13 @@ public void editQuestion(ActionRequest actionRequest, ActionResponse actionRespo actionResponse.setRenderParameter("backUrl", backUrl); actionResponse.setRenderParameter("jspPage", "/html/questions/admin/editQuestion.jsp"); } - + public void serveResource(ResourceRequest request, ResourceResponse response)throws PortletException, IOException { String action = ParamUtil.getString(request, "action"); long actId = ParamUtil.getLong(request, "resId",0); response.setCharacterEncoding(StringPool.UTF8); - + try { if(action.equals("exportResultsCsv")){ response.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=data.csv"); @@ -490,17 +493,20 @@ public void serveResource(ResourceRequest request, ResourceResponse response)th //Obtenemos las respuestas que hay introducido. for(Element question:rootElement.elements("question")){ + try{ + TestQuestion q = TestQuestionLocalServiceUtil.getTestQuestion(Long.valueOf(question.attributeValue("id"))); - TestQuestion q = TestQuestionLocalServiceUtil.getTestQuestion(Long.valueOf(question.attributeValue("id"))); - - if(q.getQuestionType() == 0){ + if(q.getQuestionType() == 0){ - for(Element answerElement:question.elements("answer")){ - //Guardamos el id de la respuesta para posteriormente obtener su texto. - if(Validator.isNumber(answerElement.attributeValue("id"))){ - answersIds.add(Long.valueOf(answerElement.attributeValue("id"))); + for(Element answerElement:question.elements("answer")){ + //Guardamos el id de la respuesta para posteriormente obtener su texto. + if(Validator.isNumber(answerElement.attributeValue("id"))){ + answersIds.add(Long.valueOf(answerElement.attributeValue("id"))); + } } } + }catch(NoSuchTestQuestionException e){ + if(log.isErrorEnabled()) log.error("En la actividad de tipo test "+activity.getActId()+" no se puede exportar la respuesta del usuario "+user.getUserId()+" para la pregunta "+question.attributeValue("id")+" porque ésta fue eliminada."); } } @@ -534,26 +540,26 @@ public void serveResource(ResourceRequest request, ResourceResponse response)th writer.flush(); writer.close(); - + }else if(action.equals("exportXml")){ response.addProperty(HttpHeaders.CONTENT_DISPOSITION,"attachment; fileName=data.xml"); response.setContentType(ContentTypes.TEXT_XML_UTF8); PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(response.getPortletOutputStream(),StringPool.UTF8)); Element quizXML=SAXReaderUtil.createElement("quiz"); Document quizXMLDoc=SAXReaderUtil.createDocument(quizXML); - + List questiones=TestQuestionLocalServiceUtil.getQuestions(actId); List questions = ListUtil.copy(questiones); BeanComparator beanComparator = new BeanComparator("weight"); Collections.sort(questions, beanComparator); - + if(questions!=null &&questions.size()>0){ for(TestQuestion question:questions){ QuestionType qt =new QuestionTypeRegistry().getQuestionType(question.getQuestionType()); quizXML.add(qt.exportXML(question.getQuestionId())); } } - + printWriter.write(quizXMLDoc.formattedString()); printWriter.flush(); printWriter.close(); @@ -565,16 +571,16 @@ public void serveResource(ResourceRequest request, ResourceResponse response)th response.setContentLength((int)file.length()); response.addProperty(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + name); ServletResponseUtil.sendFile(PortalUtil.getHttpServletRequest(request), - PortalUtil.getHttpServletResponse(response), - name, - FileUtil.getBytes(file), - ContentTypes.APPLICATION_VND_MS_EXCEL); - - - - + PortalUtil.getHttpServletResponse(response), + name, + FileUtil.getBytes(file), + ContentTypes.APPLICATION_VND_MS_EXCEL); + + + + } - + response.getPortletOutputStream().flush(); response.getPortletOutputStream().close(); @@ -589,7 +595,7 @@ public void serveResource(ResourceRequest request, ResourceResponse response)th response.getPortletOutputStream().close(); } } - + private String formatString(String str) { String res = ""; @@ -626,7 +632,7 @@ private Long getQuestionIdByAnswerId(Long answerId) throws PortalException, Syst return answersMap.get(answerId).getQuestionId(); } - + public void importQuestions(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { @@ -678,10 +684,10 @@ public void importQuestions(ActionRequest actionRequest, ActionResponse actionRe actionResponse.setRenderParameter("actionEditingDetails", StringPool.TRUE); actionResponse.setRenderParameter("resId", Long.toString(actId)); } - - + + public void importExcelQuestions(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { - + UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest); long actId = ParamUtil.getLong(actionRequest, "resId",0); @@ -701,7 +707,7 @@ public void importExcelQuestions(ActionRequest actionRequest, ActionResponse act workbook = new HSSFWorkbook(excelFile); }catch(Exception e){//Excel 2007 workbook = new XSSFWorkbook(excelFile); - + } //Cogemos la primera hoja @@ -729,23 +735,25 @@ public void importExcelQuestions(ActionRequest actionRequest, ActionResponse act if(questionTitle!=null && Validator.isNotNull(questionTitle.trim())){ questionType = Integer.valueOf(row.getCell(COLUMN_INDEX_QUESTION_TYPE).getStringCellValue()); questionPenalize = Boolean.parseBoolean(row.getCell(COLUMN_INDEX_QUESTION_PENALIZE).getStringCellValue()); - //Es pregunta con respuesta - if (log.isDebugEnabled()) log.debug("Line: " + fila + " ***********Es pregunta con respuesta************"); + //Es pregunta + if (log.isDebugEnabled()) log.debug("Line: " + fila + " ***********Es pregunta************"); if (log.isDebugEnabled()) log.debug("Line: " + fila + " Titulo pregunta: " + questionTitle); if (log.isDebugEnabled()) log.debug("Line: " + fila + " Tipo: " + questionType); if (log.isDebugEnabled()) log.debug("Line: " + fila + " Penalize: " + questionPenalize); - if (log.isDebugEnabled()) log.debug("Line: " + fila + " Titulo respuesta: " + answerTitle); - if (log.isDebugEnabled()) log.debug("Line: " + fila + " Es correcta: " + answerIsCorrect); - + //Creamos la pregunta. question =TestQuestionLocalServiceUtil.addQuestion(actId, questionTitle, questionType); question.setPenalize(questionPenalize); question = TestQuestionLocalServiceUtil.updateTestQuestion(question); - //Creamos la respuesta - TestAnswerLocalServiceUtil.addTestAnswer(question.getQuestionId(), answerTitle, feedbackCorrect, feedbackIncorrect, answerIsCorrect); - - - + if(answerTitle!=null && Validator.isNotNull(answerTitle.trim())){ + //Si tiene respuestas, creamos la respuesta + if (log.isDebugEnabled()) log.debug("Line: " + fila + " ***********Tiene respuesta************"); + if (log.isDebugEnabled()) log.debug("Line: " + fila + " Titulo respuesta: " + answerTitle); + if (log.isDebugEnabled()) log.debug("Line: " + fila + " Es correcta: " + answerIsCorrect); + TestAnswerLocalServiceUtil.addTestAnswer(question.getQuestionId(), answerTitle, feedbackCorrect, feedbackIncorrect, answerIsCorrect); + } + + }else{ //Es solo respuesta if (log.isDebugEnabled()) log.debug("Line: " + fila + " ***********Es solo respuesta************"); if (log.isDebugEnabled()) log.debug("Line: " + fila + " Titulo respuesta: " + answerTitle); @@ -753,12 +761,12 @@ public void importExcelQuestions(ActionRequest actionRequest, ActionResponse act if(feedbackCorrect!=null && feedbackCorrect.length()>1000){ feedbackCorrect = feedbackCorrect.substring(0, 999); } - + if(feedbackIncorrect!=null && feedbackIncorrect.length()>1000){ feedbackIncorrect = feedbackIncorrect.substring(0, 999); } if(question!=null){ - TestAnswerLocalServiceUtil.addTestAnswer(question.getQuestionId(), answerTitle, feedbackCorrect, feedbackIncorrect, answerIsCorrect); + TestAnswerLocalServiceUtil.addTestAnswer(question.getQuestionId(), answerTitle, feedbackCorrect, feedbackIncorrect, answerIsCorrect); } } }catch(Exception e){ @@ -781,35 +789,35 @@ public void importExcelQuestions(ActionRequest actionRequest, ActionResponse act allCorrect=false; e.printStackTrace(); } - + } - + if(allCorrect){ - System.out.println("ALL CORRECT!!!"); + log.debug("ALL CORRECT!!!"); actionResponse.setRenderParameter("jspPage", "/html/questions/admin/editquestions.jsp"); SessionMessages.add(actionRequest, "questions-added-successfully"); } } - + } - + if (!SessionErrors.isEmpty(actionRequest)){ actionResponse.setRenderParameter("jspPage", "/html/questions/admin/importQuestionsExcel.jsp"); } - + actionResponse.setRenderParameter("actionEditingDetails", StringPool.TRUE); actionResponse.setRenderParameter("resId", Long.toString(actId)); } - + private File exportExcelQuestions(ThemeDisplay themeDisplay, long actId) throws PortletException, IOException { - + log.debug("::ARRANCAMOS HILO USERS EXPORT EXCEL:::"); int rowNumber = 1; // Presenta en pantalla informacion sobre este hilo en particular File file = FileUtil.createTempFile("xls"); try { - + FileOutputStream bw = null; try { bw = new FileOutputStream(file); @@ -826,61 +834,72 @@ private File exportExcelQuestions(ThemeDisplay themeDisplay, long actId) throws } HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFSheet sheet = workbook.createSheet(LanguageUtil.get(themeDisplay.getLocale(), "questions", "questions")); - - HSSFFont font = workbook.createFont(); - font.setFontName(TIMES_NEW_ROMAN); - font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); - HSSFCellStyle style = workbook.createCellStyle(); - style.setFont(font); - - exportExcelLine(headersTitle, sheet.createRow(0), style); - - font = workbook.createFont(); - font.setFontName(TIMES_NEW_ROMAN); - style = workbook.createCellStyle(); - style.setFont(font); - String[] questionLine = new String[headers.length]; - + HSSFSheet sheet = workbook.createSheet(LanguageUtil.get(themeDisplay.getLocale(), "questions", "questions")); + + HSSFFont font = workbook.createFont(); + font.setFontName(TIMES_NEW_ROMAN); + font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); + HSSFCellStyle style = workbook.createCellStyle(); + style.setFont(font); + + exportExcelLine(headersTitle, sheet.createRow(0), style); + + font = workbook.createFont(); + font.setFontName(TIMES_NEW_ROMAN); + style = workbook.createCellStyle(); + style.setFont(font); + String[] questionLine = new String[headers.length]; + List testAnswers = null; + for(TestQuestion question: TestQuestionLocalServiceUtil.getQuestions(actId)){ questionLine[COLUMN_INDEX_QUESTION_TITLE]=question.getText(); questionLine[COLUMN_INDEX_QUESTION_TYPE]=String.valueOf(question.getQuestionType()); questionLine[COLUMN_INDEX_QUESTION_PENALIZE]= String.valueOf(question.getPenalize()); i=0; - for(TestAnswer answer: TestAnswerLocalServiceUtil.getTestAnswersByQuestionId(question.getQuestionId())){ - questionLine[COLUMN_INDEX_ANSWER_TITLE]=answer.getAnswer(); - questionLine[COLUMN_INDEX_ANSWER_IS_CORRECT]=String.valueOf(answer.isIsCorrect()); - questionLine[COLUMN_INDEX_ANSWER_FEEDBACK_CORRECT]=answer.getFeedbackCorrect(); - questionLine[COLUMN_INDEX_ANSWER_FEEDBACK_INCORRECT]=answer.getFeedbacknocorrect(); - - exportExcelLine(questionLine, sheet.createRow(rowNumber++), style); - - if(questionLine[COLUMN_INDEX_QUESTION_TITLE]!="" || questionLine[COLUMN_INDEX_QUESTION_TYPE]!=""|| questionLine[COLUMN_INDEX_QUESTION_PENALIZE]!= ""){ - questionLine[COLUMN_INDEX_QUESTION_TITLE]=""; - questionLine[COLUMN_INDEX_QUESTION_TYPE]=""; - questionLine[COLUMN_INDEX_QUESTION_PENALIZE]= ""; + testAnswers = TestAnswerLocalServiceUtil.getTestAnswersByQuestionId(question.getQuestionId()); + + if(testAnswers != null && testAnswers.size() > 0){ + for(TestAnswer answer: testAnswers){ + questionLine[COLUMN_INDEX_ANSWER_TITLE]=answer.getAnswer(); + questionLine[COLUMN_INDEX_ANSWER_IS_CORRECT]=String.valueOf(answer.isIsCorrect()); + questionLine[COLUMN_INDEX_ANSWER_FEEDBACK_CORRECT]=answer.getFeedbackCorrect(); + questionLine[COLUMN_INDEX_ANSWER_FEEDBACK_INCORRECT]=answer.getFeedbacknocorrect(); + + exportExcelLine(questionLine, sheet.createRow(rowNumber++), style); + + if(questionLine[COLUMN_INDEX_QUESTION_TITLE]!="" || questionLine[COLUMN_INDEX_QUESTION_TYPE]!=""|| questionLine[COLUMN_INDEX_QUESTION_PENALIZE]!= ""){ + questionLine[COLUMN_INDEX_QUESTION_TITLE]=""; + questionLine[COLUMN_INDEX_QUESTION_TYPE]=""; + questionLine[COLUMN_INDEX_QUESTION_PENALIZE]= ""; + } } + }else{ + questionLine[COLUMN_INDEX_ANSWER_TITLE]=""; + questionLine[COLUMN_INDEX_ANSWER_IS_CORRECT]=""; + questionLine[COLUMN_INDEX_ANSWER_FEEDBACK_CORRECT]=""; + questionLine[COLUMN_INDEX_ANSWER_FEEDBACK_INCORRECT]=""; + exportExcelLine(questionLine, sheet.createRow(rowNumber++), style); } - + } workbook.write(bw); - + try { bw.close(); } - catch (IOException e) { + catch (IOException e) { e.printStackTrace(); } - + }catch (Exception e) { e.printStackTrace(); } - + return file; } - - + + private void exportExcelLine(String[] line,HSSFRow row,HSSFCellStyle style){ int columnNumer = 0; for (String column : line) { @@ -889,19 +908,19 @@ private void exportExcelLine(String[] line,HSSFRow row,HSSFCellStyle style){ cell.setCellValue(column); } } - + public void setBankTest(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception{ - + long actId = ParamUtil.getLong(actionRequest, "actId", 0); String redirect = actionRequest.getParameter("redirect"); String isMultiple = ParamUtil.getString(actionRequest, "banks-multipleselections", "false"); String isBank = ParamUtil.getString(actionRequest, "is-bank", "false"); String assetCategoryIds = ParamUtil.getString(actionRequest, "assetCategoryIds", StringPool.BLANK); long[] longCategoryIds = GetterUtil.getLongValues(StringUtil.split(assetCategoryIds)); - + AssetEntryQuery entryQuery = new AssetEntryQuery(); entryQuery.setAllCategoryIds(longCategoryIds); - + if(!Validator.equals(AssetEntryLocalServiceUtil.getEntries(entryQuery).size(), 0)){ LearningActivityLocalServiceUtil.setExtraContentValue(actId,"isBank", isBank); LearningActivityLocalServiceUtil.setExtraContentValue(actId,"isMultiple", isMultiple); @@ -914,7 +933,7 @@ public void setBankTest(ActionRequest actionRequest, ActionResponse actionRespon }else{ SessionErrors.add(actionRequest, "error-not-results"); } - + WindowState windowState = actionRequest.getWindowState(); if (Validator.isNotNull(redirect)) { if (!windowState.equals(LiferayWindowState.POP_UP)) { @@ -928,7 +947,7 @@ public void setBankTest(ActionRequest actionRequest, ActionResponse actionRespon } } } - + public void deletequestion(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { @@ -941,12 +960,13 @@ public void deletequestion(ActionRequest actionRequest, ActionResponse actionRes TestQuestionLocalServiceUtil.deleteTestQuestion(question.getQuestionId()); SessionMessages.add(actionRequest, "question-deleted-successfully"); - if (learnact.getTypeId() == 0) { + if (learnact.getTypeId() == ResourceExternalLearningActivityType.TYPE_ID || learnact.getTypeId() == SurveyLearningActivityType.TYPE_ID || learnact.getTypeId() == TestLearningActivityType.TYPE_ID) { QuestionType qt =new QuestionTypeRegistry().getQuestionType(question.getQuestionType()); actionResponse.setRenderParameter("actionEditingDetails", StringPool.TRUE); actionResponse.setRenderParameter("resId", Long.toString(question.getActId())); actionResponse.setRenderParameter("jspPage", qt.getURLBack()); + } } - + } diff --git a/docroot/WEB-INF/src/com/liferay/lms/ResourceExternalActivity.java b/docroot/WEB-INF/src/com/liferay/lms/ResourceExternalActivity.java index 3f54a91af..8c6750e99 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/ResourceExternalActivity.java +++ b/docroot/WEB-INF/src/com/liferay/lms/ResourceExternalActivity.java @@ -240,7 +240,7 @@ public void render(RenderRequest renderRequest, RenderResponse renderResponse) String parametros = ""; if(videoControlDisabled && !userPassed){ - parametros += "?background=1&loop=0&mute=0"; + parametros += "?background=1&loop=0&mute=0&autoplay=1"; } videoCode += parametros; log.debug("videoCode: " + videoCode); @@ -268,25 +268,28 @@ public void render(RenderRequest renderRequest, RenderResponse renderResponse) renderRequest.setAttribute("mimeType", "video/" + mimeType); renderRequest.setAttribute("video", videoCode); - List listQuestions = TestQuestionLocalServiceUtil.getQuestions(actId); - renderRequest.setAttribute("listQuestions", listQuestions); - - //Ahora pasamos los tiempos de las preguntas - Hashtable timeQuestions = new Hashtable(); - Element element = null; - for(TestQuestion question: listQuestions){ - try{ - element = root.element("question_" + question.getQuestionId()); - if(element != null){ - timeQuestions.put(question.getQuestionId(), Integer.parseInt(element.getText())); + if(!hasPermissionAccessCourseFinished){ + + List listQuestions = TestQuestionLocalServiceUtil.getQuestions(actId); + renderRequest.setAttribute("listQuestions", listQuestions); + + //Ahora pasamos los tiempos de las preguntas + Hashtable timeQuestions = new Hashtable(); + Element element = null; + for(TestQuestion question: listQuestions){ + try{ + element = root.element("question_" + question.getQuestionId()); + if(element != null){ + timeQuestions.put(question.getQuestionId(), Integer.parseInt(element.getText())); + } + }catch(Exception e){ + e.printStackTrace(); } - }catch(Exception e){ - e.printStackTrace(); } + + renderRequest.setAttribute("timeQuestions", timeQuestions); } - renderRequest.setAttribute("timeQuestions", timeQuestions); - }else{ //Es un fileEntryId AssetEntry videoAsset= AssetEntryLocalServiceUtil.getAssetEntry(Long.parseLong(video.attributeValue("id"))); @@ -306,17 +309,20 @@ public void render(RenderRequest renderRequest, RenderResponse renderResponse) //Creamos el nuevo intento al usuario ServiceContext serviceContext = ServiceContextFactory.getInstance(LearningActivityTry.class.getName(), renderRequest); - LearningActivityTry learningTry =LearningActivityTryLocalServiceUtil.createLearningActivityTry(actId,serviceContext); - if (lastLearningActivityTry != null){ - learningTry.setTryResultData(lastLearningActivityTry.getTryResultData()); - LearningActivityTryLocalServiceUtil.updateLearningActivityTry(learningTry); - } - renderRequest.setAttribute("latId", learningTry.getLatId()); - //Si no hace falta nota para aprobar ya lo aprobamos - if(isDefaultScore){ - learningTry.setEndDate(new Date()); - learningTry.setResult(100); - LearningActivityTryLocalServiceUtil.updateLearningActivityTry(learningTry); + if(!hasPermissionAccessCourseFinished){ + + LearningActivityTry learningTry =LearningActivityTryLocalServiceUtil.createLearningActivityTry(actId,serviceContext); + if (lastLearningActivityTry != null){ + learningTry.setTryResultData(lastLearningActivityTry.getTryResultData()); + LearningActivityTryLocalServiceUtil.updateLearningActivityTry(learningTry); + } + renderRequest.setAttribute("latId", learningTry.getLatId()); + //Si no hace falta nota para aprobar ya lo aprobamos + if(isDefaultScore){ + learningTry.setEndDate(new Date()); + learningTry.setResult(100); + LearningActivityTryLocalServiceUtil.updateLearningActivityTry(learningTry); + } } //Documentos anexos al recurso externo diff --git a/docroot/WEB-INF/src/com/liferay/lms/actions/AsynchronousConfigurationAction.java b/docroot/WEB-INF/src/com/liferay/lms/actions/AsynchronousConfigurationAction.java new file mode 100644 index 000000000..1dbbab414 --- /dev/null +++ b/docroot/WEB-INF/src/com/liferay/lms/actions/AsynchronousConfigurationAction.java @@ -0,0 +1,68 @@ +package com.liferay.lms.actions; + +import javax.portlet.ActionRequest; +import javax.portlet.ActionResponse; +import javax.portlet.PortletConfig; +import javax.portlet.PortletPreferences; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; + +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.portlet.ConfigurationAction; +import com.liferay.portal.kernel.servlet.SessionMessages; +import com.liferay.portal.kernel.util.ParamUtil; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portlet.PortletPreferencesFactoryUtil; + +public class AsynchronousConfigurationAction implements ConfigurationAction { + + public static final String JSP = "/html/asynchronousprocessdashboard/config/config.jsp"; + + private static Log log = LogFactoryUtil.getLog(AsynchronousConfigurationAction.class); + + public String render(PortletConfig config, RenderRequest renderRequest, RenderResponse renderResponse) throws Exception + { + return JSP; + } + + public void processAction( + PortletConfig portletConfig, ActionRequest actionRequest, + ActionResponse actionResponse) + throws Exception { + + + PortletPreferences portletPreferences = + PortletPreferencesFactoryUtil.getPortletSetup( + actionRequest, ParamUtil.getString(actionRequest, "portletResource")); + + + + String refreshPageEachXSeg = ParamUtil.getString(actionRequest,"refreshPageEachXSeg", ""); + portletPreferences.setValue("refreshPageEachXSeg", refreshPageEachXSeg); + + String showAllClassName = ParamUtil.getString(actionRequest,"preferences--showAllClassName--", ""); + portletPreferences.setValue("preferences--showAllClassName--", showAllClassName); + + String classNameValue =""; + if(showAllClassName.equalsIgnoreCase("true")){ + classNameValue = "todos"; + }else{ + classNameValue = StringUtil.merge(actionRequest.getParameterMap().get( "className")); + } + portletPreferences.setValue("className",classNameValue); + + String onlyForUserOwner = ParamUtil.getString(actionRequest,"preferences--onlyForUserOwner--", ""); + portletPreferences.setValue("preferences--onlyForUserOwner--", onlyForUserOwner); + + String showExtraContent = ParamUtil.getString(actionRequest,"preferences--showExtraContent--", ""); + portletPreferences.setValue("preferences--showExtraContent--", showExtraContent); + + portletPreferences.store(); + + SessionMessages.add( + actionRequest, portletConfig.getPortletName() + ".doConfigure"); + + + } +} diff --git a/docroot/WEB-INF/src/com/liferay/lms/actions/GeneralStatsConfigurationAction.java b/docroot/WEB-INF/src/com/liferay/lms/actions/GeneralStatsConfigurationAction.java index 99171ee1c..d4eb1d373 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/actions/GeneralStatsConfigurationAction.java +++ b/docroot/WEB-INF/src/com/liferay/lms/actions/GeneralStatsConfigurationAction.java @@ -28,9 +28,16 @@ public void processAction(PortletConfig portletConfig, ActionRequest actionReque PortletPreferences portletPreferences = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, ParamUtil.getString(actionRequest, "portletResource")); - portletPreferences.setValue("showSearchTagsGeneralStats", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showSearchTagsGeneralStats", false))); - portletPreferences.setValue("showSearchCategoriesGeneralStats", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showSearchCategoriesGeneralStats", true))); - + portletPreferences.setValue("categories", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showSearchTags", false))); + portletPreferences.setValue("showFailed", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showFailed", false))); + portletPreferences.setValue("showFinished", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showFinished", true))); + portletPreferences.setValue("showAvgResult", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showAvgResult", true))); + portletPreferences.setValue("showModules", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showModules", true))); + portletPreferences.setValue("showActivities", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showActivities", true))); + portletPreferences.setValue("showPassed", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showPassed", false))); + portletPreferences.setValue("showInit", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showInit", true))); + portletPreferences.setValue("showCourseClosed", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showCourseClosed", true))); + portletPreferences.setValue("showRegistered", Boolean.toString(ParamUtil.getBoolean(actionRequest, "showRegistered", true))); portletPreferences.store(); SessionMessages.add(actionRequest, portletConfig.getPortletName() + ".doConfigure"); diff --git a/docroot/WEB-INF/src/com/liferay/lms/actions/StudentManagementConfigurationAction.java b/docroot/WEB-INF/src/com/liferay/lms/actions/StudentManagementConfigurationAction.java index 8f8545c43..fdebc3151 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/actions/StudentManagementConfigurationAction.java +++ b/docroot/WEB-INF/src/com/liferay/lms/actions/StudentManagementConfigurationAction.java @@ -41,6 +41,7 @@ public void processAction( prefs.setValue("showActionSocial", actionRequest.getParameter("showActionSocial")); prefs.setValue("showActionAudit", actionRequest.getParameter("showActionAudit")); + prefs.setValue("showEmailAddress", actionRequest.getParameter("showEmailAddress")); prefs.store(); diff --git a/docroot/WEB-INF/src/com/liferay/lms/course/inscriptiontype/UserDaysInscriptionType.java b/docroot/WEB-INF/src/com/liferay/lms/course/inscriptiontype/UserDaysInscriptionType.java index 42784b9de..d9130699b 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/course/inscriptiontype/UserDaysInscriptionType.java +++ b/docroot/WEB-INF/src/com/liferay/lms/course/inscriptiontype/UserDaysInscriptionType.java @@ -2,7 +2,9 @@ import java.util.Calendar; import java.util.Date; +import java.util.HashSet; import java.util.Locale; +import java.util.Set; import javax.portlet.PortletPreferences; import javax.portlet.PortletResponse; @@ -18,6 +20,7 @@ import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.PrefsPropsUtil; import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.model.GroupConstants; import com.liferay.portal.service.PortalPreferencesLocalServiceUtil; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.util.PortletKeys; @@ -49,10 +52,8 @@ public String setExtraContent(UploadRequest uploadRequest,PortletResponse portle PortletPreferences prefs= PortalPreferencesLocalServiceUtil.getPreferences(course.getCompanyId(), course.getGroupCreatedId(), PortletKeys.PREFS_OWNER_TYPE_COMPANY); if(!prefs.isReadOnly("inscription-days")){ - prefs.setValue("inscription-days", value); prefs.store(); - } }else{ return "inscription-days-required"; @@ -66,8 +67,6 @@ public String setExtraContent(UploadRequest uploadRequest,PortletResponse portle return null; } - - @Override public String enrollUser(long courseId, long userId, long teamId, ServiceContext serviceContext) throws PortalException, SystemException { Course course = CourseLocalServiceUtil.getCourse(courseId); @@ -92,4 +91,16 @@ public String getTitle(Locale locale) { public boolean canUnsubscribe() { return false; } + + @Override + public Set getGroupTypesAvailable(){ + Set sites = new HashSet(); + sites.add(GroupConstants.TYPE_SITE_OPEN); + return sites; + } + + @Override + public boolean isActive(long companyId){ + return true; + } } diff --git a/docroot/WEB-INF/src/com/liferay/lms/events/ThemeIdEvent.java b/docroot/WEB-INF/src/com/liferay/lms/events/ThemeIdEvent.java index 062744803..2bb3c9b71 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/events/ThemeIdEvent.java +++ b/docroot/WEB-INF/src/com/liferay/lms/events/ThemeIdEvent.java @@ -9,12 +9,19 @@ public final class ThemeIdEvent implements Serializable { private long moduleId; long themeId; + private long actId; /** * @return the moduleId */ public final long getModuleId() { return moduleId; } + public long getActId() { + return actId; + } + public void setActId(long actId) { + this.actId = actId; + } /** * @param moduleId the moduleId to set */ diff --git a/docroot/WEB-INF/src/com/liferay/lms/expando/LearningActivityCustomAttributesDisplay.java b/docroot/WEB-INF/src/com/liferay/lms/expando/LearningActivityCustomAttributesDisplay.java new file mode 100644 index 000000000..966ceac27 --- /dev/null +++ b/docroot/WEB-INF/src/com/liferay/lms/expando/LearningActivityCustomAttributesDisplay.java @@ -0,0 +1,15 @@ +package com.liferay.lms.expando; + +import com.liferay.lms.model.LearningActivity; +import com.liferay.portlet.expando.model.BaseCustomAttributesDisplay; + +public class LearningActivityCustomAttributesDisplay extends BaseCustomAttributesDisplay { + + public static final String CLASS_NAME = LearningActivity.class.getName(); + + public String getClassName() { + + return CLASS_NAME; + } + +} diff --git a/docroot/WEB-INF/src/com/liferay/lms/lar/ImportUtil.java b/docroot/WEB-INF/src/com/liferay/lms/lar/ImportUtil.java index 40164ae3c..1711898e3 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/lar/ImportUtil.java +++ b/docroot/WEB-INF/src/com/liferay/lms/lar/ImportUtil.java @@ -33,6 +33,8 @@ import com.liferay.portlet.documentlibrary.model.DLFileEntry; import com.liferay.portlet.documentlibrary.model.DLFolderConstants; import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil; +import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil; +import com.liferay.portlet.documentlibrary.service.persistence.DLFileEntryFinderUtil; public class ImportUtil { @@ -87,10 +89,29 @@ public static FileEntry importDLFileEntry(PortletDataContext context, Element en String imageName = name[name.length-1]; InputStream input = context.getZipEntryAsInputStream(entryElement.attributeValue("file")); + log.debug("imageName: " + imageName); + log.debug("input: " + input); + if(input != null){ log.info("mimeType: " + fileEntryOld.getMimeType()); - try { - FileEntry newFile = DLAppLocalServiceUtil.addFileEntry(userId, repositoryId , folderId , imageName, fileEntryOld.getMimeType(), fileEntryOld.getTitle(), fileEntryOld.getDescription(), StringPool.BLANK, IOUtils.toByteArray(input), serviceContext ) ; + try { + + int numFiles = DLFileEntryLocalServiceUtil.getFileEntriesCount(context.getScopeGroupId(), folderId); + FileEntry newFile = null; + String fileEntryTitle = fileEntryOld.getTitle(); + try{ + newFile = DLAppLocalServiceUtil.getFileEntry(context.getScopeGroupId(), folderId, fileEntryTitle); + if (newFile != null){ + log.debug("if (newFile != null)"); + int i = numFiles + 1; + fileEntryTitle = fileEntryTitle + i; + } + }catch (Exception e){ + log.debug("Excepcion - getFileEntry - se crea el fichero"); + } + log.debug("fileEntryTitle: " + fileEntryTitle); + newFile = DLAppLocalServiceUtil.addFileEntry(userId, repositoryId , folderId , imageName, fileEntryOld.getMimeType(), fileEntryTitle, fileEntryOld.getDescription(), StringPool.BLANK, IOUtils.toByteArray(input), serviceContext ) ; + if(newFile != null)log.info("newFile: " + newFile.getFileEntryId()); return newFile; } catch(DuplicateFileException dfl){ diff --git a/docroot/WEB-INF/src/com/liferay/lms/lar/LearningActivityImport.java b/docroot/WEB-INF/src/com/liferay/lms/lar/LearningActivityImport.java index 8486e5995..d01f23dc2 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/lar/LearningActivityImport.java +++ b/docroot/WEB-INF/src/com/liferay/lms/lar/LearningActivityImport.java @@ -1,7 +1,9 @@ package com.liferay.lms.lar; import java.io.InputStream; +import java.util.HashMap; import java.util.Iterator; +import java.util.List; import org.apache.commons.io.IOUtils; @@ -65,14 +67,22 @@ public static long importLearningActivity(PortletDataContext context, Element en larn.setGroupId(newModule.getGroupId()); larn.setModuleId(newModule.getModuleId()); - LearningActivity newLarn=LearningActivityLocalServiceUtil.addLearningActivity(larn,serviceContext); - serviceContext.setScopeGroupId(newLarn.getGroupId()); + //Comprobamos si la actividad ya existe para actualizarla o para crearla nueva + LearningActivity newLarn = null; - //Para actividad de recurso externo - if(larn.getTypeId() == 2){ - //changeExtraContentDocumentIds(newLarn, newModule, userId, context, serviceContext); + try{ + newLarn = LearningActivityLocalServiceUtil.getLearningActivityByUuidAndGroupId(larn.getUuid(), newModule.getGroupId()); + }catch(PortalException | SystemException e){ + log.debug("La actividad no existe, la creamos"); } + if(newLarn == null){ + newLarn=LearningActivityLocalServiceUtil.addLearningActivity(larn,serviceContext); + }else{ + newLarn=LearningActivityLocalServiceUtil.updateLearningActivity(newLarn, larn,serviceContext); + } + + serviceContext.setScopeGroupId(newLarn.getGroupId()); //Seteo de contenido propio de la actividad log.debug("***IMPORT EXTRA CONTENT****"); @@ -105,6 +115,9 @@ public static long importLearningActivity(PortletDataContext context, Element en private static void importQuestions(LearningActivity newLarn, long userId, PortletDataContext context, ServiceContext serviceContext, Element actElement) throws SystemException, PortalException { + //Guardamos los identificadores en un hashmap para actualizar el orden de las preguntas + HashMap questionIdsMap = new HashMap(); + for(Element qElement:actElement.elements("question")){ String pathq = qElement.attributeValue("path"); @@ -112,6 +125,13 @@ private static void importQuestions(LearningActivity newLarn, long userId, Portl question.setActId(newLarn.getActId()); TestQuestion nuevaQuestion=TestQuestionLocalServiceUtil.addQuestion(question.getActId(), question.getText(), question.getQuestionType()); + if(question.getWeight() != question.getQuestionId()){ + nuevaQuestion.setWeight(question.getWeight()); + nuevaQuestion = TestQuestionLocalServiceUtil.updateTestQuestion(nuevaQuestion); + questionIdsMap.put(question.getQuestionId(), nuevaQuestion.getQuestionId()); + } + + questionIdsMap.put(question.getQuestionId(), nuevaQuestion.getQuestionId()); log.info(" Test Question: " + nuevaQuestion.getQuestionId() /*Jsoup.parse(nuevaQuestion.getText()).text()*/); //Si tenemos ficheros en las descripciones de las preguntas. @@ -121,13 +141,22 @@ private static void importQuestions(LearningActivity newLarn, long userId, Portl //log.info(" description : " + description ); nuevaQuestion.setText(description); - TestQuestionLocalServiceUtil.updateTestQuestion(nuevaQuestion); + nuevaQuestion = TestQuestionLocalServiceUtil.updateTestQuestion(nuevaQuestion); } QuestionType qt =new QuestionTypeRegistry().getQuestionType(question.getQuestionType()); qt.importQuestionAnswers(context, qElement, nuevaQuestion.getQuestionId(), userId, serviceContext); } + + List questions = TestQuestionLocalServiceUtil.getQuestions(newLarn.getActId()); + for(TestQuestion question: questions){ + if(question.getWeight() > 0 && questionIdsMap.containsKey(question.getWeight())){ + log.debug("nuevo orden: " + questionIdsMap.get(question.getWeight())); + question.setWeight(questionIdsMap.get(question.getWeight())); + TestQuestionLocalServiceUtil.updateTestQuestion(question); + } + } } /** @@ -224,41 +253,28 @@ private static void importDLFileEntries(LearningActivity newLarn, long userId, P Element theElement = it.next(); log.info("element: " + theElement.toString()); - String messageException = ""; - //try { - log.info(" dlfileentry path: "+theElement.attributeValue("path")); + log.info(" dlfileentry path: "+theElement.attributeValue("path")); - FileEntry newFile = ImportUtil.importDLFileEntry(context, theElement, serviceContext, userId); - - AssetEntry asset = AssetEntryLocalServiceUtil.getEntry(DLFileEntry.class.getName(), newFile.getPrimaryKey()); - - //Ponemos a la actividad el fichero que hemos recuperado. - log.info(" Extracontent : \n"+newLarn.getExtracontent()); - if(newLarn.getTypeId() == 2){ - log.info("TIPO EXTERNO"); - if(countDocument < 0){ - LearningActivityLocalServiceUtil.setExtraContentValue(newLarn.getActId(), "document", String.valueOf(asset.getEntryId())); - }else{ - LearningActivityLocalServiceUtil.setExtraContentValue(newLarn.getActId(), "document" + countDocument, String.valueOf(asset.getEntryId())); - } - countDocument++; - }else if(newLarn.getTypeId() == 7){ - LearningActivityLocalServiceUtil.setExtraContentValue(newLarn.getActId(), "assetEntry", String.valueOf(asset.getEntryId())); + FileEntry newFile = ImportUtil.importDLFileEntry(context, theElement, serviceContext, userId); + + AssetEntry asset = AssetEntryLocalServiceUtil.getEntry(DLFileEntry.class.getName(), newFile.getPrimaryKey()); + + //Ponemos a la actividad el fichero que hemos recuperado. + log.info(" Extracontent : \n"+newLarn.getExtracontent()); + if(newLarn.getTypeId() == 2){ + log.info("TIPO EXTERNO"); + if(countDocument < 0){ + LearningActivityLocalServiceUtil.setExtraContentValue(newLarn.getActId(), "document", String.valueOf(asset.getEntryId())); + }else{ + LearningActivityLocalServiceUtil.setExtraContentValue(newLarn.getActId(), "document" + countDocument, String.valueOf(asset.getEntryId())); } - - Long newActId = newLarn.getActId(); - newLarn = LearningActivityLocalServiceUtil.getLearningActivity(newActId); - - /* }catch(FileExtensionException fee){ - fee.printStackTrace(); - log.info("*ERROR! dlfileentry path FileExtensionException:" + theElement.attributeValue("path")+", "+messageException +", message: "+fee.getMessage()); - }catch(FileSizeException fse){ - log.info("*ERROR! dlfileentry path FileSizeException:" + theElement.attributeValue("path")+messageException +", message: "+ fse.getMessage()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - log.info("*ERROR! dlfileentry path: " + theElement.attributeValue("path")+messageException +", message: "+e.getMessage()); - }*/ + countDocument++; + }else if(newLarn.getTypeId() == 7){ + LearningActivityLocalServiceUtil.setExtraContentValue(newLarn.getActId(), "assetEntry", String.valueOf(asset.getEntryId())); + } + + Long newActId = newLarn.getActId(); + newLarn = LearningActivityLocalServiceUtil.getLearningActivity(newActId); } } diff --git a/docroot/WEB-INF/src/com/liferay/lms/lar/ModuleDataHandlerImpl.java b/docroot/WEB-INF/src/com/liferay/lms/lar/ModuleDataHandlerImpl.java index 5b799a4f1..9c23c4b2e 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/lar/ModuleDataHandlerImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/lar/ModuleDataHandlerImpl.java @@ -41,6 +41,7 @@ import com.liferay.portal.service.ServiceContext; import com.liferay.portlet.documentlibrary.model.DLFolderConstants; import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil; +import com.liferay.util.LmsLocaleUtil; public class ModuleDataHandlerImpl extends BasePortletDataHandler { @@ -377,9 +378,21 @@ private long importEntry(PortletDataContext context, Element entryElement, Modul log.info("ENTRY ELEMENT-->"+entryElement); + Module newModule = null; + + //Comprobamos si el módulo ya existe (por uuid) si ya existe lo actualizamos, no lo creamos de nuevo + try{ + newModule = ModuleLocalServiceUtil.getModuleByUuidAndGroupId(entry.getUuid(), context.getScopeGroupId()); + }catch(PortalException | SystemException e){ + log.debug("Modulo no existe, lo creamos"); + } //Creamos el nuevo módulo en el curso - Module newModule = ModuleLocalServiceUtil.addmodule(entry); + if(newModule == null){ + newModule = ModuleLocalServiceUtil.addmodule(entry); + }else{ + newModule = ModuleLocalServiceUtil.updateModule(newModule, entry); + } //Importamos las imagenes de los módulos ModuleImport.importImageModule(context, entryElement, serviceContext, userId, newModule); diff --git a/docroot/WEB-INF/src/com/liferay/lms/learningactivity/questiontype/DraganddropQuestionType.java b/docroot/WEB-INF/src/com/liferay/lms/learningactivity/questiontype/DraganddropQuestionType.java index 11b823f27..504824d50 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/learningactivity/questiontype/DraganddropQuestionType.java +++ b/docroot/WEB-INF/src/com/liferay/lms/learningactivity/questiontype/DraganddropQuestionType.java @@ -34,9 +34,8 @@ public class DraganddropQuestionType extends BaseQuestionType { private static final long serialVersionUID = 1L; - - private static Log log = LogFactoryUtil.getLog(DraganddropQuestionType.class); + private static Log log = LogFactoryUtil.getLog(DraganddropQuestionType.class); public long getTypeId(){ return 4; } diff --git a/docroot/WEB-INF/src/com/liferay/lms/model/impl/AsynchronousProcessAuditCacheModel.java b/docroot/WEB-INF/src/com/liferay/lms/model/impl/AsynchronousProcessAuditCacheModel.java index 08aebb07b..2e2873c55 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/model/impl/AsynchronousProcessAuditCacheModel.java +++ b/docroot/WEB-INF/src/com/liferay/lms/model/impl/AsynchronousProcessAuditCacheModel.java @@ -35,7 +35,7 @@ public class AsynchronousProcessAuditCacheModel implements CacheModel getModelAttributes() { attributes.put("endDate", getEndDate()); attributes.put("status", getStatus()); attributes.put("statusMessage", getStatusMessage()); + attributes.put("extraContent", getExtraContent()); return attributes; } @@ -202,6 +204,12 @@ public void setModelAttributes(Map attributes) { if (statusMessage != null) { setStatusMessage(statusMessage); } + + String extraContent = (String)attributes.get("extraContent"); + + if (extraContent != null) { + setExtraContent(extraContent); + } } public long getAsynchronousProcessAuditId() { @@ -399,6 +407,19 @@ public void setStatusMessageMap(Map statusMessageMap, } } + public String getExtraContent() { + if (_extraContent == null) { + return StringPool.BLANK; + } + else { + return _extraContent; + } + } + + public void setExtraContent(String extraContent) { + _extraContent = extraContent; + } + @Override public ExpandoBridge getExpandoBridge() { return ExpandoBridgeFactoryUtil.getExpandoBridge(getCompanyId(), @@ -444,6 +465,7 @@ public Object clone() { asynchronousProcessAuditImpl.setEndDate(getEndDate()); asynchronousProcessAuditImpl.setStatus(getStatus()); asynchronousProcessAuditImpl.setStatusMessage(getStatusMessage()); + asynchronousProcessAuditImpl.setExtraContent(getExtraContent()); asynchronousProcessAuditImpl.resetOriginalValues(); @@ -548,12 +570,20 @@ public CacheModel toCacheModel() { asynchronousProcessAuditCacheModel.statusMessage = null; } + asynchronousProcessAuditCacheModel.extraContent = getExtraContent(); + + String extraContent = asynchronousProcessAuditCacheModel.extraContent; + + if ((extraContent != null) && (extraContent.length() == 0)) { + asynchronousProcessAuditCacheModel.extraContent = null; + } + return asynchronousProcessAuditCacheModel; } @Override public String toString() { - StringBundler sb = new StringBundler(21); + StringBundler sb = new StringBundler(23); sb.append("{asynchronousProcessAuditId="); sb.append(getAsynchronousProcessAuditId()); @@ -575,13 +605,15 @@ public String toString() { sb.append(getStatus()); sb.append(", statusMessage="); sb.append(getStatusMessage()); + sb.append(", extraContent="); + sb.append(getExtraContent()); sb.append("}"); return sb.toString(); } public String toXmlString() { - StringBundler sb = new StringBundler(34); + StringBundler sb = new StringBundler(37); sb.append(""); sb.append("com.liferay.lms.model.AsynchronousProcessAudit"); @@ -627,6 +659,10 @@ public String toXmlString() { "statusMessage"); + sb.append( + "extraContent"); sb.append(""); @@ -649,5 +685,6 @@ public String toXmlString() { private int _status; private String _statusMessage; private String _statusMessageCurrentLanguageId; + private String _extraContent; private AsynchronousProcessAudit _escapedModelProxy; } \ No newline at end of file diff --git a/docroot/WEB-INF/src/com/liferay/lms/model/impl/CourseImpl.java b/docroot/WEB-INF/src/com/liferay/lms/model/impl/CourseImpl.java index 782c84e61..4ef4903b7 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/model/impl/CourseImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/model/impl/CourseImpl.java @@ -18,26 +18,40 @@ import java.util.List; import java.util.Locale; +import javax.el.ELException; + +import com.liferay.lms.InscriptionException; +import com.liferay.lms.course.inscriptiontype.InscriptionType; +import com.liferay.lms.course.inscriptiontype.InscriptionTypeRegistry; import com.liferay.lms.model.Course; +import com.liferay.lms.model.CourseCompetence; import com.liferay.lms.model.CourseResult; import com.liferay.lms.model.Schedule; +import com.liferay.lms.model.UserCompetence; +import com.liferay.lms.service.CourseCompetenceLocalServiceUtil; import com.liferay.lms.service.CourseLocalServiceUtil; import com.liferay.lms.service.CourseResultLocalServiceUtil; import com.liferay.lms.service.ScheduleLocalServiceUtil; +import com.liferay.lms.service.UserCompetenceLocalServiceUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.workflow.WorkflowConstants; import com.liferay.portal.model.Group; +import com.liferay.portal.model.GroupConstants; +import com.liferay.portal.model.MembershipRequestConstants; import com.liferay.portal.model.Team; import com.liferay.portal.model.User; import com.liferay.portal.security.permission.ActionKeys; import com.liferay.portal.security.permission.PermissionChecker; import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; import com.liferay.portal.service.GroupLocalServiceUtil; +import com.liferay.portal.service.MembershipRequestLocalServiceUtil; import com.liferay.portal.service.TeamLocalServiceUtil; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; @@ -92,6 +106,11 @@ public Course getParentCourse() throws PortalException, SystemException } } + public boolean isRegistrationOnDate(){ + Date now = new Date(); + return now.before(getEndDate()) && now.after(getStartDate()); + } + @Override public void setTitle(String title) { @@ -326,4 +345,95 @@ public boolean isLocked(User user, PermissionChecker permissionChecker){ return false; } + + public boolean canEnroll(long userId, boolean checkCompetences, Locale locale, PermissionChecker permissionChecker) throws PortalException, InscriptionException, SystemException { + log.debug("canEnroll: " + getCourseId() + " - " + userId + " - " + checkCompetences); + //1.Comprobamos que no esté ya inscrito + if(!GroupLocalServiceUtil.hasUserGroup(userId, getGroupCreatedId())) { + Date now = new Date(); + + if(permissionChecker.hasPermission(this.getGroupCreatedId(), Course.class.getName(), this.getCourseId() , "REGISTER")){ + //2. Fecha actual dentro del periodo de inscripcion + if((getStartDate().before(now) && getEndDate().after(now))){ + + //3.Comprobamos que se cumplan todos los prerequisitos + boolean isPassed = true; + if(checkCompetences){ + List listCourseCompetences = CourseCompetenceLocalServiceUtil.findBycourseId(getCourseId(), true); + int i = 0; + UserCompetence userCompentece = null; + while(isPassed && listCourseCompetences.size() > i) { + userCompentece = UserCompetenceLocalServiceUtil.findByUserIdCompetenceId(userId, listCourseCompetences.get(i).getCompetenceId()); + isPassed = userCompentece != null; + i++; + } + } + if(isPassed) { + // 4. El máximo de inscripciones del curso no ha sido superado + if(getMaxusers()<=0 || CourseLocalServiceUtil.countStudentsFromCourse(this.getCourseId(), this.getCompanyId(), null, null, null, null, WorkflowConstants.STATUS_APPROVED, null, true) < getMaxusers()){ + //5. Comprobamos el tipo de inscripción + Group group = GroupLocalServiceUtil.getGroup(getGroupCreatedId()); + if(group.getType()==GroupConstants.TYPE_SITE_OPEN){ + log.debug("puede inscribirse"); + return true; + }else{ + if(group.getType()==GroupConstants.TYPE_SITE_RESTRICTED){ + if(MembershipRequestLocalServiceUtil.hasMembershipRequest(userId, group.getGroupId(), MembershipRequestConstants.STATUS_PENDING)){ + throw new InscriptionException("status-pending", LanguageUtil.get(locale, "course.pending")); + }else if(MembershipRequestLocalServiceUtil.hasMembershipRequest(userId, group.getGroupId(), MembershipRequestConstants.STATUS_DENIED)){ + throw new InscriptionException("status-denied", LanguageUtil.get(locale, "course.denied")); + }else{ + log.debug("puede inscribirse"); + return true; + } + }else{ + if(group.getType()==GroupConstants.TYPE_SITE_PRIVATE){ + //Debería lanzar una excepción indicando que es privado y que no se puede + log.debug("exception: " + LanguageUtil.get(locale, "inscription.error.site-private")); + throw new InscriptionException("site-private", LanguageUtil.get(locale, "inscription.error.site-private")); + } + } + } + }else { + log.debug("exception: " + LanguageUtil.get(locale, "inscription.error.max-users")); + throw new InscriptionException("max-users", LanguageUtil.get(locale, "inscription-error-max-users")); + } + }else { + //Debería lanzar una excepción indicando que no se cumplen los prerequisitos + log.debug("exception: " + LanguageUtil.get(locale, "inscription.error.competences")); + throw new InscriptionException("competences", LanguageUtil.get(locale, "competence.block")); + } + }else { + //Debería lanzar una excepción indicando que está en periodo de ejecución + log.debug("exception: " + LanguageUtil.get(locale, "inscription.error.registration-dates")); + throw new InscriptionException("registration-dates", LanguageUtil.get(locale, "inscripcion.date.pass")); + } + }else { + log.debug("exception: " + LanguageUtil.get(locale, "inscription.error.permission-register")); + throw new InscriptionException("permission-register", LanguageUtil.get(locale, "inscription.error.permission-register")); + } + log.debug("no puede inscribirse"); + return false; + }else { + log.debug("no estoy inscrito"); + return false; + } + } + + public boolean canUnsubscribe(long userId, PermissionChecker permissionChecker) throws PortalException, SystemException { + Date now = new Date(); + + if (GroupLocalServiceUtil.hasUserGroup(userId, getGroupCreatedId()) && getStartDate().before(now) && + getEndDate().after(now) && permissionChecker.hasPermission(this.getGroupCreatedId(), Course.class.getName(), this.getCourseId() , "REGISTER")) { + CourseResult courseResult = CourseResultLocalServiceUtil.getCourseResultByCourseAndUser(getCourseId(), userId); + Group group = GroupLocalServiceUtil.getGroup(getGroupCreatedId()); + + InscriptionTypeRegistry inscriptionTypeRegistry = new InscriptionTypeRegistry(); + InscriptionType inscriptionType = inscriptionTypeRegistry.getInscriptionType(getInscriptionType()); + + return courseResult == null || courseResult.getPassedDate() == null || (group.getType() == GroupConstants.TYPE_SITE_OPEN) && inscriptionType.canUnsubscribe(); + }else { + return false; + } + } } \ No newline at end of file diff --git a/docroot/WEB-INF/src/com/liferay/lms/model/impl/ScheduleImpl.java b/docroot/WEB-INF/src/com/liferay/lms/model/impl/ScheduleImpl.java index 6867b951a..8e64ae9c7 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/model/impl/ScheduleImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/model/impl/ScheduleImpl.java @@ -14,6 +14,12 @@ package com.liferay.lms.model.impl; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.model.Team; +import com.liferay.portal.service.TeamLocalService; +import com.liferay.portal.service.TeamLocalServiceUtil; + /** * The extended model implementation for the Schedule service. Represents a row in the "Lms_Schedule" database table, with each column mapped to a property of this class. * @@ -31,4 +37,13 @@ public class ScheduleImpl extends ScheduleBaseImpl { */ public ScheduleImpl() { } + + public Team getTeam(){ + try { + return TeamLocalServiceUtil.getTeam(getTeamId()); + } catch (PortalException | SystemException e) { + e.printStackTrace(); + return null; + } + } } \ No newline at end of file diff --git a/docroot/WEB-INF/src/com/liferay/lms/portlet/AsynchronousProcessDashboard.java b/docroot/WEB-INF/src/com/liferay/lms/portlet/AsynchronousProcessDashboard.java index ad3586b70..49adbdffb 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/portlet/AsynchronousProcessDashboard.java +++ b/docroot/WEB-INF/src/com/liferay/lms/portlet/AsynchronousProcessDashboard.java @@ -7,10 +7,13 @@ import java.util.List; import javax.portlet.PortletException; +import javax.portlet.PortletPreferences; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletURL; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; +import javax.portlet.ResourceRequest; +import javax.portlet.ResourceResponse; import com.liferay.lms.model.AsynchronousProcessAudit; import com.liferay.lms.service.AsynchronousProcessAuditLocalServiceUtil; @@ -18,8 +21,11 @@ import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.ParamUtil; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.theme.ThemeDisplay; +import com.liferay.portlet.PortletPreferencesFactoryUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import com.tls.lms.util.LiferaylmsUtil; @@ -27,150 +33,291 @@ * Portlet implementation class AsynchronousProcessDashboard */ public class AsynchronousProcessDashboard extends MVCPortlet { + private String viewJSP = null; public void init() throws PortletException { - viewJSP = getInitParameter("view-jsp"); + viewJSP = getInitParameter("view-template"); } + + private static Log log = LogFactoryUtil + .getLog(AsynchronousProcessDashboard.class); - private static Log log = LogFactoryUtil.getLog(AsynchronousProcessDashboard.class); + public void doView(RenderRequest renderRequest, + RenderResponse renderResponse) throws IOException, PortletException { + showProcesses(renderRequest, renderResponse, false); + } - public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { - ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); - try{ - log.debug(":: VIEW ASSYNCRONOUS PROCESSES DASHBOARD "+this.viewJSP); - String classNameValue = ParamUtil.getString(renderRequest, "className", ""); + public void showProcesses(RenderRequest renderRequest, + RenderResponse renderResponse, boolean ajax) throws IOException, PortletException { - //Obtenemos todos los classname distintos para efectuar la lista; - List classnames = AsynchronousProcessAuditLocalServiceUtil.getDistinctTypes(themeDisplay.getCompanyId()); - renderRequest.setAttribute("classnames", classnames); + ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest + .getAttribute(WebKeys.THEME_DISPLAY); + + if(log.isDebugEnabled()) + log.debug(" ::showViewDefault:: "); + + log.debug(":1: VIEW ASSYNCRONOUS PROCESSES DASHBOARD " + + this.viewJSP); + + try { + + PortletPreferences prefs; + String portletResource = ParamUtil.getString(renderRequest, "portletResource"); + if (Validator.isNotNull(portletResource)){ + prefs = PortletPreferencesFactoryUtil.getPortletSetup(renderRequest, portletResource); + } else { + prefs = renderRequest.getPreferences(); + } - renderRequest.setAttribute("className", classNameValue); - //Obtenemos las fechas para la búsqueda - int startDay= ParamUtil.getInteger(renderRequest, "startDay",-1); - int startMonth= ParamUtil.getInteger(renderRequest, "startMonth",-1); - int startYear= ParamUtil.getInteger(renderRequest, "startYear",-1); - int endDay= ParamUtil.getInteger(renderRequest, "endDay",-1); - int endMonth= ParamUtil.getInteger(renderRequest, "endMonth",-1); - int endYear= ParamUtil.getInteger(renderRequest, "endYear",-1); + boolean onlyForUserOwner = (prefs.getValue("preferences--onlyForUserOwner--", "false")).compareTo("true") == 0; + renderRequest.setAttribute("onlyForUserOwner", onlyForUserOwner); + boolean showExtraContent = (prefs.getValue("preferences--showExtraContent--", "true")).compareTo("true") == 0; + renderRequest.setAttribute("showExtraContent", showExtraContent); + String classNamePrefsValues = prefs.getValue("className", StringPool.BLANK); + String classNameValue = ParamUtil.getString(renderRequest,"className", ""); + + String refreshPageEachXSeg = prefs.getValue("refreshPageEachXSeg","true"); + renderRequest.setAttribute("refreshPageEachXSeg", refreshPageEachXSeg); + boolean showAllClassName = (prefs.getValue("preferences--showAllClassName--", "true")).compareTo("true") == 0; + renderRequest.setAttribute("showAllClassName", showAllClassName); + renderRequest.setAttribute("showTypeSearcher", true); + // Obtenemos todos los classname distintos para efectuar la lista; Si estan por preferencias los editamos + List classnames = new ArrayList(); + if(!showAllClassName){ + if(classNamePrefsValues.indexOf(",")>=0){ + for (String typeUnit : classNamePrefsValues.split(",")) { + classnames.add(typeUnit); + } + }else{ + classNameValue=classNamePrefsValues; + renderRequest.setAttribute("showTypeSearcher", false); + classnames.add(classNamePrefsValues); + } + }else{ + classnames =AsynchronousProcessAuditLocalServiceUtil + .getDistinctTypes(themeDisplay.getCompanyId()); + } - Date startDate=null; - if(startDay!=-1 && startMonth!=-1 && startYear!=-1){ - Calendar startCalendar= Calendar.getInstance(); + long userId =0L; + if(onlyForUserOwner){ + userId = themeDisplay.getUserId(); + } + + renderRequest.setAttribute("classnames", classnames); + + renderRequest.setAttribute("className", classNameValue); + // Obtenemos las fechas para la búsqueda + int startDay = ParamUtil.getInteger(renderRequest, "startDay", -1); + int startMonth = ParamUtil.getInteger(renderRequest, "startMonth", + -1); + int startYear = ParamUtil + .getInteger(renderRequest, "startYear", -1); + int endDay = ParamUtil.getInteger(renderRequest, "endDay", -1); + int endMonth = ParamUtil.getInteger(renderRequest, "endMonth", -1); + int endYear = ParamUtil.getInteger(renderRequest, "endYear", -1); + + Date startDate = null; + if (startDay != -1 && startMonth != -1 && startYear != -1) { + Calendar startCalendar = Calendar.getInstance(); startCalendar.set(Calendar.YEAR, startYear); startCalendar.set(Calendar.MONTH, startMonth); startCalendar.set(Calendar.DAY_OF_MONTH, startDay); startDate = startCalendar.getTime(); } - - Date endDate=null; - if(endDay!=-1 && endMonth!=-1 && endYear!=-1){ - Calendar endCalDate= Calendar.getInstance(); + + Date endDate = null; + if (endDay != -1 && endMonth != -1 && endYear != -1) { + Calendar endCalDate = Calendar.getInstance(); endCalDate.set(Calendar.YEAR, endYear); endCalDate.set(Calendar.MONTH, endMonth); endCalDate.set(Calendar.DAY_OF_MONTH, endDay); endDate = endCalDate.getTime(); } - renderRequest.setAttribute("startDay",startDay); - renderRequest.setAttribute("startMonth",startMonth); - renderRequest.setAttribute("startYear",startYear); - renderRequest.setAttribute("endDay",endDay); - renderRequest.setAttribute("endMonth",endMonth); - renderRequest.setAttribute("endYear",endYear); - - - renderRequest.setAttribute("defaultStartYear", LiferaylmsUtil.defaultStartYear); - renderRequest.setAttribute("defaultEndYear", LiferaylmsUtil.defaultEndYear); - + renderRequest.setAttribute("startDay", startDay); + renderRequest.setAttribute("startMonth", startMonth); + renderRequest.setAttribute("startYear", startYear); + renderRequest.setAttribute("endDay", endDay); + renderRequest.setAttribute("endMonth", endMonth); + renderRequest.setAttribute("endYear", endYear); + + renderRequest.setAttribute("defaultStartYear", + LiferaylmsUtil.defaultStartYear); + renderRequest.setAttribute("defaultEndYear", + LiferaylmsUtil.defaultEndYear); + PortletURL iteratorURL = renderResponse.createRenderURL(); iteratorURL.setParameter("startDay", String.valueOf(startDay)); iteratorURL.setParameter("startMonth", String.valueOf(startMonth)); iteratorURL.setParameter("startYear", String.valueOf(startYear)); - iteratorURL.setParameter("defaultStartYear", String.valueOf(LiferaylmsUtil.defaultStartYear)); - iteratorURL.setParameter("defaultEndtYear", String.valueOf(LiferaylmsUtil.defaultEndYear)); - + iteratorURL.setParameter("defaultStartYear", + String.valueOf(LiferaylmsUtil.defaultStartYear)); + iteratorURL.setParameter("defaultEndtYear", + String.valueOf(LiferaylmsUtil.defaultEndYear)); + iteratorURL.setParameter("showExtraContent", String.valueOf(showExtraContent)); iteratorURL.setParameter("endDay", String.valueOf(endDay)); iteratorURL.setParameter("endMonth", String.valueOf(endMonth)); iteratorURL.setParameter("endYear", String.valueOf(endYear)); - - iteratorURL.setParameter("className", String.valueOf(classNameValue)); + + iteratorURL.setParameter("className", + String.valueOf(classNameValue)); + +// iteratorURL.setParameter("userId", +// String.valueOf(userId)); List asynchronousProcesses = new ArrayList(); + + SearchContainer searchContainer = new SearchContainer( + renderRequest, null, null, + SearchContainer.DEFAULT_CUR_PARAM, + SearchContainer.DEFAULT_DELTA, iteratorURL, null, + "no-results"); + - SearchContainer searchContainer = new SearchContainer(renderRequest, null, null, SearchContainer.DEFAULT_CUR_PARAM, - SearchContainer.DEFAULT_DELTA, iteratorURL, - null, "no-results"); - asynchronousProcesses = AsynchronousProcessAuditLocalServiceUtil.getByCompanyIdClassNameIdCreateDate(themeDisplay.getCompanyId(), classNameValue, startDate, endDate, searchContainer.getStart(),searchContainer.getEnd()); - int asynchronousProcessesCount = AsynchronousProcessAuditLocalServiceUtil.countByCompanyIdClassNameIdCreateDate(themeDisplay.getCompanyId(), classNameValue, startDate, endDate); + asynchronousProcesses = AsynchronousProcessAuditLocalServiceUtil + .getByCompanyIdClassNameIdCreateDate( + themeDisplay.getCompanyId(), classNameValue, userId, + startDate, endDate, searchContainer.getStart(), + searchContainer.getEnd()); + int asynchronousProcessesCount = AsynchronousProcessAuditLocalServiceUtil + .countByCompanyIdClassNameIdCreateDate( + themeDisplay.getCompanyId(), classNameValue, userId, + startDate, endDate); searchContainer.setIteratorURL(iteratorURL); searchContainer.setResults(asynchronousProcesses); searchContainer.setTotal(asynchronousProcessesCount); - + renderRequest.setAttribute("searchContainer", searchContainer); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + } catch (Exception e) { e.printStackTrace(); - } - - this.include(this.viewJSP, renderRequest, renderResponse); + } + if(ajax){ + include("/html/asynchronousprocessdashboard/search-container.jsp" , renderRequest, renderResponse); + }else{ + this.include(this.viewJSP, renderRequest, renderResponse); + } + + } + public void serveResource(ResourceRequest resourceRequest, + ResourceResponse resourceResponse) throws IOException, + PortletException { + + + String action = ParamUtil.getString(resourceRequest, "action"); + log.debug("---action: "+action); + + ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY); + + if(action.equals("search")){ + String classNameValue = ParamUtil.getString(resourceRequest,"className", ""); + List asynchronousProcesses = new ArrayList(); + // Obtenemos las fechas para la búsqueda + int startDay = ParamUtil.getInteger(resourceRequest, "startDay", -1); + int startMonth = ParamUtil.getInteger(resourceRequest, "startMonth", + -1); + int startYear = ParamUtil + .getInteger(resourceRequest, "startYear", -1); + int endDay = ParamUtil.getInteger(resourceRequest, "endDay", -1); + int endMonth = ParamUtil.getInteger(resourceRequest, "endMonth", -1); + int endYear = ParamUtil.getInteger(resourceRequest, "endYear", -1); + boolean showExtraContent = ParamUtil.getBoolean(resourceRequest, "showExtraContent", false); + Date startDate = null; + if (startDay != -1 && startMonth != -1 && startYear != -1) { + Calendar startCalendar = Calendar.getInstance(); + startCalendar.set(Calendar.YEAR, startYear); + startCalendar.set(Calendar.MONTH, startMonth); + startCalendar.set(Calendar.DAY_OF_MONTH, startDay); + startDate = startCalendar.getTime(); + } + + Date endDate = null; + if (endDay != -1 && endMonth != -1 && endYear != -1) { + Calendar endCalDate = Calendar.getInstance(); + endCalDate.set(Calendar.YEAR, endYear); + endCalDate.set(Calendar.MONTH, endMonth); + endCalDate.set(Calendar.DAY_OF_MONTH, endDay); + endDate = endCalDate.getTime(); + } + + PortletURL iteratorURL = resourceResponse.createRenderURL(); + iteratorURL.setParameter("startDay", String.valueOf(startDay)); + iteratorURL.setParameter("startMonth", String.valueOf(startMonth)); + iteratorURL.setParameter("startYear", String.valueOf(startYear)); + iteratorURL.setParameter("defaultStartYear", + String.valueOf(LiferaylmsUtil.defaultStartYear)); + iteratorURL.setParameter("defaultEndtYear", + String.valueOf(LiferaylmsUtil.defaultEndYear)); + iteratorURL.setParameter("showExtraContent", String.valueOf(showExtraContent)); + iteratorURL.setParameter("endDay", String.valueOf(endDay)); + iteratorURL.setParameter("endMonth", String.valueOf(endMonth)); + iteratorURL.setParameter("endYear", String.valueOf(endYear)); + + iteratorURL.setParameter("className", + String.valueOf(classNameValue)); + + + SearchContainer searchContainer = new SearchContainer( + resourceRequest, null, null, + SearchContainer.DEFAULT_CUR_PARAM, + SearchContainer.DEFAULT_DELTA, iteratorURL, null, + "no-results"); + long userId =0L; + boolean onlyForUserOwner = true; + + if(onlyForUserOwner){ + userId = themeDisplay.getUserId(); + } + + asynchronousProcesses = AsynchronousProcessAuditLocalServiceUtil + .getByCompanyIdClassNameIdCreateDate( + themeDisplay.getCompanyId(), classNameValue, userId, + startDate, endDate, searchContainer.getStart(), + searchContainer.getEnd()); + int asynchronousProcessesCount = AsynchronousProcessAuditLocalServiceUtil + .countByCompanyIdClassNameIdCreateDate( + themeDisplay.getCompanyId(), classNameValue, userId, + startDate, endDate); + searchContainer.setIteratorURL(iteratorURL); + searchContainer.setResults(asynchronousProcesses); + searchContainer.setTotal(asynchronousProcessesCount); - - - protected void include(String path, RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { - PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path); - if (portletRequestDispatcher == null) { + resourceRequest.setAttribute("searchContainer", searchContainer); + + log.debug("************includeeeeee!!! "); + PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher( "/html/asynchronousprocessdashboard/search-container.jsp" ); + resourceRequest.setAttribute("showExtraContent", showExtraContent); + resourceRequest.setAttribute("namespace", resourceResponse.getNamespace()); + dispatcher.include( resourceRequest, resourceResponse ); + + super.serveResource(resourceRequest, resourceResponse); - } else { - portletRequestDispatcher.include(renderRequest, renderResponse); } } - + protected void doDispatch(RenderRequest renderRequest, + RenderResponse renderResponse) throws IOException, PortletException { + log.debug("PARAM "+ParamUtil.getString(renderRequest, "ajaxAction")); + if("refresh".equals(ParamUtil.getString(renderRequest, "ajaxAction"))){ + showProcesses(renderRequest,renderResponse,true); + } + super.doDispatch(renderRequest, renderResponse); + } - + protected void include(String path, RenderRequest renderRequest, + RenderResponse renderResponse) throws IOException, PortletException { + PortletRequestDispatcher portletRequestDispatcher = getPortletContext() + .getRequestDispatcher(path); + if (portletRequestDispatcher == null) { + } else { + portletRequestDispatcher.include(renderRequest, renderResponse); + } + } - - - } diff --git a/docroot/WEB-INF/src/com/liferay/lms/portlet/inscriptioncommunity/CommunityInscription.java b/docroot/WEB-INF/src/com/liferay/lms/portlet/inscriptioncommunity/CommunityInscription.java index 9dabd3fde..1bd5a42ad 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/portlet/inscriptioncommunity/CommunityInscription.java +++ b/docroot/WEB-INF/src/com/liferay/lms/portlet/inscriptioncommunity/CommunityInscription.java @@ -1,214 +1,238 @@ package com.liferay.lms.portlet.inscriptioncommunity; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; import java.util.List; -import javax.mail.internet.InternetAddress; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; +import javax.portlet.PortletException; +import javax.portlet.PortletURL; import javax.portlet.ProcessAction; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; +import javax.servlet.http.HttpServletRequest; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.lms.course.inscriptiontype.InscriptionType; import com.liferay.lms.course.inscriptiontype.InscriptionTypeRegistry; import com.liferay.lms.model.Course; +import com.liferay.lms.model.CourseCompetence; +import com.liferay.lms.model.Schedule; +import com.liferay.lms.service.CourseCompetenceLocalServiceUtil; import com.liferay.lms.service.CourseLocalServiceUtil; -import com.liferay.mail.service.MailServiceUtil; +import com.liferay.lms.service.ScheduleLocalServiceUtil; +import com.liferay.lms.util.LmsConstant; import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.mail.MailMessage; import com.liferay.portal.kernel.servlet.SessionErrors; +import com.liferay.portal.kernel.servlet.SessionMessages; import com.liferay.portal.kernel.util.ParamUtil; -import com.liferay.portal.kernel.util.PrefsPropsUtil; -import com.liferay.portal.kernel.util.PropsKeys; -import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.StringBundler; +import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; -import com.liferay.portal.model.Group; import com.liferay.portal.model.GroupConstants; -import com.liferay.portal.model.User; -import com.liferay.portal.security.permission.ActionKeys; -import com.liferay.portal.security.permission.PermissionChecker; -import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; -import com.liferay.portal.service.GroupLocalServiceUtil; -import com.liferay.portal.service.MembershipRequestLocalServiceUtil; +import com.liferay.portal.model.MembershipRequestConstants; +import com.liferay.portal.model.Team; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.ServiceContextFactory; +import com.liferay.portal.service.TeamLocalServiceUtil; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; -import com.liferay.portlet.social.service.SocialActivityLocalServiceUtil; +import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; /** Portlet implementation class CommunityInscription */ public class CommunityInscription extends MVCPortlet { private static Log log = LogFactoryUtil.getLog(CommunityInscription.class); - - @ProcessAction(name = "member") - public void member(ActionRequest request, ActionResponse response) throws SystemException{ - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY); - Group group = null; - Course course = null; - int numberUsers = 0; - try { - group = GroupLocalServiceUtil.getGroup(themeDisplay.getScopeGroupId()); - course = CourseLocalServiceUtil.getCourseByGroupCreatedId(themeDisplay.getScopeGroupId()); - numberUsers = UserLocalServiceUtil.getGroupUsersCount(themeDisplay.getScopeGroupId()); - } catch (PortalException e) { - if(log.isDebugEnabled()){ - e.printStackTrace(); - } - - } catch (SystemException e) { - if(log.isDebugEnabled()){ - e.printStackTrace(); - } - } - - if(group.getType()!=GroupConstants.TYPE_SITE_RESTRICTED){ - if(log.isDebugEnabled()){ - log.debug("Site not restricted!"); - } - throw new SystemException("Site not restricted!"); - } - - if(course.getMaxusers()>0&&numberUsers>=course.getMaxusers()){ - if(log.isDebugEnabled()){ - log.debug("Maxusers!"); - } - throw new SystemException("Maxusers!"); - } - - + + @Override + public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { + ThemeDisplay themeDisplay =(ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); try { - long teamId = ParamUtil.getLong(request, "teamId",0); - ServiceContext serviceContext=ServiceContextFactory.getInstance(request); - MembershipRequestLocalServiceUtil.addMembershipRequest(themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), "Enroll petition", serviceContext); - SocialActivityLocalServiceUtil.addActivity(themeDisplay.getUserId(), course.getGroupId(), Course.class.getName(), course.getCourseId(), com.liferay.portlet.social.model.SocialActivityConstants.TYPE_SUBSCRIBE, "", course.getUserId()); - - if(teamId>0){ - long[] userIds = new long[1]; - userIds[0] = themeDisplay.getUserId(); - if(!UserLocalServiceUtil.hasTeamUser(teamId, themeDisplay.getUserId())){ - UserLocalServiceUtil.addTeamUsers(teamId, userIds); - } - } + Course course= CourseLocalServiceUtil.getCourseByGroupCreatedId(themeDisplay.getScopeGroupId()); - List allUsers = UserLocalServiceUtil.getGroupUsers(course.getGroupCreatedId()); + InscriptionTypeRegistry inscriptionTypeRegistry = new InscriptionTypeRegistry(); + InscriptionType inscriptionType = inscriptionTypeRegistry.getInscriptionType(course.getInscriptionType()); + renderRequest.setAttribute("inscriptionType", inscriptionType); - for(User userTmp : allUsers){ - PermissionChecker permissionChecker; - try { - permissionChecker = PermissionCheckerFactoryUtil.create(userTmp); - if(log.isDebugEnabled())log.debug(userTmp.getFullName()); - if(permissionChecker.hasPermission(course.getGroupCreatedId(),Course.class.getName(),course.getCourseId(),ActionKeys.ASSIGN_MEMBERS)){ - if(log.isDebugEnabled())log.debug(userTmp.getFullName()); - - String fromName = PrefsPropsUtil.getString(themeDisplay.getCompanyId(), - PropsKeys.ADMIN_EMAIL_FROM_NAME); - String fromAddress = PrefsPropsUtil.getString(themeDisplay.getCompanyId(), - PropsKeys.ADMIN_EMAIL_FROM_ADDRESS); + log.debug("inscriptionTypeFactory: " + inscriptionType.getTypeId() + " - " + inscriptionType.getPortletId()); + if(!Validator.isNull(inscriptionType.getPortletId())) { + StringBundler sb = new StringBundler(); + sb.append(""); + sb.append(""); + sb.append(""); + sb.append("portletSetupShowBorders"); + sb.append(""); + sb.append(""); + sb.append("false"); + sb.append(""); + sb.append(""); + sb.append(""); + renderRequest.setAttribute("inscriptionPortletName", inscriptionType.getPortletId()); + renderRequest.setAttribute("defaultPreferences", sb); + }else if(themeDisplay.isSignedIn()){ + log.debug("usuario logado"); + HttpServletRequest renderServletRequest = PortalUtil.getHttpServletRequest(renderRequest); + HttpServletRequest servletRequest = PortalUtil.getOriginalServletRequest(renderServletRequest); + + String inscriptionParam = servletRequest.getParameter("inscriptionOk"); + log.debug("inscriptionParam: " + inscriptionParam); + if(Validator.isNotNull(inscriptionParam)){ + try{ + SessionMessages.add(renderRequest, "inscription-ok"); + }catch(Exception e){ + if(log.isDebugEnabled())e.printStackTrace(); + } + } + + PortletURL unsubscribeURL = renderResponse.createActionURL(); + unsubscribeURL.setParameter("javax.portlet.action", "unsubscribe"); + renderRequest.setAttribute("unsubscribeURL", unsubscribeURL); + + //Comprobamos si estoy inscrita en el curso o en alguna convocatoria + if(UserLocalServiceUtil.hasGroupUser(course.getGroupCreatedId(), themeDisplay.getUserId())) { + //Ya estoy inscrito, mando el curso y que estoy inscrito + log.debug("usuario registrado: " + course.getCourseId() ); + renderRequest.setAttribute("registredUser", true); + renderRequest.setAttribute("course", course); + }else { + //Comprobamos si estoy inscrita en alguna de las hijas + long courseParentId = course.getCourseId(); + log.debug("courseParentId: " + courseParentId); + if(course.getParentCourseId() != LmsConstant.DEFAULT_PARENT_COURSE_ID) { + courseParentId = course.getParentCourseId(); + } + + renderRequest.setAttribute("TYPE_SITE_OPEN", GroupConstants.TYPE_SITE_OPEN); + renderRequest.setAttribute("TYPE_SITE_RESTRICTED", GroupConstants.TYPE_SITE_RESTRICTED); + renderRequest.setAttribute("STATUS_PENDING", MembershipRequestConstants.STATUS_PENDING); + renderRequest.setAttribute("STATUS_DENIED", MembershipRequestConstants.STATUS_DENIED); + + log.debug("courseParentId: " + courseParentId); + List listChildCourses = CourseLocalServiceUtil.getChildsRegistredUser(courseParentId, themeDisplay.getUserId()); + if(listChildCourses != null && listChildCourses.size() > 0) { + log.debug("estoy inscrito en una convocatoria hija: " + listChildCourses.get(0).getCourseId()); + //Estoy inscrita en alguna convocatoria de las hijas, mando qeu estoy inscrita y las convocatorias en las que estoy + renderRequest.setAttribute("registredUser", true); + renderRequest.setAttribute("listChildCourses", listChildCourses); + }else { + //Comprobamos los prerequisitos del curso padre (tanto si tiene convocatorias como si no) + List listCourseCompetences = CourseCompetenceLocalServiceUtil.findBycourseId( + course.getParentCourseId() == 0 ? course.getCourseId() : course.getParentCourseId(), true); + renderRequest.setAttribute("listCourseCompetences", listCourseCompetences); - InternetAddress from = new InternetAddress(fromAddress, fromName); - - String url = themeDisplay.getURLPortal(); - String urlcourse = themeDisplay.getURLPortal()+"/web"+course.getFriendlyURL(); - - String emailTo = userTmp.getEmailAddress(); - String nameTo = userTmp.getFullName(); - InternetAddress to = new InternetAddress(emailTo, nameTo); + PortletURL enrollURL = renderResponse.createActionURL(); + enrollURL.setParameter("javax.portlet.action", "enroll"); + renderRequest.setAttribute("enrollURL", enrollURL); - String subject = LanguageUtil.format(userTmp.getLocale(),"reply-membership-request-for-x", new String[]{course.getTitle(userTmp.getLocale())}); - String body = StringUtil.replace( - LanguageUtil.get(userTmp.getLocale(), "reply-membership-body"), - new String[] {"[$FROM_ADDRESS$]", "[$FROM_NAME$]", "[$PAGE_URL$]","[$PORTAL_URL$]","[$TO_ADDRESS$]","[$TO_NAME$]","[$COURSE_NAME$]"}, - new String[] {fromAddress, fromName, urlcourse, url, emailTo, nameTo,course.getTitle(userTmp.getLocale())}); - try{ - if(log.isDebugEnabled()){ - log.debug(from); - log.debug(to); - log.debug(subject); - log.debug(body); + //Si es una convocatoria sabemos que no estoy inscrito en ninguna más así que paso el curso, además + //no puede tener inscripción por equipos porque sólo la tienen los padre + if(course.getParentCourseId() != LmsConstant.DEFAULT_PARENT_COURSE_ID) { + log.debug("Es convocatoria hija: " + course.getCourseId()); + renderRequest.setAttribute("course", course); + }else { + //Si es un curso padre y no tengo convocatorias hijas mando el curso, si no mando las hijas + //Buscamos los cursos hijos abiertos o restringidos + + listChildCourses = CourseLocalServiceUtil.getOpenOrRestrictedChildCourses(course.getCourseId()); + + if(course.getParentCourseId() == LmsConstant.DEFAULT_PARENT_COURSE_ID && (listChildCourses == null || listChildCourses.size() == 0)) { + log.debug("Es convocatoria padre que no tiene hijos: " + course.getCourseId()); + //Mando sólo el curso hijo + renderRequest.setAttribute("course", course); + //Si es curso padre y no tiene cursos hijos puede haber inscripción por equipos + List teams = TeamLocalServiceUtil.getGroupTeams(course.getGroupCreatedId()); + List schedules = new ArrayList(); + Schedule schedule = null; + Date now = new Date(); + for(Team team : teams){ + schedule = ScheduleLocalServiceUtil.getScheduleByTeamId(team.getTeamId()); + if(schedule!=null){ + renderRequest.setAttribute("hasTeams", true); + log.debug("hasTeams"); + if(schedule.getStartDate().before(now)&&schedule.getEndDate().after(now)){ + schedules.add(schedule); + } + } + } + renderRequest.setAttribute("schedules", schedules); + log.debug("schedules: " + schedules.size()); + }else { + renderRequest.setAttribute("listChildCourses", listChildCourses); + log.debug("childCourses: " + listChildCourses.size()); + //Paso también el curso padre + renderRequest.setAttribute("course", course); + log.debug("course: " + course.getCourseId()); } - MailMessage mailm = new MailMessage(from, to, subject, body, true); - MailServiceUtil.sendEmail(mailm); } - catch(Exception ex) - { - ex.printStackTrace(); - } - } - } catch (Exception e) { - if(log.isDebugEnabled())e.printStackTrace(); - if(log.isErrorEnabled())log.error(e.getMessage()); } } - } catch (PortalException e) { - if(log.isDebugEnabled()){ - e.printStackTrace(); - } - - }catch (SystemException e) { - if(log.isDebugEnabled()){ - e.printStackTrace(); - } + super.doView(renderRequest, renderResponse); + } catch (Exception e) { + e.printStackTrace(); + renderRequest.setAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY, Boolean.FALSE); } } - - @ProcessAction(name = "inscribir") - public void inscribir(ActionRequest request, ActionResponse response) throws Exception{ - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY); + @ProcessAction(name = "enroll") + public void enroll(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException{ + ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY); if (!themeDisplay.isSignedIn()) {return;} - - long teamId = ParamUtil.getLong(request, "teamId",0); - long groupId = themeDisplay.getScopeGroupId(); - - Course course = CourseLocalServiceUtil.getCourseByGroupCreatedId(groupId); - - log.debug("COURSE GROUP ID "+course.getGroupCreatedId()); - log.debug("THEME DISPLAY GROUP "+groupId); - long userId = themeDisplay.getUserId(); - - ServiceContext serviceContext=ServiceContextFactory.getInstance(request); - - InscriptionType inscriptionType = new InscriptionTypeRegistry().getInscriptionType(course.getInscriptionType()); - - String result = inscriptionType.enrollUser(course.getCourseId(), userId, teamId, serviceContext); - - if(!result.equalsIgnoreCase("ok")){ - if(result.equalsIgnoreCase("error-complete-course")){ - SessionErrors.add(request, "inscription-error-max-users"); - }else if(result.equalsIgnoreCase("error-private-course")){ - SessionErrors.add(request, "inscription-error-syte-restricted"); - }else if(result.equalsIgnoreCase("error-user-suscribed")){ - SessionErrors.add(request, "inscription-error-already-enrolled"); - }else{ - SessionErrors.add(request, "inscription-error"); - } - } - } + + long courseId = ParamUtil.getLong(actionRequest, "courseId"); + long teamId = ParamUtil.getLong(actionRequest, "teamId"); + + log.debug("courseId: " + courseId); + log.debug("teamId: " + teamId); + + Course course = CourseLocalServiceUtil.getCourse(courseId); + + ServiceContext serviceContext = ServiceContextFactory.getInstance(Course.class.getName(), actionRequest); + try { + InscriptionTypeRegistry inscriptionTypeRegistry = new InscriptionTypeRegistry(); + + InscriptionType inscriptionType = inscriptionTypeRegistry.getInscriptionType(course.getInscriptionType()); + + inscriptionType.enrollUser(courseId, themeDisplay.getUserId(), teamId, serviceContext); + if(course.getGroupCreatedId() != themeDisplay.getScopeGroupId()) { + //Redirijo + String url = themeDisplay.getPortalURL() + "/" + themeDisplay.getLocale().getLanguage() + "/web" + course.getFriendlyURL()+"?inscriptionOk=true"; + log.debug("Redirect to: "+url); + actionResponse.sendRedirect(url); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + SessionErrors.add(actionRequest, "error-enroll-user", e.getMessage()); + } + } - public void desinscribir(ActionRequest request, ActionResponse response) throws Exception{ - - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY); + @ProcessAction(name="unsubscribe") + public void unsubscribe(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException{ + ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY); if (!themeDisplay.isSignedIn()) {return;} - - long[] groupId = new long[1]; - groupId[0] = themeDisplay.getScopeGroupId(); - long userId = themeDisplay.getUserId(); - Course course = CourseLocalServiceUtil.getCourseByGroupCreatedId(groupId[0]); - - InscriptionType inscriptionType = new InscriptionTypeRegistry().getInscriptionType(course.getInscriptionType()); + long courseId = ParamUtil.getLong(actionRequest, "courseId"); + log.debug("InscriptionPortlet::unsubscribe::courseId::" + courseId); - - boolean result = inscriptionType.unsubscribeUser(course, userId); - - if(!result){ - SessionErrors.add(request, "inscription-error-already-disenrolled"); + Course course = CourseLocalServiceUtil.getCourse(courseId); + + InscriptionTypeRegistry inscriptionTypeRegistry = new InscriptionTypeRegistry(); + InscriptionType inscriptionType = inscriptionTypeRegistry.getInscriptionType(course.getInscriptionType()); + + boolean result = inscriptionType.unsubscribeUser(course, themeDisplay.getUserId()); + + log.debug("InscriptionPortlet::unsubscribe::result::" + result); + if(result) { + SessionMessages.add(actionRequest, "unsusbscribe"); + }else{ + SessionErrors.add(actionRequest, "unsusbscribe"); } } diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/http/CourseServiceSoap.java b/docroot/WEB-INF/src/com/liferay/lms/service/http/CourseServiceSoap.java index 55eedd0fa..8ae9850d6 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/http/CourseServiceSoap.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/http/CourseServiceSoap.java @@ -100,6 +100,29 @@ public static com.liferay.lms.model.CourseSoap createCourse(long groupId, } } + public static com.liferay.lms.model.CourseSoap createCourse(long groupId, + java.lang.String title, java.lang.String description, + boolean published, java.lang.String summary, int evaluationmethod, + int calificationType, int template, int registermethod, int maxusers, + java.util.Date startregistrationdate, + java.util.Date endregistrationdate, java.util.Date startExecutionDate, + java.util.Date endExecutionDate) throws RemoteException { + try { + com.liferay.lms.model.Course returnValue = CourseServiceUtil.createCourse(groupId, + title, description, published, summary, evaluationmethod, + calificationType, template, registermethod, maxusers, + startregistrationdate, endregistrationdate, + startExecutionDate, endExecutionDate); + + return com.liferay.lms.model.CourseSoap.toSoapModel(returnValue); + } + catch (Exception e) { + _log.error(e, e); + + throw new RemoteException(e.getMessage()); + } + } + public static com.liferay.lms.model.CourseSoap createCourse( java.lang.String title, java.lang.String description, boolean published, java.lang.String summary, int evaluationmethod, diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/AsynchronousProcessAuditLocalServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/AsynchronousProcessAuditLocalServiceImpl.java index a457b59ec..7543f475d 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/AsynchronousProcessAuditLocalServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/AsynchronousProcessAuditLocalServiceImpl.java @@ -52,20 +52,20 @@ public List getDistinctTypes(long companyId){ } - public List getByCompanyIdClassNameIdCreateDate(long companyId, String type, Date startDate, Date endDate, int start, int end){ + public List getByCompanyIdClassNameIdCreateDate(long companyId, String type,long userId, Date startDate, Date endDate, int start, int end){ List asynchronousProcessAudits = new ArrayList(); try{ - asynchronousProcessAudits = AsynchronousProcessAuditFinderUtil.getByCompanyIdClassNameIdCreateDate(companyId, type, startDate, endDate,start,end); + asynchronousProcessAudits = AsynchronousProcessAuditFinderUtil.getByCompanyIdClassNameIdCreateDate(companyId, type, userId, startDate, endDate,start,end); }catch(Exception e){ e.printStackTrace(); } return asynchronousProcessAudits; } - public int countByCompanyIdClassNameIdCreateDate(long companyId, String type, Date startDate, Date endDate){ + public int countByCompanyIdClassNameIdCreateDate(long companyId, String type, long userId, Date startDate, Date endDate){ int asynchronousProcessAudits = 0; try{ - asynchronousProcessAudits = AsynchronousProcessAuditFinderUtil.countByCompanyIdClassNameIdCreateDate(companyId, type, startDate, endDate); + asynchronousProcessAudits = AsynchronousProcessAuditFinderUtil.countByCompanyIdClassNameIdCreateDate(companyId, type, userId, startDate, endDate); }catch(Exception e){ e.printStackTrace(); } @@ -93,6 +93,26 @@ public AsynchronousProcessAudit addAsynchronousProcessAudit(long companyId, long return asynchronousProcessAudit; } + public AsynchronousProcessAudit addAsynchronousProcessAudit(long companyId, long userId, String classNameValue, long classNameId, long classPK, String type){ + AsynchronousProcessAudit asynchronousProcessAudit = null; + try{ + asynchronousProcessAudit = asynchronousProcessAuditPersistence.create(counterLocalService.increment(AsynchronousProcessAudit.class.getName())); + asynchronousProcessAudit.setCompanyId(companyId); + asynchronousProcessAudit.setType(type); + asynchronousProcessAudit.setUserId(userId); + asynchronousProcessAudit.setClassName(classNameValue); + asynchronousProcessAudit.setCreateDate(new Date()); + asynchronousProcessAudit.setStatus(LmsConstant.STATUS_NOT_STARTED); + + asynchronousProcessAudit =asynchronousProcessAuditPersistence.update(asynchronousProcessAudit, true); + + + + }catch(SystemException e){ + e.printStackTrace(); + } + return asynchronousProcessAudit; + } public AsynchronousProcessAudit updateProcessStatus(AsynchronousProcessAudit asynchronousProcessAudit, Date endDate, int status, String statusMessage) { try{ diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseLocalServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseLocalServiceImpl.java index f5c8b7b24..b9101736f 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseLocalServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseLocalServiceImpl.java @@ -150,15 +150,15 @@ public class CourseLocalServiceImpl extends CourseLocalServiceBaseImpl { Log log = LogFactoryUtil.getLog(CourseLocalServiceImpl.class); - public java.util.List getCoursesOfGroup(long groupId) throws SystemException{ + public List getCoursesOfGroup(long groupId) throws SystemException{ return coursePersistence.findByGroupId(groupId); } - public java.util.List getOpenCoursesOfGroup(long groupId) throws SystemException{ + public List getOpenCoursesOfGroup(long groupId) throws SystemException{ return coursePersistence.findByGroupId(groupId); } - public java.util.List getCourses(long companyId) throws SystemException{ + public List getCourses(long companyId) throws SystemException{ return coursePersistence.findByCompanyId(companyId); } @@ -171,7 +171,7 @@ public Course fetchByGroupCreatedId(long groupId) throws SystemException{ } public Course addCourse (String title, String description,String summary,String friendlyURL, Locale locale, - java.util.Date createDate,java.util.Date startDate,java.util.Date endDate,long layoutSetPrototypeId,int typesite,ServiceContext serviceContext, long calificationType, int maxUsers,boolean isFromClone) + Date createDate,Date startDate,Date endDate,long layoutSetPrototypeId,int typesite,ServiceContext serviceContext, long calificationType, int maxUsers,boolean isFromClone) throws SystemException, PortalException { return addCourse(title, description, summary, friendlyURL, locale, createDate, startDate, endDate, layoutSetPrototypeId, typesite, 0, calificationType, maxUsers, serviceContext,isFromClone); } @@ -234,8 +234,6 @@ public List getPublicCoursesByCompanyId(Long companyId){ return null; } - - public List getPublicCoursesByCompanyId(Long companyId, int start, int end){ @@ -269,7 +267,7 @@ public List getPublicCoursesByCompanyId(Long companyId, int start, int e public Course addCourse (String title, String description,String summary,String friendlyURL, Locale locale, - java.util.Date createDate,java.util.Date startDate,java.util.Date endDate,long layoutSetPrototypeId,int typesite, long CourseEvalId, long calificationType, int maxUsers,ServiceContext serviceContext,boolean isfromClone) + Date createDate,Date startDate,Date endDate,long layoutSetPrototypeId,int typesite, long CourseEvalId, long calificationType, int maxUsers,ServiceContext serviceContext,boolean isfromClone) throws SystemException, PortalException { Course course = addCourse (title, description,summary,friendlyURL, locale, @@ -466,7 +464,7 @@ public Course addCourse (Map titleMap, String description,String @Indexable(type=IndexableType.REINDEX) public Course addCourse (String title, String description,String summary,String friendlyURL, Locale locale, - java.util.Date createDate,java.util.Date startDate,java.util.Date endDate, + Date createDate,Date startDate,Date endDate, ServiceContext serviceContext, long calificationType) throws SystemException, PortalException { @@ -480,7 +478,7 @@ public Course addCourse (String title, String description,String summary,String @Indexable(type=IndexableType.REINDEX) public Course addCourse (String title, String description,String friendlyURL, Locale locale, - java.util.Date createDate,java.util.Date startDate,java.util.Date endDate, + Date createDate,Date startDate,Date endDate, ServiceContext serviceContext, long calificationType) throws SystemException, PortalException { @@ -621,7 +619,7 @@ public Course modCourse (Course course,String summary, long courseTypeId, throws SystemException, PortalException { - int numberUsers = UserLocalServiceUtil.getGroupUsersCount(course.getGroupCreatedId()); + int numberUsers = countStudentsFromCourse(course.getCourseId(), course.getCompanyId(), null, null, null, null, WorkflowConstants.STATUS_APPROVED, null, true); if(course.getMaxusers()>0&&numberUsers>course.getMaxusers()){ if(log.isDebugEnabled()){ log.debug("Throws exception max users violated"); @@ -721,18 +719,19 @@ public Course closeCourse(long courseId) throws SystemException, @Indexable(type=IndexableType.REINDEX) public Course openCourse(long courseId) throws SystemException, PortalException { - - Course course=CourseLocalServiceUtil.getCourse(courseId); + + Course course=getCourse(courseId); + log.debug("::OPEN COURSE "+course.getClosed()); if(course.getClosed()){ course.setClosed(false); course.setModifiedDate(new Date()); - Group courseGroup=GroupLocalServiceUtil.getGroup(course.getGroupCreatedId()); + Group courseGroup=groupLocalService.getGroup(course.getGroupCreatedId()); courseGroup.setActive(true); - GroupLocalServiceUtil.updateGroup(courseGroup); + groupLocalService.updateGroup(courseGroup); coursePersistence.update(course, true); - AssetEntry courseAsset=AssetEntryLocalServiceUtil.getEntry(Course.class.getName(), course.getCourseId()); + AssetEntry courseAsset=assetEntryLocalService.getEntry(Course.class.getName(), course.getCourseId()); courseAsset.setVisible(true); - AssetEntryLocalServiceUtil.updateAssetEntry(courseAsset); + assetEntryLocalService.updateAssetEntry(courseAsset); CourseEval courseEval=new CourseEvalRegistry().getCourseEval(course.getCourseEvalId()); if(Validator.isNotNull(courseEval)) { @@ -1349,7 +1348,7 @@ public String addStudentToCourseByUserId(long courseId, long userId, long teamId } } - if((startDate.before(now) && endDate.after(now))){ + if((!course.isClosed() && startDate.before(now) && endDate.after(now))){ //3. Control de competencias List courseCompetences = CourseCompetenceLocalServiceUtil.findBycourseId(course.getCourseId(), true); //Busco si al usuario le falta alguna competencia que es necesaria para la inscripcion al curso @@ -1364,7 +1363,7 @@ public String addStudentToCourseByUserId(long courseId, long userId, long teamId } if(enoughCompetences){ // 4. El máximo de inscripciones del curso no ha sido superado - if(course.getMaxusers()<=0 || UserLocalServiceUtil.getGroupUsersCount(course.getGroupCreatedId()) < course.getMaxusers()){ + if(course.getMaxusers()<=0 || countStudentsFromCourse(courseId, course.getCompanyId(), null, null, null, null, WorkflowConstants.STATUS_APPROVED, null, true) < course.getMaxusers()){ if(group.getType()==GroupConstants.TYPE_SITE_OPEN){ Role sitemember=RoleLocalServiceUtil.getRole(course.getCompanyId(), RoleConstants.SITE_MEMBER) ; @@ -1445,7 +1444,7 @@ public boolean validateAddUserToCourse(long groupId, long userId, long teamId) t boolean enoughCompetences = true; CourseCompetence courseCompetence = null; if(userId > 0){ - //1. Si no está ya inscrito + //1. Si no está ya inscrito if(!GroupLocalServiceUtil.hasUserGroup(userId,course.getGroupCreatedId())){ Group group = GroupLocalServiceUtil.getGroup(course.getGroupCreatedId()); @@ -1948,7 +1947,6 @@ public List getFinishedCoursesOfUser(long userId, int start, i } } } - } } catch (PortalException | SystemException e) { e.printStackTrace(); @@ -1961,4 +1959,8 @@ public List getFinishedCoursesOfUser(long userId, int start, i return courses; } + public List getChildsRegistredUser(long parentCourseId, long userId){ + return courseFinder.findChildRegistredUser(parentCourseId, userId); + } + } diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseResultLocalServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseResultLocalServiceImpl.java index 37754440a..b20148d2e 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseResultLocalServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseResultLocalServiceImpl.java @@ -38,8 +38,6 @@ import com.liferay.lms.model.UserCompetence; import com.liferay.lms.service.ClpSerializer; import com.liferay.lms.service.CourseLocalServiceUtil; -import com.liferay.lms.service.CourseResultLocalServiceUtil; -import com.liferay.lms.service.CourseResultServiceUtil; import com.liferay.lms.service.base.CourseResultLocalServiceBaseImpl; import com.liferay.lms.service.persistence.CourseResultFinderUtil; import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; @@ -499,17 +497,19 @@ public void update(CourseResult cresult) throws SystemException{ } } - - //Actualizamos los diplomas externos (si los hay) - CourseDiplomaRegistry cdr=new CourseDiplomaRegistry(); - if(cdr!=null){ - CourseDiploma courseDiploma = cdr.getCourseDiploma(); - if(courseDiploma!=null){ - courseDiploma.updateUserDiploma(cresult.getCrId()); - } - } } courseResultPersistence.update(cresult, false); + + //Actualizamos los diplomas externos (si los hay) + CourseDiplomaRegistry cdr=new CourseDiplomaRegistry(); + if(cdr!=null){ + CourseDiploma courseDiploma = cdr.getCourseDiploma(); + if(courseDiploma!=null){ + courseDiploma.updateUserDiploma(cresult.getCrId()); + } + } + + } public void update(ModuleResult mresult) throws PortalException, SystemException{ @@ -591,4 +591,8 @@ public List getCourseResultByCourseId(long courseId, int start, in return null; } } + + public long countFinishedOnlyStudents(long courseId, long companyId, long courseGropupCreatedId, List _students, long teamId){ + return CourseResultFinderUtil.countFinishedOnlyStudents(courseId, companyId, courseGropupCreatedId, _students, teamId); + } } diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseServiceImpl.java index 91cbbc456..bade2bf96 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/CourseServiceImpl.java @@ -96,6 +96,13 @@ public java.util.List getCoursesOfGroup(long groupId) throws SystemExcep } @JSONWebService public Course createCourse(long groupId,String title, String description,boolean published,String summary,int evaluationmethod,int calificationType,int template,int registermethod,int maxusers, Date startregistrationdate,Date endregistrationdate) throws PortalException, SystemException + { + return createCourse(groupId, title, description, published, summary, evaluationmethod, calificationType, template, registermethod, maxusers, startregistrationdate, endregistrationdate,null,null); + } + + + @JSONWebService + public Course createCourse(long groupId,String title, String description,boolean published,String summary,int evaluationmethod,int calificationType,int template,int registermethod,int maxusers, Date startregistrationdate,Date endregistrationdate, Date startExecutionDate, Date endExecutionDate) throws PortalException, SystemException { User user=getUser(); @@ -103,15 +110,11 @@ public Course createCourse(long groupId,String title, String description,boolean ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext(); serviceContext.setUserId(user.getUserId()); serviceContext.setScopeGroupId(groupId); - String groupName = GroupConstants.GUEST; - long companyId = PortalUtil.getDefaultCompanyId(); if( getPermissionChecker().hasPermission(groupId, "com.liferay.lms.coursemodel",groupId,"ADD_COURSE")) { - Course course = com.liferay.lms.service.CourseLocalServiceUtil.addCourse( - title, description, summary, StringPool.BLANK, - user.getLocale(), ahora, startregistrationdate, endregistrationdate,template,registermethod,evaluationmethod, - calificationType,maxusers,serviceContext,false); + Course course = CourseLocalServiceUtil.addCourse(title, description, summary, StringPool.BLANK, user.getLocale(), ahora, startregistrationdate, endregistrationdate, startExecutionDate, endExecutionDate, template, registermethod, evaluationmethod, calificationType, maxusers, serviceContext, false); + com.liferay.lms.service.CourseLocalServiceUtil.setVisible(course.getCourseId(), published); return course; } @@ -120,6 +123,8 @@ public Course createCourse(long groupId,String title, String description,boolean return null; } } + + @JSONWebService public Course createCourse(String title, String description,boolean published,String summary,int evaluationmethod,int calificationType,int template,int registermethod,int maxusers, Date startregistrationdate,Date endregistrationdate) throws PortalException, SystemException { diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityLocalServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityLocalServiceImpl.java index b59692deb..51eec6669 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityLocalServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityLocalServiceImpl.java @@ -182,6 +182,71 @@ public LearningActivity addLearningActivity(LearningActivity learningActivity,Se return retorno; } + + @Override + public LearningActivity updateLearningActivity(LearningActivity updateActivity, LearningActivity learningActivity,ServiceContext serviceContext) throws SystemException, PortalException { + + updateActivity.setTitle(learningActivity.getTitle()); + updateActivity.setDescription(learningActivity.getDescription()); + updateActivity.setStartdate(learningActivity.getStartdate()); + updateActivity.setEnddate(learningActivity.getEnddate()); + updateActivity.setTypeId(learningActivity.getTypeId()); + updateActivity.setTries(learningActivity.getTries()); + updateActivity.setPasspuntuation(learningActivity.getPasspuntuation()); + updateActivity.setExtracontent(learningActivity.getExtracontent()); + updateActivity.setFeedbackCorrect(learningActivity.getFeedbackCorrect()); + updateActivity.setFeedbackNoCorrect(learningActivity.getFeedbackNoCorrect()); + updateActivity.setModifiedDate(new Date(System.currentTimeMillis())); + updateActivity.setStatus(WorkflowConstants.STATUS_APPROVED); + + assetEntryLocalService.updateEntry( + serviceContext.getUserId(), updateActivity.getGroupId(), LearningActivity.class.getName(), + updateActivity.getActId(), updateActivity.getUuid(),updateActivity.getTypeId(), serviceContext.getAssetCategoryIds(), + serviceContext.getAssetTagNames(), true, null, null, + new java.util.Date(System.currentTimeMillis()), null, + ContentTypes.TEXT_HTML, + updateActivity.getTitle().length()<255 ? updateActivity.getTitle():updateActivity.getTitle(Locale.getDefault()), + null, updateActivity.getDescription(serviceContext.getLocale()),null, null, 0, 0, + null, false); + + updateActivity.setPrecedence(learningActivity.getPrecedence()); + updateActivity.setPriority(learningActivity.getPriority()); + updateActivity.setWeightinmodule(learningActivity.getWeightinmodule()); + learningActivityPersistence.update(updateActivity, true); + + boolean isNotificationActivated = PrefsPropsUtil.getBoolean(updateActivity.getCompanyId(), "lms.notifications.active"); + if(isNotificationActivated && learningActivity.getTypeId()!=8){ + List listaUsuarios = userService.getGroupUsers(updateActivity.getGroupId()); + if(!listaUsuarios.isEmpty()){ + Iterator it = listaUsuarios.iterator(); + while(it.hasNext()){ + User u = it.next(); + try { + + if(u.isActive() + && !(PermissionCheckerFactoryUtil.create(u)).hasPermission(updateActivity.getGroupId(), "com.liferay.lms.model", updateActivity.getGroupId(), "VIEW_RESULTS") + && !updateActivity.isInactive() + && !updateActivity.isExpired() + && !moduleLocalService.isLocked(updateActivity.getModuleId(),u.getUserId()) + && !courseLocalService.getCourseByGroupCreatedId(updateActivity.getGroupId()).isInactive() + && !courseLocalService.getCourseByGroupCreatedId(updateActivity.getGroupId()).isExpired() + && !courseLocalService.getCourseByGroupCreatedId(updateActivity.getGroupId()).isClosed()){ + String courseTitle = courseLocalService.getCourseByGroupCreatedId(updateActivity.getGroupId()).getTitle(u.getLocale()); + String subject = LanguageUtil.format(u.getLocale(),"notif.modification.new.title", null); + String body =LanguageUtil.format(u.getLocale(),"notif.modification.new.body", new String[]{updateActivity.getTitle(u.getLocale()),courseTitle}); + sendNotification(subject, body, "", "announcements.type.general", 1,serviceContext, updateActivity.getStartdate(), updateActivity.getEnddate(),u.getUserId()); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + + return updateActivity; + } + public LearningActivity addLearningActivity (String title, String description, java.util.Date createDate,java.util.Date startDate,java.util.Date endDate, int typeId,long tries,int passpuntuation,long moduleId, String extracontent, @@ -212,6 +277,7 @@ public LearningActivity addLearningActivity (String title, String description, larn.setPriority(larn.getActId()); larn.setFeedbackCorrect(feedbackCorrect); larn.setFeedbackNoCorrect(feedbackNoCorrect); + larn.setExpandoBridgeAttributes(serviceContext); larn = LmsLocaleUtil.checkDefaultLocale(LearningActivity.class, larn, "title"); larn = LmsLocaleUtil.checkDefaultLocale(LearningActivity.class, larn, "description"); @@ -384,7 +450,7 @@ public LearningActivity addLearningActivity(long userId, long groupId, int statu return learningActivity; } - public LearningActivity modLearningActivity (long actId,String title, String description, java.util.Date createDate,java.util.Date startDate,java.util.Date endDate, int typeId,long tries,int passpuntuation,long moduleId, + public LearningActivity modLearningActivity (long actId,String title, String description, Date createDate,Date startDate,Date endDate, int typeId,long tries,int passpuntuation,long moduleId, String extracontent, String feedbackCorrect, String feedbackNoCorrect,ServiceContext serviceContext) throws SystemException, PortalException { @@ -409,6 +475,8 @@ public LearningActivity modLearningActivity (long actId,String title, String des larn.setExtracontent(extracontent); larn.setFeedbackCorrect(feedbackCorrect); larn.setFeedbackNoCorrect(feedbackNoCorrect); + larn.setExpandoBridgeAttributes(serviceContext); + larn = LmsLocaleUtil.checkDefaultLocale(LearningActivity.class, larn, "title"); larn = LmsLocaleUtil.checkDefaultLocale(LearningActivity.class, larn, "description"); learningActivityPersistence.update(larn, true); diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityResultLocalServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityResultLocalServiceImpl.java index f29dd6590..64ab46fe7 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityResultLocalServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/LearningActivityResultLocalServiceImpl.java @@ -14,24 +14,10 @@ package com.liferay.lms.service.impl; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLDecoder; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.List; import java.util.Locale; -import java.util.Map; - -import org.xml.sax.InputSource; import com.liferay.lms.NoSuchLearningActivityResultException; import com.liferay.lms.auditing.AuditConstants; @@ -49,7 +35,6 @@ import com.liferay.lms.service.LearningActivityLocalServiceUtil; import com.liferay.lms.service.LearningActivityResultLocalServiceUtil; import com.liferay.lms.service.LearningActivityTryLocalServiceUtil; -import com.liferay.lms.service.ModuleLocalServiceUtil; import com.liferay.lms.service.ModuleResultLocalServiceUtil; import com.liferay.lms.service.base.LearningActivityResultLocalServiceBaseImpl; import com.liferay.lms.service.persistence.LearningActivityResultFinderUtil; @@ -60,25 +45,14 @@ import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil; import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil; import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil; -import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.json.JSONArray; -import com.liferay.portal.kernel.json.JSONFactoryUtil; -import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.xml.Document; -import com.liferay.portal.kernel.xml.DocumentException; -import com.liferay.portal.kernel.xml.Element; -import com.liferay.portal.kernel.xml.SAXReaderUtil; import com.liferay.portal.model.User; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.ServiceContextThreadLocal; -import com.liferay.portlet.asset.model.AssetEntry; -import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; public class LearningActivityResultLocalServiceImpl extends LearningActivityResultLocalServiceBaseImpl { @@ -772,7 +746,9 @@ public LearningActivityResult deleteLearningActivityResult(LearningActivityResul } return lar; - } catch (NoSuchLearningActivityResultException e) { + } catch (NullPointerException e){ + e.printStackTrace(); + }catch (NoSuchLearningActivityResultException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (PortalException e) { diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleLocalServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleLocalServiceImpl.java index 8ac7f71df..ff57144c0 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleLocalServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleLocalServiceImpl.java @@ -289,6 +289,9 @@ public Module addmodule (Module validmodule, ServiceContext serviceContext) thro log.debug(":::::::::::::::addmodule::::::::::::::::::::"); Module fileobj = modulePersistence.create(CounterLocalServiceUtil.increment(Module.class.getName())); + if(Validator.isNotNull(validmodule.getUuid())){ + fileobj.setUuid(validmodule.getUuid()); + } fileobj.setCompanyId(validmodule.getCompanyId()); fileobj.setGroupId(validmodule.getGroupId()); fileobj.setUserId(validmodule.getUserId()); @@ -351,6 +354,35 @@ public Module addmodule (Module validmodule, ServiceContext serviceContext) thro return module; } + @Indexable(type=IndexableType.REINDEX) + public Module updateModule (Module fileobj, Module validmodule) throws SystemException, PortalException { + log.debug(":::::::::::::::addmodule::::::::::::::::::::"); + + fileobj.setModifiedDate(new java.util.Date(System.currentTimeMillis())); + fileobj.setStartDate(validmodule.getStartDate()); + fileobj.setEndDate(validmodule.getEndDate()); + fileobj.setTitle(validmodule.getTitle()); + fileobj.setDescription(validmodule.getDescription()); + fileobj.setOrdern(fileobj.getModuleId()); + fileobj.setIcon(validmodule.getIcon()); + fileobj.setPrecedence(validmodule.getPrecedence()); + + fileobj = LmsLocaleUtil.checkDefaultLocale(Module.class, fileobj, "title"); + fileobj = LmsLocaleUtil.checkDefaultLocale(Module.class, fileobj, "description"); + + Module module = modulePersistence.update(fileobj, false); + + //Index + Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(Module.class); + indexer.reindex(module); + + //auditing + AuditingLogFactory.audit(module.getCompanyId(), module.getGroupId(), Module.class.getName(), + validmodule.getModuleId(), module.getUserId(), AuditConstants.UPDATE, null); + + return module; + } + @Indexable(type=IndexableType.REINDEX) public Module addModule(Long companyId, Long groupId, Long userId, String title, String description, diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleResultLocalServiceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleResultLocalServiceImpl.java index 2a32770d8..044ce5172 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleResultLocalServiceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/impl/ModuleResultLocalServiceImpl.java @@ -383,7 +383,7 @@ public void update(LearningActivityResult lactr) moduleResult= getAndCreateIfNotExists( userId, moduleId,lactr.getStartDate()); log.debug("****Modulo "+learningActivity.getModuleId() ); - log.debug("****REsult End Date "+lactr.getEndDate()); + log.debug("****Result End Date "+lactr.getEndDate()); if (learningActivity.getModuleId() > 0 && lactr.getEndDate()!=null) { log.debug("****Recalculamos Modulo"); @@ -632,9 +632,11 @@ private void calculateModuleResult(ModuleResult moduleResult) throws PortalExcep }else if(learnActList.size()>0 && !moduleResult.getPassed()){ result= 100; passedDate = new Date(); + }else if(learnActList.size()>0){ + //Se añade para el recálculo de las antiguas, que ya están aprobadas pero con un 0 + result = 100; } - if(result>0) - { + if(result>0){ //Vamos a ver si tiene un sistema de evaluaci?e m?o CourseEvalRegistry cer=new CourseEvalRegistry(); Course course=courseLocalService.fetchByGroupCreatedId(module.getGroupId()); diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditFinderImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditFinderImpl.java index 10f74c7ee..ec4d67454 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditFinderImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditFinderImpl.java @@ -73,14 +73,25 @@ public List getDistinctTypes(long companyId){ } - public List getByCompanyIdClassNameIdCreateDate(long companyId, String type, Date startDate, Date endDate, int start, int end){ + public List getByCompanyIdClassNameIdCreateDate(long companyId, String type,long userId, Date startDate, Date endDate, int start, int end){ Session session = null; List asynchronousProcessAudits = new ArrayList(); try{ session = openSession(); String sql = CustomSQLUtil.get(GET_BY_COMPANY_CLASSNAME_CREATE_DATE); + //Logica para incluir select multiples en la consulta de procesos asincronos if(Validator.isNull(type)){ - sql = sql.replace("AND asy.type_ = ?", ""); + sql = sql.replace("AND asy.type_ IN (?)", ""); + }else{ + if(type.indexOf(",")>=0){ + String bffcopy=""; + for (String s : type.split(",")) { bffcopy = bffcopy + ",?"; } + String sqlReplace = "AND asy.type_ IN ("+bffcopy.replaceFirst(",","")+")"; + sql = sql.replace("AND asy.type_ IN (?)", sqlReplace); + } + } + if(Validator.equals(userId, 0L)){ + sql = sql.replace("AND asy.userId = ?", ""); } if(start < 0 && end < 0){ @@ -107,6 +118,8 @@ public List getByCompanyIdClassNameIdCreateDate(long c log.debug("SQL "+sql); + + SQLQuery q = session.createSQLQuery(sql); q.addEntity("Lms_AsynchronousProcessAudit", AsynchronousProcessAuditImpl.class); if(log.isDebugEnabled()){ @@ -114,6 +127,7 @@ public List getByCompanyIdClassNameIdCreateDate(long c if(Validator.isNotNull(type)){ log.debug("--TypeId: "+type); } + log.debug("--userId "+userId); log.debug("--Start Date: "+startDate); log.debug("--EndDate: "+endDate); } @@ -121,11 +135,22 @@ public List getByCompanyIdClassNameIdCreateDate(long c qPos.add(companyId); if(Validator.isNotNull(type)){ - qPos.add(type); + if(type.indexOf(",")>=0){ + String[] split = type.split(","); + for (String string : split) { + qPos.add(string); + } + } + else{ + qPos.add(type); + } + } + if(!Validator.equals(userId, 0L)){ + qPos.add(userId); } - asynchronousProcessAudits = (List)q.list(); + asynchronousProcessAudits = (List)q.list(); } catch (Exception e) { e.printStackTrace(); @@ -138,14 +163,24 @@ public List getByCompanyIdClassNameIdCreateDate(long c - public int countByCompanyIdClassNameIdCreateDate(long companyId, String type, Date startDate, Date endDate){ + public int countByCompanyIdClassNameIdCreateDate(long companyId, String type,long userId, Date startDate, Date endDate){ Session session = null; int asynchronousProcessAudits = 0; try{ session = openSession(); String sql = CustomSQLUtil.get(COUNT_BY_COMPANY_CLASSNAME_CREATE_DATE); if(Validator.isNull(type)){ - sql = sql.replace("AND asy.type_ = ?", ""); + sql = sql.replace("AND asy.type_ IN (?)", ""); + }else{ + if(type.indexOf(",")>=0){ + String bffcopy=""; + for (String s : type.split(",")) { bffcopy = bffcopy + ",?"; } + String sqlReplace = "("+bffcopy.replaceFirst(",","")+")"; + sql = sql.replace("(?)", sqlReplace); + } + } + if(Validator.equals(userId, 0L)){ + sql = sql.replace("AND asy.userId = ?", ""); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); if(Validator.isNotNull(startDate)){ @@ -177,7 +212,18 @@ public int countByCompanyIdClassNameIdCreateDate(long companyId, String type, Da qPos.add(companyId); if(Validator.isNotNull(type)){ - qPos.add(type); + if(type.indexOf(",")>=0){ + String[] split = type.split(","); + for (String string : split) { + qPos.add(string); + } + } + else{ + qPos.add(type); + } + } + if(!Validator.equals(userId, 0L)){ + qPos.add(userId); } Iterator itr = q.iterate(); diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditPersistenceImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditPersistenceImpl.java index 8390e4546..ebe523707 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditPersistenceImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/persistence/AsynchronousProcessAuditPersistenceImpl.java @@ -322,6 +322,7 @@ protected AsynchronousProcessAudit toUnwrappedModel( asynchronousProcessAuditImpl.setEndDate(asynchronousProcessAudit.getEndDate()); asynchronousProcessAuditImpl.setStatus(asynchronousProcessAudit.getStatus()); asynchronousProcessAuditImpl.setStatusMessage(asynchronousProcessAudit.getStatusMessage()); + asynchronousProcessAuditImpl.setExtraContent(asynchronousProcessAudit.getExtraContent()); return asynchronousProcessAuditImpl; } diff --git a/docroot/WEB-INF/src/com/liferay/lms/service/persistence/CourseFinderImpl.java b/docroot/WEB-INF/src/com/liferay/lms/service/persistence/CourseFinderImpl.java index ab30b4cd2..1266310ff 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/service/persistence/CourseFinderImpl.java +++ b/docroot/WEB-INF/src/com/liferay/lms/service/persistence/CourseFinderImpl.java @@ -150,7 +150,8 @@ public class CourseFinderImpl extends BasePersistenceImpl implements Cou ".countExistingUserCourses"; public static final String GET_DISTINCT_COURSE_GROUPS = CourseFinder.class.getName() + ".getDistinctCourseGroups"; - + public static final String FIND_CHILD_REGISTRED_USER = + CourseFinder.class.getName() + ".findChildRegistredUser"; public static final String INNER_JOIN_CUSTOM_ATTRIBUTE = CourseFinder.class.getName() + ".innerCustomAttribute"; @@ -190,7 +191,7 @@ public List findByC_T_D_S_PC_G(long companyId, String title, String desc description = "%" + description + "%"; if (params == null) { - params = _emptyLinkedHashMap; + params = new LinkedHashMap(0); } if(Validator.isNotNull(title) || Validator.isNotNull(description)){ @@ -690,7 +691,7 @@ public int countByC_T_D_S_PC_G(long companyId, String title, String description, description = "%" + description + "%"; if (params == null) { - params = _emptyLinkedHashMap; + params = new LinkedHashMap(0);; } if(Validator.isNotNull(title) || Validator.isNotNull(description)){ @@ -1515,6 +1516,50 @@ public int countMyCourses(long groupId, long userId, LinkedHashMap findChildRegistredUser(long parentCourseId, long userId){ + + Session session = null; + List listCourse = null; + + if(log.isDebugEnabled()){ + log.debug("CourseFinderImpl:findChildRegistredUser"); + log.debug("parentCourseId: " + parentCourseId); + log.debug("userId: " + userId); + } + + try{ + + session = openSession(); + + String sql = CustomSQLUtil.get(FIND_CHILD_REGISTRED_USER); + log.debug("sql: " + sql); + + SQLQuery q = session.createSQLQuery(sql); + + q.addEntity("Lms_Course", CourseImpl.class); + + QueryPos qPos = QueryPos.getInstance(q); + + qPos.add(userId); + qPos.add(parentCourseId); + + if(log.isDebugEnabled()){ + log.debug("sql: " + sql); + } + + listCourse = (List) QueryUtil.list( + q, getDialect(), QueryUtil.ALL_POS, QueryUtil.ALL_POS); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + closeSession(session); + } + + return listCourse; + } + protected void setJoinCustomAttribute( QueryPos qPos, long columnId, String expandoValue){ if(columnId > 0 && Validator.isNotNull(expandoValue)){ @@ -1598,7 +1643,6 @@ public Session openSessionLiferay() throws ORMException { private static final String PARAM_STATUS = "status"; private static final String PARAM_PARENT_COURSE_ID = "parentCourseId"; - private LinkedHashMap _emptyLinkedHashMap = - new LinkedHashMap(0); + } diff --git a/docroot/WEB-INF/src/com/liferay/lms/upgrade/UpgradeVersion_3_8_0.java b/docroot/WEB-INF/src/com/liferay/lms/upgrade/UpgradeVersion_3_8_0.java new file mode 100644 index 000000000..58b3bb20d --- /dev/null +++ b/docroot/WEB-INF/src/com/liferay/lms/upgrade/UpgradeVersion_3_8_0.java @@ -0,0 +1,75 @@ +package com.liferay.lms.upgrade; + + +import java.io.IOException; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.liferay.lms.model.LmsPrefs; +import com.liferay.lms.model.Module; +import com.liferay.lms.service.LmsPrefsLocalServiceUtil; +import com.liferay.lms.service.ModuleLocalServiceUtil; +import com.liferay.portal.kernel.dao.db.DB; +import com.liferay.portal.kernel.dao.db.DBFactoryUtil; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.search.Indexer; +import com.liferay.portal.kernel.search.IndexerRegistryUtil; +import com.liferay.portal.kernel.upgrade.UpgradeProcess; +import com.liferay.portal.kernel.util.ContentTypes; +import com.liferay.portal.model.Company; +import com.liferay.portal.model.ResourceConstants; +import com.liferay.portal.model.Role; +import com.liferay.portal.model.RoleConstants; +import com.liferay.portal.service.CompanyLocalServiceUtil; +import com.liferay.portal.service.ResourceActionLocalServiceUtil; +import com.liferay.portal.service.ResourcePermissionLocalServiceUtil; +import com.liferay.portal.service.RoleLocalServiceUtil; +import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; + +public class UpgradeVersion_3_8_0 extends UpgradeProcess { + private static Log log = LogFactoryUtil.getLog(UpgradeVersion_3_8_0.class); + + + public int getThreshold() { + return 380; + } + + protected void doUpgrade() throws Exception { + log.info("Actualizando version a 3.8"); + + /*********************************************************************************************/ + /***************** ALTER TABLE LMS_ASYNCHRONOUSPROCESSAUDIT -->> EXTRA CONTENT **************/ + /*********************************************************************************************/ + + String alterCourseDeniedInscription = "ALTER TABLE `lms_asynchronousprocessaudit` "+ + "ADD COLUMN `extraContent` LONGTEXT NULL AFTER `statusMessage`;"; + + + /*********************************************************************************************/ + /***************************Execute SQL Queries******************************/ + /*********************************************************************************************/ + DB db = DBFactoryUtil.getDB(); + log.info("Alter table lms_asynchronousprocessaudit -->> Add extracontent"); + try { + db.runSQL(alterCourseDeniedInscription); + } catch (IOException | SQLException e) { + e.printStackTrace(); + } + + //Damos el permiso de registrar al user + List companies = CompanyLocalServiceUtil.getCompanies(); + Role userRole = null; + for(Company company: companies){ + log.info("Asignando permiso REGISTER al User en companyId: " + company.getCompanyId()); + userRole = RoleLocalServiceUtil.getRole(company.getCompanyId(), RoleConstants.USER); + ResourcePermissionLocalServiceUtil.addResourcePermission(company.getCompanyId(), "com.liferay.lms.model.Course", ResourceConstants.SCOPE_COMPANY, String.valueOf(company.getCompanyId()), userRole.getRoleId(), "REGISTER"); + } + + } + +} \ No newline at end of file diff --git a/docroot/WEB-INF/src/com/liferay/lms/views/CourseStatsView.java b/docroot/WEB-INF/src/com/liferay/lms/views/CourseStatsView.java index 8af7c81c2..846f8e5f4 100644 --- a/docroot/WEB-INF/src/com/liferay/lms/views/CourseStatsView.java +++ b/docroot/WEB-INF/src/com/liferay/lms/views/CourseStatsView.java @@ -1,5 +1,17 @@ package com.liferay.lms.views; +import java.text.DecimalFormat; +import java.util.Locale; + +import com.liferay.lms.model.Course; +import com.liferay.lms.service.CourseLocalServiceUtil; +import com.liferay.lms.service.CourseResultLocalServiceUtil; +import com.liferay.lms.service.LearningActivityLocalServiceUtil; +import com.liferay.lms.service.ModuleLocalServiceUtil; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.language.LanguageUtil; +import com.liferay.portal.kernel.workflow.WorkflowConstants; + public class CourseStatsView { @@ -11,13 +23,62 @@ public class CourseStatsView { private long finished; private long passed; private long failed; + private Course course; + private double avgResult = 0.0; + private long modules; + private long activities; + private String closed; + private DecimalFormat df = new DecimalFormat("#.#"); + + - public CourseStatsView(long courseId, String courseTitle) { + + + public CourseStatsView(long courseId, Locale locale, long teamId, long[] userExcludedIds, long[] userIds, boolean generalStats) { super(); this.courseId = courseId; - this.courseTitle = courseTitle; + + try { + this.course = CourseLocalServiceUtil.fetchCourse(courseId); + this.courseTitle = course.getTitle(locale); + if(teamId > 0){ + this.registered =userIds.length; + this.started = CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsStarted(course.getCourseId(), userIds); + this.started = CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsFinished(course.getCourseId(), userIds); + this.passed = CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsPassed(course.getCourseId(), userIds); + this.failed = CourseResultLocalServiceUtil.countStudentsByCourseIdUserIdsFailed(course.getCourseId(), userIds); + }else{ + this.registered = CourseLocalServiceUtil.countStudentsStatus(course.getCourseId(), course.getCompanyId(), null, null, null, null, WorkflowConstants.STATUS_ANY, false); + this.started = CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsStarted(course.getCourseId(), userExcludedIds); + this.finished = CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsFinished(course.getCourseId(), userExcludedIds); + this.passed = CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsPassed(course.getCourseId(), userExcludedIds); + this.failed = CourseResultLocalServiceUtil.countStudentsByCourseIdUserExcludedIdsFailed(course.getCourseId(), userExcludedIds); + } + } catch (SystemException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + if(generalStats){ + try { + this.modules = ModuleLocalServiceUtil.countByGroupId(course.getGroupCreatedId()); + this.activities = LearningActivityLocalServiceUtil.countLearningActivitiesOfGroup(course.getGroupCreatedId()); + if(this.finished>0){ + this.avgResult=CourseResultLocalServiceUtil.avgResultByCourseIdUserExcludedIds(course.getCourseId(), true, userExcludedIds); + } + } catch (SystemException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if(course.getClosed()){ + this.closed = LanguageUtil.get(locale, "yes"); + }else{ + this.closed = LanguageUtil.get(locale,"no"); + } + + } } @@ -50,7 +111,13 @@ public long getRegistered() { return registered; } - + public String getCssClosed(){ + String cssClosed =""; + if(course.getClosed()){ + cssClosed="course-closed"; + } + return cssClosed; + } public void setRegistered(long registered) { this.registered = registered; @@ -104,6 +171,62 @@ public void setFailed(long failed) { this.failed = failed; } - + public Course getCourse() { + return course; + } + + + + public void setCourse(Course course) { + this.course = course; + } + + + + public String getAvgResult() { + return df.format(avgResult); + } + + + + public void setAvgResult(double avgResult) { + this.avgResult = avgResult; + } + + + + public long getModules() { + return modules; + } + + + + public void setModules(long modules) { + this.modules = modules; + } + + + + public long getActivities() { + return activities; + } + + + + public void setActivities(long activities) { + this.activities = activities; + } + + + + public String getClosed() { + return closed; + } + + + + public void setClosed(String closed) { + this.closed = closed; + } } diff --git a/docroot/WEB-INF/src/com/liferay/util/CourseCopyUtil.java b/docroot/WEB-INF/src/com/liferay/util/CourseCopyUtil.java index dbd9938ef..4803837f6 100644 --- a/docroot/WEB-INF/src/com/liferay/util/CourseCopyUtil.java +++ b/docroot/WEB-INF/src/com/liferay/util/CourseCopyUtil.java @@ -358,19 +358,25 @@ public void createTestQuestionsAndAnswers(LearningActivity oldActivity, Learning TestQuestion newTestQuestion= null; List answers = new ArrayList(); TestAnswer newTestAnswer = null; + HashMap questionIdsMap = new HashMap(); + for(TestQuestion question:questions){ try { newTestQuestion = TestQuestionLocalServiceUtil.addQuestion(newActivity.getActId(), question.getText(), question.getQuestionType()); String newTestDescription = descriptionFilesClone(question.getText(),newModule.getGroupId(), newTestQuestion.getActId(),userId); newTestQuestion.setText(newTestDescription); - TestQuestionLocalServiceUtil.updateTestQuestion(newTestQuestion, true); + if(question.getWeight() != question.getQuestionId()){ + newTestQuestion.setWeight(question.getWeight()); + questionIdsMap.put(question.getQuestionId(), newTestQuestion.getQuestionId()); + } + newTestQuestion = TestQuestionLocalServiceUtil.updateTestQuestion(newTestQuestion, true); + if(log.isDebugEnabled()){ log.debug(" Test question : " + question.getQuestionId() ); log.debug(" + Test question : " + newTestQuestion.getQuestionId() ); log.debug(" + Test question TEXT : " + newTestDescription ); } } catch (Exception e) { - // TODO Auto-generated catch block e.printStackTrace(); continue; } @@ -394,12 +400,19 @@ public void createTestQuestionsAndAnswers(LearningActivity oldActivity, Learning // TODO Auto-generated catch block e.printStackTrace(); } - } - } + questions = TestQuestionLocalServiceUtil.getQuestions(newActivity.getActId()); + for(TestQuestion question:questions){ + log.debug("orden anterior de la pregunta: " + question.getWeight()); + if(question.getWeight() > 0 && questionIdsMap.containsKey(question.getWeight())){ + log.debug("nuevo orden: " + questionIdsMap.get(question.getWeight())); + question.setWeight(questionIdsMap.get(question.getWeight())); + TestQuestionLocalServiceUtil.updateTestQuestion(question); + } + } } public void copyEvaluationExtraContent(List evaluations, HashMap correlationActivities) throws PortalException, SystemException{ diff --git a/docroot/WEB-INF/src/content/Language.properties b/docroot/WEB-INF/src/content/Language.properties index d254b3868..88c45741f 100644 --- a/docroot/WEB-INF/src/content/Language.properties +++ b/docroot/WEB-INF/src/content/Language.properties @@ -76,6 +76,7 @@ activity.edition = Edici\u00F3n de actividad activity.go = Iniciar activity.invisible = No visible activity.just.one.visible = Visible solo esta actividad +activity.move-activity-with-result = Hay usuarios que han realizado la actividad. Antes de mover la actividad de m\u00F3dulo, se deben eliminar todos los resultados de los usuarios. activity.openwindow = La actividad se abrir\u00E1 en una nueva ventana. Si no es as\u00ED, pulsa en Iniciar o Continuar activity.openwindow.passed = Si deseas reintentar la actividad pulsa en Iniciar activity.result = Tu resultado es: {0} @@ -141,8 +142,13 @@ assign-member = Asignar miembros asynchronous-proccess-audit.status-ok = El proceso ha finalizado correctamente -asynchronous-process-audit.process-not-started = El proceso a\u00FAn no ha comenzado. La llamada no ha sido recibida. -asynchronous-process-audit.status-ok = El proceso ha finalizado correctamente +asynchronous-process-audit.config.only-owner = Mostrar solo eventos propios del usuario +asynchronous-process-audit.config.refresh-page-eachXSeg = Refrescar cada x segundos. 0 para desactivarlo. Min 10 segundos. +asynchronous-process-audit.config.show-all-class-name = Mostrar todos los tipos de evento o selecciona los disponibles. +asynchronous-process-audit.config.show-extra-content = Mostrar columna extraContent +asynchronous-process-audit.config.show-types = Mostrar todos los tipos de evento o selecciona los disponibles. +asynchronous-process-audit.process-not-started = El proceso a\u00FAn no ha comenzado. La llamada no ha sido recibida. +asynchronous-process-audit.status-ok = El proceso ha finalizado correctamente auto-upgrade = Actualizaci\u00F3n autom\u00E1tica @@ -646,6 +652,10 @@ editactivity.selectoption = Seleccione edition = Edici\u00F3n +editions-available = Ediciones disponibles + +editions-available.select-edition = Seleccione la edici\u00F3n en la que desea inscribirse y pulse en el bot\u00F3n para inscribirse + enable-edition = Activar edici\u00F3n end-course-date = Fecha de fin @@ -871,7 +881,6 @@ execactivity.editquestions.partialcorrection = Evaluaci\u00F3n Par execactivity.editquestions.partialcorrection.helpmessage = Si se marca esta opci\u00F3n no ser\u00E1 necesario responder correctamente a todas las preguntas para obtener una calificaci\u00F3n execactivity.manualCorrect = Correcci\u00F3n Manual execactivity.notes = Notas -execactivity.test.go-to-test = Ir al test execativity.editquestions.banks.multipleselections.helpmessage = Marcar en caso de que desee utilizar preguntas de bancos de forma aleatoria. execativity.editquestions.editquestion = Edici\u00F3n pregunta @@ -930,6 +939,8 @@ execution-date = Periodo de ejecuci\u00F3n export = Exportar +extraContent = Contenido Extra + failed = Suspenso false = Falso @@ -972,6 +983,15 @@ freetext.title = Texto libre general = General +generalstats.config.showActivities = Mostrar columna de actividades +generalstats.config.showAvgResult = Mostrar columna de puntuaci\u00F3n media +generalstats.config.showCourseClosed = Mostrar columna de curso cerrado +generalstats.config.showFailed = Mostrar columna de fallados +generalstats.config.showFinished = Mostrar columna de finalizados +generalstats.config.showInit = Mostrar columna de iniciados +generalstats.config.showModules = Mostrar columna de m\u00F3dulos +generalstats.config.showPassed = Mostrar columna de pasados +generalstats.config.showRegistered = Mostrar columna de registrados generalstats.config.showSearch = Opciones de b\u00FAsqueda generalstats.config.showSearchCategories = Buscar por clasificaci\u00F3n generalstats.config.showSearchTags = Buscar por tags @@ -1040,8 +1060,12 @@ inscription-error-already-enrolled = Ya est\u00E1s inscrito en el curso inscription-error-max-users = El curso ha alcanzado el n\u00FAmero m\u00E1ximo de usuarios +inscription-error-syte-private = El curso es privado + inscription-error-syte-restricted = El curso est\u00E1 restringido +inscription-ok = La inscripci\u00F3n al curso se ha realizado correctamente + inscription-startDate-before-stopDate = Fecha de registro posterior a fecha de cierre inscription-type = Tipo de inscripci\u00F3n @@ -1050,6 +1074,8 @@ inscription-type.title = B\u00E1sica inscription-type.user-days.title = Tiempo para alumno inscription.days = D\u00EDas para realizar el curso +inscription.error.permission-register = No tienes permisos para inscribirte en el curso +inscription.go-to-course = Acceder inscription.petition = Peticiones pendientes inscription.totalUsers = Usuarios inscritos @@ -1272,6 +1298,7 @@ lms-inscription-configuration = Inscripci\u00F3n lms.dialog.cancel = Cancelar lms.dialog.ok = Aceptar +lms.inscription.unsusbscribe.success = Se ha desinscrito del curso correctamente lmsactivitieslist.view.actualModule = M\u00F3dulo actual lmsactivitieslist.view.complete = \u00C1rbol completo @@ -1888,6 +1915,8 @@ searchresults.viewresults = Ver resultados. select = Seleccionar +select-edition = Selecciona una edici\u00F3n + select-resource = Seleccione recurso select-the-delivery-options-for-announcements = Seleccione las opciones de entrega para los avisos. @@ -2021,6 +2050,10 @@ taskp2p = Tarea p2p team-activity = Equipo +teams-available = Equipos disponibles + +teams-available.select-team = Seleccione el equipo en el que desea inscribirse y pulse en el bot\u00F3n para inscribirse + template-not-equals = Vas a seleccionar una plantilla distinta al curso. Esto puede causar errores. test-done = Prueba realizada diff --git a/docroot/WEB-INF/src/content/Language_ca.properties b/docroot/WEB-INF/src/content/Language_ca.properties index eda164288..294334c11 100644 --- a/docroot/WEB-INF/src/content/Language_ca.properties +++ b/docroot/WEB-INF/src/content/Language_ca.properties @@ -869,7 +869,6 @@ execactivity.editquestions.partialcorrection = Avaluaci\u00F3 Parc execactivity.editquestions.partialcorrection.helpmessage = Si es marca aquesta opci\u00F3 no ser\u00E0 necessari respondre correctament a totes les preguntes per obtenir una qualificaci\u00F3 execactivity.manualCorrect = Correcci\u00F3 manual execactivity.notes = Notes -execactivity.test.go-to-test = Anar al test execativity.editquestions.banks.categoryselections = Selecciona les categories els bancs vols incloure. execativity.editquestions.banks.error.caterogiesempty = Heu de seleccionar almenys una categoria @@ -1045,6 +1044,8 @@ inscription-error-max-users = El curs ha arribat al nombre m\u00E0xim d'usuaris inscription-error-syte-restricted = El curs est\u00E0 restringit +inscription-ok = La inscripci\u00F3 al curs s'ha realitzat correctament + inscription-startDate-before-stopDate = Data de registre posterior a la data de tancament inscription-type = Tipus d'inscripci\u00F3 @@ -1053,6 +1054,7 @@ inscription-type.title = B\u00E0sica inscription-type.user-days.title = Temps per a l'alumne inscription.days = Dies per realitzar el curs +inscription.go-to-course = Accedir inscription.petition = Peticions pendents inscription.totalUsers = Usuaris inscrits @@ -2161,3 +2163,27 @@ your-result-try-again = Torna a intentar-ho. youtube-code = Codi de Youtube youtube-code-help = Ha d\u2019introduir el codi que proporciona YouTube/Vimeo per compartir el v\u00EDdeo, que pots trobar a la p\u00E0gina del v\u00EDdeo, a l\u2019opci\u00F3 \u201CComparteix/Insereix\u201D.\r\n + +activity.move-activity-with-result=Hi ha usuaris que han fet l’activitat. Abans de moure l’activitat de mòdul, cal eliminar tots els resultats dels usuaris. +asynchronous-process-audit.config.only-owner=Mostra només esdeveniments propis de l’usuari +asynchronous-process-audit.config.refresh-page-eachXSeg=Refresca cada x segons. 0 per desactivar-lo. Mín. 10 segons. +asynchronous-process-audit.config.show-all-class-name=Mostra tots els tipus d’esdeveniment o selecciona’n els disponibles. +asynchronous-process-audit.config.show-extra-content=Mostra la columna extraContent +asynchronous-process-audit.config.show-types=Mostra tots els tipus d’esdeveniment o selecciona’n els disponibles. +editions-available=Edicions disponibles +editions-available.select-edition=Seleccioneu l’edició en la qual us voleu inscriure i premeu el botó per inscriure-us-hi +extraContent=Contingut extra +generalstats.config.showActivities=Mostra la columna d’activitats +generalstats.config.showAvgResult=Mostra la columna de puntuació mitjana +generalstats.config.showCourseClosed=Mostra la columna de curs tancat +generalstats.config.showFailed=Mostra la columna de fallats +generalstats.config.showFinished=Mostra la columna de finalitzats +generalstats.config.showInit=Mostra la columna d’iniciats +generalstats.config.showModules=Mostra la columna de mòduls +generalstats.config.showPassed=Mostra la columna de passats +generalstats.config.showRegistered=Mostra la columna de registrats +inscription-error-syte-private=El curs és privat +lms.inscription.unsusbscribe.success=S’ha desinscrit del curs correctament +select-edition=Selecciona una edició +teams-available=Equips disponibles +teams-available.select-team=Seleccioneu l’equip en el qual us voleu inscriure i premeu el botó per inscriure-us-hi diff --git a/docroot/WEB-INF/src/content/Language_en.properties b/docroot/WEB-INF/src/content/Language_en.properties index 9172987af..66a452736 100644 --- a/docroot/WEB-INF/src/content/Language_en.properties +++ b/docroot/WEB-INF/src/content/Language_en.properties @@ -885,7 +885,6 @@ execactivity.editquestions.partialcorrection = Partial Evaluation execactivity.editquestions.partialcorrection.helpmessage = If this option is checked it will not be necessary to answer all questions correctly for rating execactivity.manualCorrect = Manual Correction execactivity.notes = Notes -execactivity.test.go-to-test = Go to test execativity.editquestions.banks.categoryselections = Select the categories whose banks want to include. execativity.editquestions.banks.error.caterogiesempty = You must select at least one category @@ -1063,6 +1062,8 @@ inscription-error-max-users = The course has reached the maximum number of users inscription-error-syte-restricted = The course is restricted +inscription-ok = Course registration has been successfully completed + inscription-startDate-before-stopDate = Registry date after close inscription-type = Type of registration @@ -1071,6 +1072,7 @@ inscription-type.title = Basic inscription-type.user-days.title = Time for students inscription.days = Days to complete the course +inscription.go-to-course = Access inscription.petition = Pending requests inscription.totalUsers = Users registered @@ -2179,3 +2181,28 @@ your-result-try-again = Try again. youtube-code = Youtube/Vimeo code youtube-code-help = Enter the code provided by YouTube/Vimeo to share the video, which you can find on the video page under share/insert + +activity.move-activity-with-result=There are users who have completed the activity. Before moving the activity to another module, all user results must be deleted. +asynchronous-process-audit.config.only-owner=Show only user events +asynchronous-process-audit.config.refresh-page-eachXSeg=Refresh every x seconds. 0 to disable. Min 10 seconds. +asynchronous-process-audit.config.show-all-class-name=Show all event types or select available event types. +asynchronous-process-audit.config.show-extra-content=Show extraContent column +asynchronous-process-audit.config.show-types=Show all event types or select available event types. +editions-available=Available editions +editions-available.select-edition=Select the edition you want to register for and click the button to register +extraContent=Extra Content +generalstats.config.showActivities=Show activity column +generalstats.config.showAvgResult=Show average score column +generalstats.config.showCourseClosed=Show closed course column +generalstats.config.showFailed=Show failed column +generalstats.config.showFinished=Show completed column +generalstats.config.showInit=Show started column +generalstats.config.showModules=Show module column +generalstats.config.showPassed=Show past column +generalstats.config.showRegistered=Show registered column +inscription-error-syte-private=The course is private +lms.inscription.unsusbscribe.success=You have withdrawn from the course successfully +select-edition=Select an edition +teams-available=Teams available +teams-available.select-team=Select the team you want to register for and click the button to register + diff --git a/docroot/WEB-INF/src/content/Language_es.properties b/docroot/WEB-INF/src/content/Language_es.properties index b75b7d0cf..b1be905bd 100644 --- a/docroot/WEB-INF/src/content/Language_es.properties +++ b/docroot/WEB-INF/src/content/Language_es.properties @@ -76,6 +76,7 @@ activity.edition = Edici\u00F3n de actividad activity.go = Iniciar activity.invisible = No visible activity.just.one.visible = Visible solo esta actividad +activity.move-activity-with-result = Hay usuarios que han realizado la actividad. Antes de mover la actividad de m\u00F3dulo, se deben eliminar todos los resultados de los usuarios. activity.openwindow = La actividad se abrir\u00E1 en una nueva ventana. Si no es as\u00ED, pulsa en Iniciar o Continuar activity.openwindow.passed = Si deseas reintentar la actividad pulsa en Iniciar activity.result = Tu resultado es: {0} @@ -648,6 +649,10 @@ editactivity.selectoption = Seleccione edition = Edici\u00F3n +editions-available = Ediciones disponibles + +editions-available.select-edition = Seleccione la edici\u00F3n en la que desea inscribirse y pulse en el bot\u00F3n para inscribirse + enable-edition = Activar edici\u00F3n end-course-date = Fecha de fin @@ -873,7 +878,6 @@ execactivity.editquestions.partialcorrection = Evaluaci\u00F3n Par execactivity.editquestions.partialcorrection.helpmessage = Si se marca esta opci\u00F3n no ser\u00E1 necesario responder correctamente a todas las preguntas para obtener una calificaci\u00F3n execactivity.manualCorrect = Correcci\u00F3n Manual execactivity.notes = Notas -execactivity.test.go-to-test = Ir al test execativity.editquestions.banks.categoryselections = Selecciona las categor\u00EDas cuyos bancos deseas incluir. execativity.editquestions.banks.error.caterogiesempty = Debe seleccionar al menos una categor\u00EDa @@ -979,6 +983,15 @@ freetext.title = Texto libre general = General +generalstats.config.showActivities = Mostrar columna de actividades +generalstats.config.showAvgResult = Mostrar columna de puntuaci\u00F3n media +generalstats.config.showCourseClosed = Mostrar columna de curso cerrado +generalstats.config.showFailed = Mostrar columna de fallados +generalstats.config.showFinished = Mostrar columna de finalizados +generalstats.config.showInit = Mostrar columna de iniciados +generalstats.config.showModules = Mostrar columna de m\u00F3dulos +generalstats.config.showPassed = Mostrar columna de pasados +generalstats.config.showRegistered = Mostrar columna de registrados generalstats.config.showSearch = Opciones de b\u00FAsqueda generalstats.config.showSearchCategories = Buscar por clasificaci\u00F3n generalstats.config.showSearchTags = Buscar por tags @@ -1049,8 +1062,12 @@ inscription-error-already-enrolled = Ya est\u00E1s inscrito en el curso inscription-error-max-users = El curso ha alcanzado el n\u00FAmero m\u00E1ximo de usuarios +inscription-error-syte-private = El curso es privado + inscription-error-syte-restricted = El curso est\u00E1 restringido +inscription-ok = La inscripci\u00F3n al curso se ha realizado correctamente + inscription-startDate-before-stopDate = Fecha de registro posterior a fecha de cierre inscription-type = Tipo de inscripci\u00F3n @@ -1059,6 +1076,8 @@ inscription-type.title = B\u00E1sica inscription-type.user-days.title = Tiempo para alumno inscription.days = D\u00EDas para realizar el curso +inscription.error.permission-register = No tienes permisos para inscribirte en el curso +inscription.go-to-course = Acceder inscription.petition = Peticiones pendientes inscription.totalUsers = Usuarios inscritos @@ -1281,6 +1300,7 @@ lms-inscription-configuration = Inscripci\u00F3n lms.dialog.cancel = Cancelar lms.dialog.ok = Aceptar +lms.inscription.unsusbscribe.success = Se ha desinscrito del curso correctamente lmsactivitieslist.view.actualModule = M\u00F3dulo actual lmsactivitieslist.view.complete = \u00C1rbol completo @@ -1898,6 +1918,8 @@ searchresults.viewresults = Ver resultados. select = Seleccionar +select-edition = Selecciona una edici\u00F3n + select-resource = Seleccione recurso select-the-delivery-options-for-announcements = Seleccione las opciones de entrega para los avisos. @@ -2031,6 +2053,10 @@ taskp2p = Tarea p2p team-activity = Equipo +teams-available = Equipos disponibles + +teams-available.select-team = Seleccione el equipo en el que desea inscribirse y pulse en el bot\u00F3n para inscribirse + template-not-equals = Vas a seleccionar una plantilla distinta al curso. Esto puede causar errores. test-done = Prueba realizada diff --git a/docroot/WEB-INF/src/content/Language_it.properties b/docroot/WEB-INF/src/content/Language_it.properties index 6e157bfbf..e519413f7 100644 --- a/docroot/WEB-INF/src/content/Language_it.properties +++ b/docroot/WEB-INF/src/content/Language_it.properties @@ -865,7 +865,6 @@ execactivity.editquestions.partialcorrection = Valutazione Parzial execactivity.editquestions.partialcorrection.helpmessage = Se si indica questa opzione non sar\u00E0 necessario rispondere correttamente a tutte le domande per ottenere un voto execactivity.manualCorrect = Correzione Manuale execactivity.notes = Voti -execactivity.test.go-to-test = Vai al test execativity.editquestions.banks.multipleselections.helpmessage = Indica nel caso in cui desideri utilizzare le domande delle banche in modo aleatorio. execativity.editquestions.editquestion = Modifica domanda @@ -1036,6 +1035,8 @@ inscription-error-max-users = Il corso ha raggiunto il numero massimo di utenti inscription-error-syte-restricted = Il corso \u00E8 a numero chiuso +inscription-ok = L'iscrizione al corso \u00E8 stata effettuata con successo + inscription-startDate-before-stopDate = Data di iscrizione posteriore a quella di chiusura inscription-type = Tipo d'iscrizione @@ -1044,6 +1045,7 @@ inscription-type.title = Base inscription-type.user-days.title = Tempo per alunno inscription.days = Giorni a disposizione per realizzare il corso +inscription.go-to-course = Accedi inscription.petition = Richieste in sospeso inscription.totalUsers = Utenti iscritti @@ -2152,3 +2154,28 @@ your-result-try-again = Riprova. youtube-code = Codice di Youtube/Vimeo youtube-code-help = Devi inserire il codice offerto da YouTube/Vimeo per condividere il video, che puoi trovare sulla pagina del video su condividi/inserisci. + + +activity.move-activity-with-result=Vi sono utenti che hanno eseguito l’attività. Prima di spostare l’attività in un altro modulo, è necessario eliminare tutti i risultati degli utenti. +asynchronous-process-audit.config.only-owner=Mostra solo gli eventi dell’utente +asynchronous-process-audit.config.refresh-page-eachXSeg=Aggiorna ogni x secondi 0 per la disattivazione. Min 10 secondi. +asynchronous-process-audit.config.show-all-class-name=Mostra tutti i tipi di eventi o seleziona quelli disponibili. +asynchronous-process-audit.config.show-extra-content=Mostra colonna extraContent +asynchronous-process-audit.config.show-types=Mostra tutti i tipi di eventi o seleziona quelli disponibili. +editions-available=Edizioni disponibili +editions-available.select-edition=Seleziona l’edizione a cui desideri iscriverti e clicca sul pulsante di iscrizione +extraContent=Contenuti Extra +generalstats.config.showActivities=Mostra colonna attività +generalstats.config.showAvgResult=Mostra colonna punteggio medio +generalstats.config.showCourseClosed=Mostra colonna corso chiuso +generalstats.config.showFailed=Mostra colonna errori +generalstats.config.showFinished=Mostra colonna completati +generalstats.config.showInit=Mostra colonna avviati +generalstats.config.showModules=Mostra colonna moduli +generalstats.config.showPassed=Mostra colonna passati +generalstats.config.showRegistered=Mostra colonna registrati +inscription-error-syte-private=Il corso è privato +lms.inscription.unsusbscribe.success=La cancellazione dell’iscrizione al corso è stata eseguita correttamente +select-edition=Seleziona un’edizione +teams-available=Equipe disponibili +teams-available.select-team=Seleziona l’equipe in cui desideri iscriverti e clicca sul pulsante di iscrizione diff --git a/docroot/WEB-INF/src/content/Language_pt.properties b/docroot/WEB-INF/src/content/Language_pt.properties index b8bfd99cb..d0fd66573 100644 --- a/docroot/WEB-INF/src/content/Language_pt.properties +++ b/docroot/WEB-INF/src/content/Language_pt.properties @@ -909,7 +909,6 @@ execactivity.editquestions.partialcorrection = Avalia\u00E7\u00E3o execactivity.editquestions.partialcorrection.helpmessage = Se esta op\u00E7\u00E3o estiver marcada, n\u00E3o ser\u00E1 necess\u00E1rio responder todas as perguntas corretamente para classifica\u00E7\u00E3o execactivity.manualCorrect = Corre\u00E7\u00E3o manual execactivity.notes = Notas -execactivity.test.go-to-test = Ir a teste execativity.editquestions.banks.categoryselections = Selecione as categorias cujos bancos deseja incluir. execativity.editquestions.banks.error.caterogiesempty = Voc\u00EA deve selecionar pelo menos uma categoria @@ -1095,6 +1094,8 @@ inscription-error-max-users = O curso atingiu o n\u00FAmero m\u00E1ximo de utili inscription-error-syte-restricted = O curso \u00E9 restrito +inscription-ok = O registro no curso foi conclu\u00EDdo com sucesso + inscription-startDate-before-stopDate = Data de registo posterior \u00E0 data de encerramento inscription-type = Tipo de registro @@ -1103,6 +1104,7 @@ inscription-type.title = B\u00E1sico inscription-type.user-days.title = Tempo para o aluno inscription.days = Dias para completar o curso +inscription.go-to-course = Ir para curso inscription.petition = Pedidos pendentes inscription.totalUsers = Usu\u00E1rios inscritos @@ -2326,3 +2328,27 @@ your-result-try-again = Tente novamente. youtube-code = C\u00F3digo de Youtube/Vimeo youtube-code-help = Voc\u00EA deve introduzir o c\u00F3digo que o YouTube/Vimeo proporciona para compartilhar o v\u00EDdeo, que pode encontrar na p\u00E1gina do v\u00EDdeo, em compartilhar/inserir. + +activity.move-activity-with-result=Há usuários que realizaram a atividade. Antes de mover a atividade de módulo, é preciso eliminar todos os resultados dos usuários. +asynchronous-process-audit.config.only-owner=Mostrar só eventos próprios do usuário +asynchronous-process-audit.config.refresh-page-eachXSeg=Atualizar a cada x segundos. 0 para desativá-lo. Min. 10 segundos. +asynchronous-process-audit.config.show-all-class-name=Mostrar todos os tipos de evento ou selecione os disponíveis. +asynchronous-process-audit.config.show-extra-content=Mostrar coluna extraContent +asynchronous-process-audit.config.show-types=Mostrar todos os tipos de evento ou selecione os disponíveis. +editions-available=Edições disponíveis +editions-available.select-edition=Selecione a edição que deseja realizar a inscrição e pressione o botão de registro +extraContent=Conteúdo Extra +generalstats.config.showActivities=Mostrar coluna de atividades +generalstats.config.showAvgResult=Mostrar coluna de pontuação média +generalstats.config.showCourseClosed=Mostrar coluna de curso fechado +generalstats.config.showFailed=Mostrar coluna de reprovados +generalstats.config.showFinished=Mostrar coluna de finalizados +generalstats.config.showInit=Mostrar coluna de iniciados +generalstats.config.showModules=Mostrar coluna de módulos +generalstats.config.showPassed=Mostrar coluna de superados +generalstats.config.showRegistered=Mostrar coluna de registrados +inscription-error-syte-private=O curso é privado +lms.inscription.unsusbscribe.success=Sua desinscrição do curso foi realizada corretamente +select-edition=Selecione uma edição +teams-available=Equipes disponíveis +teams-available.select-team=Selecione a equipe em que deseja realizar a inscrição e pressione o botão de registro diff --git a/docroot/WEB-INF/src/content/Language_tr.properties b/docroot/WEB-INF/src/content/Language_tr.properties index d1f971d69..7b560b099 100644 --- a/docroot/WEB-INF/src/content/Language_tr.properties +++ b/docroot/WEB-INF/src/content/Language_tr.properties @@ -968,8 +968,11 @@ inscription-error-max-users = Kurs maksimum kullan\u0131c\u0131 say\u0131s\u0131 inscription-error-syte-restricted = Kurs s\u0131n\u0131rl\u0131 +inscription-ok = Kursa kay\u0131t olma i\u015Flemi do\u011Fru \u015Fekilde ger\u00E7ekle\u015Fti + inscription-startDate-before-stopDate = Kay\u0131t tarihi biti\u015F tarihinden ileri +inscription.go-to-course = Giri\u015F yap inscription.petition = Beklemede olan talepler inscription.totalUsers = Kay\u0131tl\u0131 kullan\u0131c\u0131lar diff --git a/docroot/WEB-INF/src/content/Language_zh.properties b/docroot/WEB-INF/src/content/Language_zh.properties index f3103ddfb..3a327a99c 100644 --- a/docroot/WEB-INF/src/content/Language_zh.properties +++ b/docroot/WEB-INF/src/content/Language_zh.properties @@ -967,8 +967,11 @@ inscription-error-max-users = \u8BFE\u7A0B\u5DF2\u8FBE\u5230\u6700\u5927\u7528\u inscription-error-syte-restricted = \u8BFE\u7A0B\u53D7\u9650\u5236 +inscription-ok = \u8BFE\u7A0B\u6CE8\u518C\u6B63\u786E\u5B8C\u6210 + inscription-startDate-before-stopDate = \u622A\u6B62\u65E5\u671F\u540E\u7684\u6CE8\u518C\u65E5\u671F +inscription.go-to-course = \u767B\u5165 inscription.petition = \u5F85\u5B9A\u8BF7\u6C42 inscription.totalUsers = \u6CE8\u518C\u7528\u6237 diff --git a/docroot/WEB-INF/src/content/asynchronousprocessdashboard/Language.properties b/docroot/WEB-INF/src/content/asynchronousprocessdashboard/Language.properties index ba6197e4b..37fe5b1d3 100644 --- a/docroot/WEB-INF/src/content/asynchronousprocessdashboard/Language.properties +++ b/docroot/WEB-INF/src/content/asynchronousprocessdashboard/Language.properties @@ -2,3 +2,5 @@ javax.portlet.description = Panel de procesos as\u00EDncronos javax.portlet.long-title = Panel de procesos as\u00EDncronos javax.portlet.title = Panel de procesos as\u00EDncronos + + diff --git a/docroot/WEB-INF/src/custom-sql/asynchronousprocessaudit.xml b/docroot/WEB-INF/src/custom-sql/asynchronousprocessaudit.xml index 95ef418e9..ca5ed4b25 100644 --- a/docroot/WEB-INF/src/custom-sql/asynchronousprocessaudit.xml +++ b/docroot/WEB-INF/src/custom-sql/asynchronousprocessaudit.xml @@ -15,7 +15,8 @@ SELECT * FROM lms_asynchronousprocessaudit asy WHERE asy.companyId = ? - AND asy.type_ = ? + AND asy.type_ IN (?) + AND asy.userId = ? AND asy.createDate > '[$STARTDATE$]' AND asy.createDate <= '[$ENDDATE$]' AND 1 = 1 @@ -29,7 +30,8 @@ SELECT COUNT(*) as COUNT_VALUE FROM lms_asynchronousprocessaudit asy WHERE asy.companyId = ? - AND asy.type_ = ? + AND asy.type_ IN (?) + AND asy.userId = ? AND asy.createDate > '[$STARTDATE$]' AND asy.createDate <= '[$ENDDATE$]' AND 1 = 1 diff --git a/docroot/WEB-INF/src/custom-sql/course.xml b/docroot/WEB-INF/src/custom-sql/course.xml index 9caf736b6..257a96695 100644 --- a/docroot/WEB-INF/src/custom-sql/course.xml +++ b/docroot/WEB-INF/src/custom-sql/course.xml @@ -315,5 +315,18 @@ (ev.data_ LIKE ? AND ev.tableId = ? AND ev.columnId = ?) ]]> + + + \ No newline at end of file diff --git a/docroot/WEB-INF/src/portal.properties b/docroot/WEB-INF/src/portal.properties index ee95c47d6..fddb100c5 100644 --- a/docroot/WEB-INF/src/portal.properties +++ b/docroot/WEB-INF/src/portal.properties @@ -30,7 +30,7 @@ lms.questions.allowed.for.4=2,6 lms.questions.allowed.for.2=0,1,2,3,4 #lms.testquestion.generatequestion.portletid= #lms.testquestion.generatequestion.classname= -#audit.implementation=com.liferay.lms.auditing.AuditingLogDB +audit.implementation=com.liferay.lms.auditing.AuditingLogDB lms.calification.type.0=com.liferay.lms.learningactivity.calificationtype.PercentCalificationType lms.calification.type.1=com.liferay.lms.learningactivity.calificationtype.CeroToTenCalificationType lms.calification.type.3=com.liferay.lms.learningactivity.calificationtype.CeroToNCalificationType @@ -69,7 +69,8 @@ lms.module.courtesytime.miliseconds=5000 com.liferay.lms.diploma.background.path=Diplomas/Fondos com.liferay.lms.diploma.additional.type=1,2,3 -release.info.build.number=374 -release.info.previous.build.number=360 -upgrade.processes=\com.liferay.lms.upgrade.UpgradeVersion_3_7_0,\com.liferay.lms.upgrade.UpgradeVersion_3_6_0,\com.liferay.lms.upgrade.UpgradeVersion_3_4_0,\com.liferay.lms.upgrade.UpgradeVersion_3_3_0,\com.liferay.lms.upgrade.UpgradeVersion_3_2_0 +release.info.build.number=380 +release.info.previous.build.number=372 +upgrade.processes=\com.liferay.lms.upgrade.UpgradeVersion_3_8_0,\com.liferay.lms.upgrade.UpgradeVersion_3_7_0,\com.liferay.lms.upgrade.UpgradeVersion_3_6_0,\com.liferay.lms.upgrade.UpgradeVersion_3_4_0,\com.liferay.lms.upgrade.UpgradeVersion_3_3_0,\com.liferay.lms.upgrade.UpgradeVersion_3_2_0 + diff --git a/docroot/html/asset/course/abstract.jsp b/docroot/html/asset/course/abstract.jsp index 925a7aa6d..cfeb7a64f 100644 --- a/docroot/html/asset/course/abstract.jsp +++ b/docroot/html/asset/course/abstract.jsp @@ -107,7 +107,7 @@ String summary = assetEntry.getSummary(themeDisplay.getLocale()); summary = StringUtil.shorten(summary, Integer.valueOf(abstractLength), "..."); %> -

<%= summary %>

+
<%= summary %>
<% } %> \ No newline at end of file diff --git a/docroot/html/asynchronousprocessdashboard/config/config.jsp b/docroot/html/asynchronousprocessdashboard/config/config.jsp new file mode 100644 index 000000000..7e46069a9 --- /dev/null +++ b/docroot/html/asynchronousprocessdashboard/config/config.jsp @@ -0,0 +1,94 @@ +<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%> +<%@page import="javax.portlet.PortletPreferences"%> +<%@page import="com.liferay.lms.service.AsynchronousProcessAuditLocalServiceUtil"%> +<%@page import="com.liferay.portlet.PortletPreferencesFactoryUtil"%> +<%@page import="com.liferay.portal.kernel.util.Constants"%> +<%@ include file="/init.jsp" %> +<% + PortletPreferences preferences = null; + + String portletResource = ParamUtil.getString(request, "portletResource"); + + if (Validator.isNotNull(portletResource)) { + preferences = PortletPreferencesFactoryUtil.getPortletSetup(request, portletResource); + } + else{ + preferences = renderRequest.getPreferences(); + } + + boolean onlyForUserOwner = (preferences.getValue("preferences--onlyForUserOwner--", "false")).compareTo("true") == 0; + boolean showExtraContent = (preferences.getValue("preferences--showExtraContent--", "false")).compareTo("true") == 0; + String classNamePrefsValues = preferences.getValue("className", ""); + + String refreshPageEachXSeg = (String)preferences.getValue("refreshPageEachXSeg", "0"); + //NEW + boolean showAllClassName = (preferences.getValue("preferences--showAllClassName--", "false")).compareTo("true") == 0; + + if(classNamePrefsValues==null){ classNamePrefsValues = ""; } + if(showAllClassName==true){ classNamePrefsValues = ""; } + + // Obtenemos todos los classname distintos para efectuar la lista; + List classNamesList = AsynchronousProcessAuditLocalServiceUtil.getDistinctTypes(themeDisplay.getCompanyId()); + +%> + + + + + + + + + + + <%for(String classe : classNamesList){ boolean selected=classNamePrefsValues.indexOf(classe) >= 0 ;%> + <%= classe %> + <%} %> + + + + + + + + + + + + + + + + Liferay.provide( + window, + 'saveConfiguration', + function() { + submitForm(document.fm); + }, + ['liferay-util-list-fields'] + ); +AUI().ready('aui-base','event','node', function(A){ + + if(A.one("#showAllClassName")){ + + if(A.one("#showAllClassNameCheckbox").attr('checked')){ + A.one('#className').hide(); + }else{ + A.one('#className').show(); + } + + A.one('#showAllClassNameCheckbox').on('click',function(e){ // it requires Checkbox as prefix in AUI`enter code here` + if(A.one("#showAllClassNameCheckbox").attr('checked')){ + A.one('#className').hide(); + }else{ + A.one('#className').show(); + } + }); + } + }); + + + + + + diff --git a/docroot/html/asynchronousprocessdashboard/search-container.jsp b/docroot/html/asynchronousprocessdashboard/search-container.jsp new file mode 100644 index 000000000..e0fce4229 --- /dev/null +++ b/docroot/html/asynchronousprocessdashboard/search-container.jsp @@ -0,0 +1,83 @@ +<%@page import="com.liferay.portal.kernel.util.FastDateFormatFactoryUtil"%> +<%@page import="java.text.Format"%> +<%@page import="com.liferay.portal.service.ClassNameLocalServiceUtil"%> +<%@page import="com.liferay.portal.kernel.json.JSONObject"%> +<%@page import="com.liferay.portal.kernel.json.JSONFactoryUtil"%> +<%@include file="/init-min.jsp" %> +<% +Format dateFormat = FastDateFormatFactoryUtil.getDateTime(locale, timeZone); +%> + + + + + + + + + + + + + + + + + + + + + + + + + + + ${asynchronousProccessAudit.classPK} + + + + <%=dateFormat.format(asynchronousProccessAudit.getCreateDate()) %> + + + + + <%=dateFormat.format(asynchronousProccessAudit.getEndDate())%> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docroot/html/asynchronousprocessdashboard/view.jsp b/docroot/html/asynchronousprocessdashboard/view.jsp index 128012dca..9dfc48d24 100644 --- a/docroot/html/asynchronousprocessdashboard/view.jsp +++ b/docroot/html/asynchronousprocessdashboard/view.jsp @@ -1,19 +1,85 @@ <%@page import="com.liferay.portal.service.ClassNameLocalServiceUtil"%> +<%@page import="com.liferay.portal.kernel.json.JSONObject"%> +<%@page import="com.liferay.portal.kernel.json.JSONFactoryUtil"%> + <%@ include file="/init.jsp"%> +<% +String timeTodoRefresh = (String) renderRequest.getAttribute("refreshPageEachXSeg"); +%> + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - + + + + + + + + + + -
- - - - - - - - - - - - - - - - - - - - - - - - - - - ${asynchronousProccessAudit.classPK} - - - - <%=dateFormatDateTime.format(asynchronousProccessAudit.getCreateDate()) %> - - - - - <%=dateFormatDateTime.format(asynchronousProccessAudit.getEndDate())%> - - - - - - - - - - - - - - - + + + +
+ <%@ include file="/html/asynchronousprocessdashboard/search-container.jsp" %> - -
\ No newline at end of file +
diff --git a/docroot/html/courseadmin/admin_actions.jsp b/docroot/html/courseadmin/admin_actions.jsp index 434033e12..7033d08bb 100644 --- a/docroot/html/courseadmin/admin_actions.jsp +++ b/docroot/html/courseadmin/admin_actions.jsp @@ -1,3 +1,8 @@ + +<%@page import="com.liferay.lms.course.adminaction.AdminActionTypeRegistry"%> +<%@page import="com.liferay.lms.course.adminaction.AdminActionType"%> + +<%@page import="com.liferay.lms.service.CourseResultLocalServiceUtil"%> <%@page import="com.liferay.portal.kernel.util.PrefsPropsUtil"%> <%@page import="com.liferay.lms.service.CourseLocalServiceUtil"%> <%@page import="javax.portlet.PortletPreferences"%> @@ -10,7 +15,7 @@ <%@ include file="/init.jsp" %> <% ResultRow row = (ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW); - +SearchContainer searchContainer = (SearchContainer)request.getAttribute("liferay-ui:search:searchContainer"); Course myCourse = (Course)row.getObject(); LmsPrefs prefs=LmsPrefsLocalServiceUtil.getLmsPrefs(themeDisplay.getCompanyId()); String name = Course.class.getName(); @@ -138,21 +143,22 @@ if( permissionChecker.hasPermission(themeDisplay.getScopeGroupId(), Course.clas %> - " message="open-course" url="<%=openURL.toString() %>" /> <%} %> - - - - -<%-- Eliminar Curso --%> +<%-- Eliminar Curso --%> <% -if( permissionChecker.hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(),primKey,ActionKeys.DELETE)&& ! myCourse.isClosed() && showDelete) -{ +if( permissionChecker.hasPermission(themeDisplay.getScopeGroupId(), Course.class.getName(),primKey,ActionKeys.DELETE)&& + ! myCourse.isClosed() && + showDelete && + CourseResultLocalServiceUtil.countFinishedOnlyStudents(myCourse.getCourseId(), myCourse.getCompanyId(), myCourse.getGroupCreatedId(), null, 0)<=0 +){ %> + + + <% } @@ -182,4 +188,21 @@ if( permissionChecker.hasPermission(themeDisplay.getScopeGroupId(), Course.clas + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/docroot/html/courseadmin/editcourse.jsp b/docroot/html/courseadmin/editcourse.jsp index 32d0d3a25..a7c593da0 100644 --- a/docroot/html/courseadmin/editcourse.jsp +++ b/docroot/html/courseadmin/editcourse.jsp @@ -74,24 +74,6 @@ String courseDiplomaError = ParamUtil.getString(request, "courseDiplomaError"); String maxLengthTitle = GetterUtil.getString( ModelHintsUtil.getHints(Group.class.getName(), "name").get("max-length"),""); String courseTitle = ""; - String site = PropsUtil.get("lms.site.types"); - Set sites = new HashSet(); - if(Validator.isNotNull(site)){ - String[] ssites = site.split(","); - for(int i=0;i
@@ -275,7 +257,6 @@ if(course!=null){ if(groupCreated!=null) registrationType = groupCreated.getType(); - %> <% @@ -290,6 +271,7 @@ if(courseType != null){ } %> + @@ -392,13 +374,13 @@ if(courseType != null){ - @@ -739,16 +721,19 @@ if(courseType != null){ inscriptions = ListUtil.toList(StringUtil.split(LmsPrefsLocalServiceUtil.getLmsPrefsIni(themeDisplay.getCompanyId()).getInscriptionTypes(),",",0L)); } InscriptionTypeRegistry inscription = new InscriptionTypeRegistry(); + InscriptionType itype = null; if(inscriptions.size()>1){%> <% for(Long ins:inscriptions){ boolean selected = false; - InscriptionType itype = inscription.getInscriptionType(ins); - if((course == null && PropsUtil.get("lms.inscription.default.type").equals(String.valueOf(ins))) || (course != null && ins == course.getInscriptionType())) + InscriptionType instype = inscription.getInscriptionType(ins); + if((course == null && PropsUtil.get("lms.inscription.default.type").equals(String.valueOf(ins))) || (course != null && ins == course.getInscriptionType())){ selected = true; + itype = instype; + } %> - + <% } %> @@ -757,13 +742,14 @@ if(courseType != null){ <% for(Long ins:inscriptions){ boolean selected = false; - InscriptionType itype = inscription.getInscriptionType(ins); - if(Validator.isNotNull(itype.getSpecificContentPage())){%> -
- + InscriptionType instype = inscription.getInscriptionType(ins); + if(Validator.isNotNull(instype.getSpecificContentPage())){%> +
+ <%if(course != null){ %> <%} %> +
<% @@ -774,12 +760,53 @@ if(courseType != null){ function changeInscriptionType(typeId){ $(".especific_content_page_inscription").addClass("aui-helper-hidden"); $("#especific_content_page_inscription_"+typeId).removeClass("aui-helper-hidden"); + + //Además cambiamos los tipos de inscripción + + $("#group_types").addClass("aui-helper-hidden"); + + $.ajax({ + dataType: 'json', + url:'${searchGroupTypesURL}', + cache:false, + data:{ + inscriptionTypeId : typeId + }, + success: function(data){ + if(data){ + if(data.length>0){ + + var selected = $("#registrationType").val(); + + var options = ''; + + $.each(data, function() { + options+= '