Subversion Repositories bacoAlunos

Rev

Rev 1312 | Rev 1699 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.services.courseunits;

import org.apache.fop.apps.FOPException;
import org.apache.log4j.Logger;
import pt.estgp.estgweb.domain.*;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.domain.enums.LangEnum;
import pt.estgp.estgweb.domain.views.CourseUnitView;
import pt.estgp.estgweb.domain.views.CourseView;
import pt.estgp.estgweb.services.email.EMAILJob;
import pt.estgp.estgweb.services.email.SendEmailService;
import pt.estgp.estgweb.services.jobs.JobScheduleService;
import pt.estgp.estgweb.utils.AreasBelongUtils;
import pt.estgp.estgweb.utils.CourseViewComparator;
import pt.estgp.estgweb.web.exceptions.NotAuthorizedException;
import pt.utl.ist.berserk.logic.serviceManager.IService;

import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Jorge Machado
 * @date 2/Jun/2008
 * @see pt.estgp.estgweb.services.courseunits
 */

public class DirectedCoordinatedUnitsService implements IService
{
    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(DirectedCoordinatedUnitsService.class);

    public DirectedCoordinatedCourses loadForUserSession(1.5.0/docs/api/java/lang/String.html">String importYear, UserSession userSession)
    {
        return loadForUser(userSession.getUser().getId(),importYear, userSession);
    }

    public DirectedCoordinatedCourses loadForUser(long teacherId, 1.5.0/docs/api/java/lang/String.html">String importYear, UserSession userSession)
    {
        if(importYear == null)
            importYear = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();
        List<Course> directorCourses = DaoFactory.getCourseDaoImpl().loadDirectorCourses(teacherId,importYear);
        List<Course> coordinatorCourses = DaoFactory.getCourseDaoImpl().loadCoordinatedCourses(teacherId,importYear);

        HashMap<Course, Boolean> map = new HashMap<Course, Boolean>();

        DirectedCoordinatedCourses directedCoordinatedCourses = new DirectedCoordinatedCourses();
        directedCoordinatedCourses.setCoordinatedCourses(new ArrayList<CourseView>());
        directedCoordinatedCourses.setDirectedCourses(new ArrayList<CourseView>());
        directedCoordinatedCourses.setMerge(new ArrayList<CourseView>());
        for (Course c : directorCourses)
        {
            CourseView cV = new CourseView(c, true);
            directedCoordinatedCourses.getDirectedCourses().add(cV);
            if (map.get(c) == null)
            {
                directedCoordinatedCourses.getMerge().add(cV);
                map.put(c, true);
            }
        }
        for (Course c : coordinatorCourses)
        {
            CourseView cV = new CourseView(c, true);
            directedCoordinatedCourses.getCoordinatedCourses().add(cV);
            if (map.get(c) == null)
            {
                directedCoordinatedCourses.getMerge().add(cV);
                map.put(c, true);
            }
        }
        java.util.1.5.0/docs/api/java/util/Collections.html">Collections.sort(directedCoordinatedCourses.getMerge(), CourseViewComparator.getInstance());
        fill(directedCoordinatedCourses.getMerge());
        return directedCoordinatedCourses;
    }

//    public DirectedCoordinatedCourses loadForServices(String importYear, UserSession userSession)
//    {
//        if(importYear == null)
//            importYear = DatesUtils.getImportYear();
//        List<Course> courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear);
//
//        List<CourseView> courseViews = new ArrayList<CourseView>();
//        for(Course c : courses)
//        {
//            CourseView cV = new CourseView(c, true);
//            courseViews.add(cV);
//        }
//        fill(courseViews);
//        DirectedCoordinatedCourses directedCoordinatedCourses = new DirectedCoordinatedCourses();
//        directedCoordinatedCourses.setMerge(courseViews);
//        return directedCoordinatedCourses;
//    }

    public DirectedCoordinatedCourses loadForServices(1.5.0/docs/api/java/lang/String.html">String importYear, long courseId, 1.5.0/docs/api/java/lang/String.html">String semestre, 1.5.0/docs/api/java/lang/String.html">String area, TeachersSituationEnum teachersSituationEnum, 1.5.0/docs/api/java/lang/String.html">String institutionCode, UserSession userSession)
    {
        if(importYear == null)
            importYear = DaoFactory.getConfigurationDaoImpl().getInterfaceImportYear();

        DirectedCoordinatedCourses directedCoordinatedCourses;
        if(courseId <= 0)
        {
            directedCoordinatedCourses = new DirectedCoordinatedCourses();
            return directedCoordinatedCourses;
        }

        /**
         * Area and Course Initialization
         */

        if (area == null && userSession.getUser() != null && userSession.getUser() instanceof Teacher)
        {
            SigesUser sigesUser = (SigesUser) userSession.getUser();
            if (sigesUser.getAreasBelong() != null && sigesUser.getAreasBelong().length() > 0)
            {
                area = AreasBelongUtils.getAreasFromSerial(sigesUser.getAreasBelong()).get(0);
            }
        }
        /**
         * If is a student can see only his course
         // ALTERACAO PARA TODOS VEREM TODOS OS PROGRAMAS

         if (userSession.getUser() != null && userSession.getUser() instanceof Student)
         {
         StudentImpl sigesUser = (StudentImpl) userSession.getUser();
         if (sigesUser.getSubscribedUnits() != null && sigesUser.getSubscribedUnits().size() > 0)
         {
         Course course = sigesUser.getSubscribedUnits().iterator().next().getCourse();
         courseId = course.getId();
         }
         }
         */


        List<Course> courses;


        if(courseId > 0)
        {
            courses = new ArrayList<Course>();
            courses.add(DaoFactory.getCourseDaoImpl().get(courseId));
        }
        else
        {
            courses = DaoFactory.getCourseDaoImpl().findAllOrderByName(importYear,area,null);
        }

        List<CourseView> courseViews = new ArrayList<CourseView>();
        for(Course c : courses)
        {
            CourseView cV = new CourseView(c, false);
            courseViews.add(cV);
        }
        fill(courseViews, semestre, importYear, teachersSituationEnum,institutionCode);
        directedCoordinatedCourses = new DirectedCoordinatedCourses();
        directedCoordinatedCourses.setMerge(courseViews);
        directedCoordinatedCourses.setArea(area);
        directedCoordinatedCourses.setCourseId(courseId);

        return directedCoordinatedCourses;
    }

    private void fill(List<CourseView> courseViews)
    {
        for (CourseView cV : courseViews)
        {
            cV.setCourseUnitsWithNoProgramS1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithNoProgramS2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedS1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedS2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedS1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedS2(new ArrayList<CourseUnitView>());
            for (CourseUnitView cUV : cV.getCourseUnits())
            {


                if (cUV.getProgramStreamId() == null)
                {
                    try {
                        ((List<CourseUnitView>)
                                (cV.getClass()
                                        .getMethod("getCourseUnitsWithNoProgram" + cUV.getSemestre())
                                        .invoke(cV)))
                                .add(cUV);
                    } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
                        logger.error(e,e);
                    }
                }
                    /*if (cUV.getSemestre().equals("S1"))
                        cV.getCourseUnitsWithNoProgramS1().add(cUV);
                    else
                        cV.getCourseUnitsWithNoProgramS2().add(cUV);*/

                else if (cUV.isValidProgram())
                {
                    try {
                        ((List<CourseUnitView>)
                                (cV.getClass()
                                        .getMethod("getCourseUnitsWithProgramChecked" + cUV.getSemestre())
                                        .invoke(cV)))
                                .add(cUV);
                    } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
                        logger.error(e,e);
                    }
                }
                    /*if (cUV.getSemestre().equals("S1"))
                        cV.getCourseUnitsWithProgramCheckedS1().add(cUV);
                    else
                        cV.getCourseUnitsWithProgramCheckedS2().add(cUV);*/

                else
                    try {
                        ((List<CourseUnitView>)
                                (cV.getClass()
                                        .getMethod("getCourseUnitsWithProgramNotChecked" + cUV.getSemestre())
                                        .invoke(cV)))
                                .add(cUV);
                    } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
                        logger.error(e,e);
                    }

                /*if (cUV.getSemestre().equals("S1"))
                    cV.getCourseUnitsWithProgramNotCheckedS1().add(cUV);
                else
                    cV.getCourseUnitsWithProgramNotCheckedS2().add(cUV);*/

            }
        }
    }

    private void fill(List<CourseView> courseViews, 1.5.0/docs/api/java/lang/String.html">String  semestre, 1.5.0/docs/api/java/lang/String.html">String importYear, TeachersSituationEnum teachersSituationEnum,1.5.0/docs/api/java/lang/String.html">String institutionCode)
    {
        boolean withTeacher = true;
        boolean withNoTeacher = true;

        if(teachersSituationEnum == TeachersSituationEnum.withNoTeachers)
            withTeacher = false;
        else if(teachersSituationEnum == TeachersSituationEnum.withTeachers)
            withNoTeacher = false;

        for (CourseView cV : courseViews)
        {
            cV.setCourseUnitsWithNoProgramA(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithNoProgramS1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithNoProgramS2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithNoProgramT1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithNoProgramT2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithNoProgramT3(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithNoProgramT4(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedA(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedS1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedS2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedT1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedT2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedT3(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramCheckedT4(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedA(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedS1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedS2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedT1(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedT2(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedT3(new ArrayList<CourseUnitView>());
            cV.setCourseUnitsWithProgramNotCheckedT4(new ArrayList<CourseUnitView>());


            List<CourseUnit> courseUnits = DaoFactory.getCourseUnitDaoImpl().loadCourseUnits(cV.getId(),semestre,importYear,withTeacher,withNoTeacher,institutionCode);
            for (CourseUnit cU : courseUnits)
            {
                CourseUnitView cUV = new CourseUnitView(cU,true,false,false,false);
                if (cUV.getProgramStreamId() == null)
                    try {
                        ((List<CourseUnitView>)
                                (cV.getClass()
                                        .getMethod("getCourseUnitsWithNoProgram" + cUV.getSemestre())
                                        .invoke(cV)))
                                .add(cUV);
                    } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
                        logger.error(e,e);
                    }
                    /*if (cUV.getSemestre().equals("S1"))
                        cV.getCourseUnitsWithNoProgramS1().add(cUV);
                    else
                        cV.getCourseUnitsWithNoProgramS2().add(cUV);*/

                else if (cUV.isValidProgram())
                    try {
                        ((List<CourseUnitView>)
                                (cV.getClass()
                                        .getMethod("getCourseUnitsWithProgramChecked" + cUV.getSemestre())
                                        .invoke(cV)))
                                .add(cUV);
                    } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
                        logger.error(e,e);
                    }
                    /*
                    if (cUV.getSemestre().equals("S1"))
                        cV.getCourseUnitsWithProgramCheckedS1().add(cUV);
                    else
                        cV.getCourseUnitsWithProgramCheckedS2().add(cUV);*/

                else
                    try {
                        ((List<CourseUnitView>)
                                (cV.getClass()
                                        .getMethod("getCourseUnitsWithProgramNotChecked" + cUV.getSemestre())
                                        .invoke(cV)))
                                .add(cUV);
                    } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e) {
                        logger.error(e,e);
                    }
                /*if (cUV.getSemestre().equals("S1"))
                    cV.getCourseUnitsWithProgramNotCheckedS1().add(cUV);
                else
                    cV.getCourseUnitsWithProgramNotCheckedS2().add(cUV);*/

            }
        }
    }

    public DirectedCoordinatedCourses update(DirectedCoordinatedCourses directedCoordinatedCourses, UserSession userSession) throws NotAuthorizedException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, 1.5.0/docs/api/java/io/IOException.html">IOException, FOPException {
        int counter = 0;
        for(CourseView courseView: directedCoordinatedCourses.getMerge())
        {
            if(courseView.getId()>0)
            {
                Course c = DaoFactory.getCourseDaoImpl().load(courseView.getId());
//                if(userSession.getUser().getId() == c.getCoordinator().getId())
                if(courseView.getId() == 2)
                    1.5.0/docs/api/java/lang/System.html">System.out.println(courseView.getValidationRole());

                if(userSession.getUser().isAdmin() ||  userSession.getUser().hasRole("courseValidatePrograms") || userSession.getUser().hasRole(c.getValidationRole())) //NOVO para validação por programas
                {
                    counter+=updateList(courseView.getCourseUnitsWithProgramCheckedA(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramCheckedS1(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramCheckedS2(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramCheckedT1(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramCheckedT2(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramCheckedT3(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramCheckedT4(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramNotCheckedA(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramNotCheckedS1(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramNotCheckedS2(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramNotCheckedT1(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramNotCheckedT2(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramNotCheckedT3(),userSession);
                    counter+=updateList(courseView.getCourseUnitsWithProgramNotCheckedT4(),userSession);
                }
            }
        }
        directedCoordinatedCourses.setUpdated(counter);
        return directedCoordinatedCourses;
    }

    private int updateList(List<CourseUnitView> views, UserSession usession) throws NotAuthorizedException, 1.5.0/docs/api/javax/xml/transform/TransformerException.html">TransformerException, 1.5.0/docs/api/java/io/IOException.html">IOException, FOPException {
        int counter = 0;
        for(CourseUnitView courseUnitView: views)
        {
            if(courseUnitView != null && courseUnitView.getId()>0)
            {
                CourseUnit courseUnit = DaoFactory.getCourseUnitDaoImpl().load(courseUnitView.getId());

                //EVALUATION OPEN BY ADMIN
                if(courseUnitView.isEvaluationOpenByAdmin() != courseUnit.isEvaluationOpenByAdmin())
                    courseUnit.setEvaluationOpenByAdmin(courseUnitView.isEvaluationOpenByAdmin());

                if(courseUnitView.getProgramStreamId() != null && courseUnitView.getProgramStreamId().length() > 0)
                {

                    if(usession.getUser().isAdmin() ||  usession.getUser().hasRole("courseValidatePrograms") || usession.getUser().hasRole(courseUnit.getCourse().getValidationRole()))
                    {
                        if(courseUnit.isValidProgram() != courseUnitView.isValidProgram())
                        {
                            courseUnit.setValidProgram(courseUnitView.isValidProgram());
                            courseUnit.setValidatorUser(usession.getUser());
                            counter++;
                            new SaveCourseUnitProgram().createPdf(courseUnit,null,usession);


                            if(courseUnitView.isValidProgram())
                                sendNotificationsValidadaInterestedPeople(courseUnit,usession);
                            else
                                sendNotificationsEditionInterestedPeople(courseUnit,usession);

                        }
                    }
                    else
                    {
                        throw new NotAuthorizedException("Não pode editar estado da unidade " + courseUnit.getCode());
                    }
                }
            }
        }
        return counter;
    }

    public static void sendNotificationsValidadaInterestedPeople(CourseUnit courseUnit,UserSession u)
    {
        try{
            SendEmailService sendEmailService = new SendEmailService();
            List<String> emails = getEmailJobNotifications(courseUnit);
            EMAILJob emailJob = new EMAILJob(sendEmailService.getUnidadeValidadaEmail(emails,courseUnit,LangEnum.PORTUGUESE));
            JobScheduleService.getInstance().scheduleNow(emailJob,"New Notification EMAIL unit state changed to courseComission and teachers " ,u);
        }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
        {
            logger.error(t,t);
        }
    }

    public static void sendNotificationsEditionInterestedPeople(CourseUnit courseUnit,UserSession u)
    {
        try{
            SendEmailService sendEmailService = new SendEmailService();
            List<String> emails = getEmailJobNotifications(courseUnit);
            EMAILJob emailJob = new EMAILJob(sendEmailService.getUnidadeEdicaoEmail(emails,courseUnit,LangEnum.PORTUGUESE));
            JobScheduleService.getInstance().scheduleNow(emailJob,"New Notification EMAIL unit state changed to courseComission and teachers " ,u);
        }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
        {
            logger.error(t,t);
        }
    }
    public static void sendNotificationsEditedInterestedPeople(CourseUnit courseUnit,UserSession u)
    {
        try{
            SendEmailService sendEmailService = new SendEmailService();
            List<String> emails = getEmailJobNotifications(courseUnit);
            EMAILJob emailJob = new EMAILJob(sendEmailService.getUnidadeEditadaEmail(emails,courseUnit,LangEnum.PORTUGUESE));
            JobScheduleService.getInstance().scheduleNow(emailJob,"New Notification EMAIL unit state changed to courseComission and teachers " ,u);
        }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
        {
            logger.error(t,t);
        }
    }

    public static void sendNotificationsCourseUnitEvaluationEditedInterestedPeople(CourseUnit courseUnit,1.5.0/docs/api/java/lang/String.html">String estado,UserSession u)
    {
        try{
            SendEmailService sendEmailService = new SendEmailService();
            List<String> emails = getEmailJobNotifications(courseUnit);
            EMAILJob emailJob = new EMAILJob(sendEmailService.getRelatorioAvaliacaoUnidadeEditadaEmail(emails,courseUnit,LangEnum.PORTUGUESE,estado));
            JobScheduleService.getInstance().scheduleNow(emailJob,"New Notification EMAIL unit state changed to courseComission and teachers " ,u);
        }catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
        {
            logger.error(t,t);
        }
    }

    public static List<String> getEmailJobNotifications(CourseUnit courseUnit) {

        List<String> emails = new ArrayList<String>();
        for(Teacher t: courseUnit.getTeachers())
        {
            if(t.getEmail() != null)
                emails.add(t.getEmail());
        }
        if(emails == null)
            emails = new ArrayList<String>();
        if(courseUnit.getCourse().getCoordinator() != null && courseUnit.getCourse().getCoordinator().getEmail()!=null)
            emails.add(courseUnit.getCourse().getCoordinator().getEmail());
        if(courseUnit.getResponsableTeacher() != null && courseUnit.getResponsableTeacher().getEmail() != null && !emails.contains(courseUnit.getResponsableTeacher().getEmail()))
        {
            emails.add(courseUnit.getResponsableTeacher().getEmail());
        }
        List<User> courseComission = DaoFactory.getUserDaoImpl().loadRoleUsers(courseUnit.getCourse().getValidationRole());
        for(User cc: courseComission)
        {
            if(cc.getEmail() != null)
                emails.add(cc.getEmail());
        }
        return emails;
    }

    public static enum TeachersSituationEnum
    {
        withTeachers,
        withNoTeachers,
        all;

        public static TeachersSituationEnum parse(1.5.0/docs/api/java/lang/String.html">String situation)
        {
            if(situation == null)
                return all;
            else if(situation.equals("withTeachers"))
                return withTeachers;
            else if(situation.equals("withNoTeachers"))
                return withNoTeachers;
            else
                return all;
        }
    }
}