Subversion Repositories bacoAlunos

Rev

Rev 1395 | Rev 1399 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1327 jmachado 1
package pt.estgp.estgweb.services.questionarios.pedagogico;
2
 
1333 jmachado 3
import com.owlike.genson.TransformationException;
1328 jmachado 4
import org.apache.log4j.Logger;
1327 jmachado 5
import org.json.JSONArray;
1328 jmachado 6
import org.json.JSONException;
1327 jmachado 7
import pt.estgp.estgweb.domain.*;
1328 jmachado 8
import pt.estgp.estgweb.domain.dao.DaoFactory;
1333 jmachado 9
import pt.estgp.estgweb.domain.dao.impl.CourseUnitDaoImpl;
1327 jmachado 10
import pt.estgp.estgweb.services.jobs.JobDeamon;
11
import pt.estgp.estgweb.services.jobs.ServiceJob;
12
import pt.estgp.estgweb.services.logresults.ILogMessages;
1332 jmachado 13
import pt.estgp.estgweb.services.logresults.LogMessageTypeEnum;
14
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessage;
1327 jmachado 15
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessages;
1329 jmachado 16
import pt.estgp.estgweb.services.questionarios.QuestionariosService;
1336 jmachado 17
import pt.estgp.estgweb.utils.ConfigProperties;
1327 jmachado 18
import pt.estgp.estgweb.web.exceptions.NotAuthorizedException;
19
import pt.utl.ist.berserk.logic.serviceManager.IService;
20
 
1333 jmachado 21
import java.io.IOException;
22
import java.util.*;
1327 jmachado 23
 
1328 jmachado 24
 
1327 jmachado 25
/**
26
 * Created by jorgemachado on 22/03/16.
27
 */
28
public class UpdateCoursesAndUnitsJobService extends ServiceJob implements IService
29
{
30
 
1328 jmachado 31
    public 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(UpdateCoursesAndUnitsJobService.class);
32
 
1329 jmachado 33
    //return similar questionarios in same year, semestre and history category
34
    public List<QuestionarioImpl> setAnoSemestre(1.5.0/docs/api/java/lang/String.html">String year, 1.5.0/docs/api/java/lang/String.html">String semestre, long questionarioId, UserSession userSession,QuestionarioImpl questionarioCleared) throws NotAuthorizedException
35
    {
36
        if(questionarioCleared.isClear((UserSessionImpl) userSession,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_SET_ANO_SEMESTRE.name()))
37
        {
38
            questionarioCleared.setYear(year);
39
            questionarioCleared.setSemestre(semestre);
40
            questionarioCleared.setSubStatePedagogicoClass(QuestionarioImpl.SubStatePedagogico.YEAR_SEMESTRE_ASSIGNED);
41
            List<QuestionarioImpl> similar = DaoFactory.getQuestionarioDaoImpl().findAnoSemestre(year, semestre, questionarioCleared.getQuestionarioHistoryDrive().getId());
42
            new QuestionariosService().loadInit(similar);
43
            return similar;
44
        }
45
        else
46
            throw new NotAuthorizedException("Não pode alterar o formulário porque o questionário está num estado avançado");
47
    }
48
 
49
 
1328 jmachado 50
    public 1.5.0/docs/api/java/lang/String.html">String[] deserializeCoursesList(QuestionarioImpl questionario)
51
    {
52
        JobServiceTaskImpl job = questionario.getCourseSelectionTaskId() > 0 ?
53
                (JobServiceTaskImpl) DaoFactory.getJobServiceTaskDaoImpl().load(questionario.getCourseSelectionTaskId()) :
54
                null;
55
        if(job == null)
56
            return new 1.5.0/docs/api/java/lang/String.html">String[0];
57
 
58
        1.5.0/docs/api/java/lang/String.html">String courses = job.getParameter(ServiceJob.JOB_questionario_courseList_KEY).getObject();
1332 jmachado 59
        return deserializeCoursesList(courses);
60
    }
1328 jmachado 61
 
1332 jmachado 62
    public List<Course> getCoursesList(1.5.0/docs/api/java/lang/String.html">String coursesListJson)
63
    {
64
        List<Course> courses = new ArrayList<Course>();
65
        1.5.0/docs/api/java/lang/String.html">String[] courseIds = deserializeCoursesList(coursesListJson);
66
        for(1.5.0/docs/api/java/lang/String.html">String courseId: courseIds)
67
        {
68
            try
69
            {
70
                Course c = DaoFactory.getCourseDaoImpl().load(new 1.5.0/docs/api/java/lang/Long.html">Long(courseId));
71
                courses.add(c);
72
            }
73
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
74
            {
75
                logger.info("Course not found in course list with id:" + courseId);
76
            }
77
        }
78
        return courses;
79
    }
80
 
81
    public 1.5.0/docs/api/java/lang/String.html">String[] deserializeCoursesList(1.5.0/docs/api/java/lang/String.html">String json)
82
    {
1328 jmachado 83
        try {
84
 
1332 jmachado 85
            JSONArray jsonArray = new JSONArray(json);
1328 jmachado 86
            1.5.0/docs/api/java/lang/String.html">String[] coursesList = new 1.5.0/docs/api/java/lang/String.html">String[jsonArray.length()];
87
            for(int i=0;i <jsonArray.length();i++)
88
            {
89
                coursesList[i] = ""+ jsonArray.get(i);
90
            }
91
            return coursesList;
92
        } catch (JSONException e) {
93
            logger.error(e,e);
94
        }
95
        return new 1.5.0/docs/api/java/lang/String.html">String[0];
96
    }
1333 jmachado 97
 
1327 jmachado 98
    public QuestionarioImpl runJobSelectCourses(long questionarioId,1.5.0/docs/api/java/lang/String.html">String[] coursesList,UserSession session,QuestionarioImpl questionarioCleared) throws NotAuthorizedException {
99
 
100
        if(!questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_SCHEDULLE_SELECT_COURSES.name()))
101
        {
102
            throw new NotAuthorizedException("Nao tem autorização para agendar atribuições de cursos");
103
        }
1333 jmachado 104
        ( questionarioCleared).setSubStatePedagogicoClass(QuestionarioImpl.SubStatePedagogico.ASSIGNING_COURSES);
1327 jmachado 105
        JSONArray jsonArray = new JSONArray();
106
        for(1.5.0/docs/api/java/lang/String.html">String sele: coursesList)
107
        {
108
            jsonArray.put(new 1.5.0/docs/api/java/lang/Long.html">Long(sele));
109
        }
110
 
111
        Set<JobServiceTaskParameter> paramsJob = new HashSet<JobServiceTaskParameter>();
112
 
113
        JobServiceTaskParameterImpl paramJobL = DomainObjectFactory.createJobServiceTaskParameterImpl();
114
        paramJobL.setName(ServiceJob.JOB_questionario_courseList_KEY);
115
        paramJobL.setDescription("lista de cursos a associar");
116
        paramJobL.setObject(jsonArray.toString());
117
        paramsJob.add(paramJobL);
118
 
119
 
120
        JobServiceTaskParameterImpl paramJob = DomainObjectFactory.createJobServiceTaskParameterImpl();
121
        paramJob.setName(ServiceJob.JOB_questionario_id_KEY);
122
        paramJob.setDescription("ID do questionário");
123
        paramJob.setObject("" + questionarioId);
124
        paramsJob.add(paramJob);
125
 
126
        JobServiceTask job = JobDeamon.createServiceJob(UpdateCoursesAndUnitsJobService.class, session.getUser(), paramsJob,
127
                "Service: Atribuição de Cursos e Unidades a um questionário Pedagógico");
128
        questionarioCleared.setCourseSelectionTaskId(job.getId());
129
        return questionarioCleared;
130
    }
131
 
1332 jmachado 132
 
1333 jmachado 133
    /**
134
     *
1336 jmachado 135
     * @param questionarioId
136
     * @param session
137
     * @param questionarioCleared
138
     * @throws NotAuthorizedException
139
     *
140
     */
141
    public ILogMessages revertAllAssignments(long questionarioId, UserSession session,QuestionarioImpl questionarioCleared) throws NotAuthorizedException {
142
 
143
        DefaultLogMessages logMessages = new DefaultLogMessages();
144
        if(!questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_REVERT_ALL_ASSIGNEMENTS.name()))
145
        {
146
            throw new NotAuthorizedException("Nao tem autorização para agendar atribuições de cursos");
147
        }
148
        for(QuestionarioPedagogicoCursoAfeto cu : DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().find(questionarioId))
149
        {
150
            int unidades = 0;
151
            if(cu.getUnidadesAfetas() != null)
152
            {
153
                unidades = cu.getUnidadesAfetas().size();
154
                for(QuestionarioPedagogicoUnidadeCurricularAfeta unidadeCurricularAfeta: cu.getUnidadesAfetas())
155
                {
156
                    logger.info("Reverting Unidade Curricular Afeta " + unidadeCurricularAfeta.getCodigoUnidade() + " - " + unidadeCurricularAfeta.getNome());
157
                    unidadeCurricularAfeta.setCursoAfeto(null);
158
                    DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().delete(unidadeCurricularAfeta);
159
                    if(unidadeCurricularAfeta.getTipologiasRequisitadas() != null && unidadeCurricularAfeta.getTipologiasRequisitadas().size() > 0)
160
                    {
1387 jmachado 161
                        1.5.0/docs/api/java/lang/String.html">String msg = "A unidade " + unidadeCurricularAfeta.getCodigoUnidade() + " tem tipologias requisitadas que tem de ser removidas primeiro, iremos remover todas as tipologias e respostas candidatas associadas";
1336 jmachado 162
                        logger.warn(msg);
163
                        logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.WARNING,msg));
164
                        removeTipologiasERespostasCascade(unidadeCurricularAfeta);
165
                    }
166
                }
167
            }
168
            1.5.0/docs/api/java/lang/String.html">String msg = "Removendo curso afeto:" + cu.getNome() + " e " + unidades + " uniades afetas";
169
            logger.info(msg);
170
            logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.INFO,msg));
171
 
172
            cu.setUnidadesAfetas(null);
173
            DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().delete(cu);
174
        }
175
        questionarioCleared.setSubStatePedagogicoClass(QuestionarioImpl.SubStatePedagogico.YEAR_SEMESTRE_ASSIGNED);
176
        return logMessages;
177
    }
178
 
1387 jmachado 179
 
180
    public ILogMessages revertAllRespostasCandidatas(long questionarioId) throws NotAuthorizedException {
181
 
182
        DefaultLogMessages logMessages = new DefaultLogMessages();
183
        1.5.0/docs/api/java/lang/String.html">String msg = "Revertendo respostas candidatas do questionario " + questionarioId;
184
        logger.warn(msg);
185
        serviceLogWarn(msg);
186
 
187
        for(QuestionarioPedagogicoCursoAfeto cu : DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().find(questionarioId))
188
        {
189
            msg = "Revertendo respostas do curso " + cu.getCodigoCurso() + " , iremos remover todas as tipologias e respostas candidatas associadas";
190
            logger.warn(msg);
191
            serviceLogWarn(msg);
1394 jmachado 192
            ((QuestionarioPedagogicoCursoAfetoImpl)cu).resetAnswerStats();
1387 jmachado 193
 
194
            int unidades = 0;
195
            if(cu.getUnidadesAfetas() != null)
196
            {
197
                unidades = cu.getUnidadesAfetas().size();
198
                for(QuestionarioPedagogicoUnidadeCurricularAfeta unidadeCurricularAfeta: cu.getUnidadesAfetas())
199
                {
1394 jmachado 200
                    ((QuestionarioPedagogicoUnidadeCurricularAfetaImpl)unidadeCurricularAfeta).resetAnswerStats();
1387 jmachado 201
                    logger.info("Reverting Respostas Unidade Curricular Afeta " + unidadeCurricularAfeta.getCodigoUnidade() + " - " + unidadeCurricularAfeta.getNome());
202
                    if(unidadeCurricularAfeta.getTipologiasRequisitadas() != null && unidadeCurricularAfeta.getTipologiasRequisitadas().size() > 0)
203
                    {
204
                        msg = "A unidade " + unidadeCurricularAfeta.getCodigoUnidade() + " tem tipologias requisitadas que tem de ser removidas primeiro, iremos remover todas as tipologias e respostas candidatas associadas";
205
                        logger.warn(msg);
206
                        serviceLogWarn(msg);
207
                        logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.WARNING,msg));
208
                        removeTipologiasERespostasCascade(unidadeCurricularAfeta);
209
                    }
210
                }
211
            }
212
            msg = "Removendo curso afeto:" + cu.getNome() + " e " + unidades + " uniades afetas";
213
            logger.info(msg);
214
            serviceLogWarn(msg);
215
            logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.INFO,msg));
216
        }
217
        return logMessages;
218
    }
219
 
1336 jmachado 220
    /**
221
     *
222
     */
1380 jmachado 223
    protected void removeTipologiasERespostasCascade(QuestionarioPedagogicoUnidadeCurricularAfeta unidadeAfeta)
1336 jmachado 224
    {
225
        for(QuestionarioPedagogicoTipologiaRequisitada tr: unidadeAfeta.getTipologiasRequisitadas())
226
        {
227
            logger.warn("deleting: " + tr);
228
            if(tr.getAlunosRequisitados() != null)
229
            {
230
                for(QuestionarioPedagogicoAlunoRequisitado ar: tr.getAlunosRequisitados())
231
                {
232
                    logger.warn("deleting: " + ar);
233
                    if(ar.getRespostaRequisitada() != null)
234
                    {
235
                        logger.warn("deleting: Resposta Requisitada " + ar.getRespostaRequisitada().getId());
236
                        if(ar.getRespostaRequisitada().getResposta() != null)
237
                        {
238
                            logger.warn("deleting resposta: " + ar.getRespostaRequisitada().getResposta());
239
                            DaoFactory.getQuestionarioRespostaDaoImpl().delete(ar.getRespostaRequisitada().getResposta());
240
                            ar.getRespostaRequisitada().setResposta(null);
241
                        }
242
                        DaoFactory.getQuestionarioRespostaRequisitadaDaoImplImpl().delete(ar.getRespostaRequisitada());
243
                        ar.setRespostaRequisitada(null);
244
                    }
245
                    DaoFactory.getQuestionarioPedagogicoAlunoRequisitadoDaoImpl().delete(ar);
246
                }
247
                tr.setAlunosRequisitados(null);
248
            }
249
            DaoFactory.getQuestionarioPedagogicoTipologiaRequisitadaDaoImpl().delete(tr);
250
        }
251
        unidadeAfeta.setTipologiasRequisitadas(null);
252
    }
253
 
254
    /**
255
     *
1333 jmachado 256
     * @return
257
     * @throws Throwable
258
     */
1327 jmachado 259
    @1.5.0/docs/api/java/lang/Override.html">Override
1329 jmachado 260
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable
261
    {
1333 jmachado 262
 
1332 jmachado 263
        DefaultLogMessages logMessages = new DefaultLogMessages();
1329 jmachado 264
        long questionarioId = 1.5.0/docs/api/java/lang/Long.html">Long.parseLong(getParametersMap().get(ServiceJob.JOB_questionario_id_KEY).getObject());
265
        QuestionarioImpl q = (QuestionarioImpl) DaoFactory.getQuestionarioDaoImpl().load(questionarioId);
266
 
1332 jmachado 267
        1.5.0/docs/api/java/lang/String.html">String[] coursesList = deserializeCoursesList(q);
1329 jmachado 268
        //Colocamos já aqui o estado para nao se poder mudar o Ano e o Semestre
269
 
1333 jmachado 270
        /**logging**/
271
        1.5.0/docs/api/java/lang/String.html">String msg = "Starting running service for questionario: " + q.getId() + " - " + q.getiAnswersProcessorClass().getTitle();
272
        serviceLogInfo(msg);
273
        logger.info(msg);
274
        /**logging**/
1332 jmachado 275
 
1387 jmachado 276
        revertAllRespostasCandidatas(questionarioId);
277
 
1333 jmachado 278
        List<String> newCourseCodesList = new ArrayList<String>();
1332 jmachado 279
        int count = 0;
280
        int totalCourses = coursesList.length;
281
        for(1.5.0/docs/api/java/lang/String.html">String courseStrId: coursesList)
1328 jmachado 282
        {
1332 jmachado 283
            count++;
284
            try{
285
                1.5.0/docs/api/java/lang/Long.html">Long courseLong = 1.5.0/docs/api/java/lang/Long.html">Long.parseLong(courseStrId);
286
                /** logging **/
1333 jmachado 287
                msg = "Loading Course BACO ID: " + courseStrId;
1332 jmachado 288
                serviceLogInfo(msg);
289
                logger.info(msg);
290
                /** logging **/
291
 
292
                Course c = DaoFactory.getCourseDaoImpl().load(courseLong);
1333 jmachado 293
                newCourseCodesList.add(c.getCode());
1332 jmachado 294
                /** logging **/
295
                msg = "(" + count + " of " + totalCourses + ")-> Course loaded: " + c.getName() + "(" + c.getCode() + ")";
296
                serviceLogInfo(msg);
297
                logger.info(msg);
298
                /** logging **/
299
 
1333 jmachado 300
                createCursoAfeto(q, c, logMessages);
1332 jmachado 301
 
1333 jmachado 302
                /** COMMIT OPERATION **/
1332 jmachado 303
                setProgress((int)((((float)count)/((float)totalCourses))*100.0f));
304
                commitPartially();
1333 jmachado 305
                DaoFactory.getQuestionarioDaoImpl().update(q);
306
                /** COMMIT OPERATION **/
1332 jmachado 307
            }
308
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
309
            {
310
                logger.error(t,t);
311
                serviceLogError(t.toString(),t);
312
                logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.ERROR,t.toString()));
313
            }
314
 
1328 jmachado 315
        }
1333 jmachado 316
 
317
        removeUnselectedCourses(q, newCourseCodesList);
318
 
319
        /** COMMIT OPERATION **/
1328 jmachado 320
        setProgress(100);
1332 jmachado 321
        commitPartially();
1333 jmachado 322
        DaoFactory.getQuestionarioDaoImpl().update(q);
323
        /** COMMIT OPERATION **/
1328 jmachado 324
 
1333 jmachado 325
 
326
        msg = "Set courses state as " + QuestionarioImpl.SubStatePedagogico.COURSES_ASSIGNED.name();
1332 jmachado 327
        serviceLogInfo(msg);
328
        logger.info(msg);
1329 jmachado 329
        q.setSubStatePedagogicoClass(QuestionarioImpl.SubStatePedagogico.COURSES_ASSIGNED);
330
        commitPartially();
1332 jmachado 331
 
332
        return logMessages;
1327 jmachado 333
    }
1333 jmachado 334
 
335
    /**
336
     *
337
     * @param q
338
     * @param newCourseCodesList
339
     */
340
    private void removeUnselectedCourses(QuestionarioImpl q, List<String> newCourseCodesList) {
341
        /** logging **/
342
        1.5.0/docs/api/java/lang/String.html">String msg = "Removing unselected courses ";
343
        serviceLogInfo(msg);
344
        logger.info(msg);
345
        /** logging **/
346
        List<QuestionarioPedagogicoCursoAfeto> allCoursesInQuestionario =  DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().find(q.getId());
347
        for(QuestionarioPedagogicoCursoAfeto cursoAfeto: allCoursesInQuestionario)
348
        {
349
            if(!newCourseCodesList.contains(cursoAfeto.getCodigoCurso()))
350
            {
351
                removeCursoAfeto(cursoAfeto);
352
            }
353
        }
354
    }
355
 
356
    private void removeCursoAfeto(QuestionarioPedagogicoCursoAfeto cursoAfeto) {
357
        1.5.0/docs/api/java/lang/String.html">String msg; /** logging **/
358
        msg = "Deleting course: " + cursoAfeto.getCodigoCurso();
359
        serviceLogInfo(msg);
360
        logger.info(msg);
361
        /** logging **/
362
        for(QuestionarioPedagogicoUnidadeCurricularAfeta unidade: cursoAfeto.getUnidadesAfetas())
363
        {
364
            /** logging **/
365
            msg = "--->Deleting unit from course: " + unidade.getCodigoUnidade();
366
            serviceLogInfo(msg);
367
            logger.info(msg);
368
            /** logging **/
369
            DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().delete(unidade);
370
        }
371
        cursoAfeto.setUnidadesAfetas(null);
372
        DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().delete(cursoAfeto);
373
    }
374
 
375
    private void removeUnselectedUnits(QuestionarioPedagogicoCursoAfeto cursoAfetado, List<String> newUnidadesCodesList) {
376
        /** logging **/
377
        1.5.0/docs/api/java/lang/String.html">String msg = "Removing unselected units from course: " + cursoAfetado.getCodigoCurso();
378
        serviceLogInfo(msg);
379
        logger.info(msg);
380
        /** logging **/
381
        Set<QuestionarioPedagogicoUnidadeCurricularAfeta> allUnidades =  cursoAfetado.getUnidadesAfetas();
382
        for(QuestionarioPedagogicoUnidadeCurricularAfeta unidadeAfeta: allUnidades)
383
        {
384
            if(!newUnidadesCodesList.contains(unidadeAfeta.getCodigoUnidade()))
385
            {
386
                /** logging **/
387
                msg = "--->Deleting unidade: " + unidadeAfeta.getCodigoUnidade();
388
                serviceLogInfo(msg);
389
                logger.info(msg);
390
                /** logging **/
391
                DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().delete(unidadeAfeta);
392
            }
393
        }
394
    }
395
 
396
 
397
    /**
398
     *
399
     * @param q
400
     * @param c
401
     * @throws IOException
402
     * @throws TransformationException
403
     */
404
    private void createCursoAfeto(QuestionarioImpl q, Course c, DefaultLogMessages logMessages) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException
405
    {
406
        1.5.0/docs/api/java/lang/String.html">String msg;
407
        QuestionarioPedagogicoCursoAfetoImpl cursoAfeto = null;
1335 jmachado 408
        //todo fazer aqui um teste a ver se na lista de unidades found vem as unidades do curso afeto
409
        //reativar o set e testar isso
1333 jmachado 410
        List<QuestionarioPedagogicoCursoAfeto> cursosFound = DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().find(q.getId(),c.getCode());
411
        if(cursosFound != null && cursosFound.size() > 1)
412
        {
413
            msg = "Encontrados mais que um curso nos mesmos códigos:" + c.getCode() + " apagando um";
414
            serviceLogWarn(msg);
415
            logger.warn(msg);
416
            logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.WARNING,msg));
417
            cursoAfeto = (QuestionarioPedagogicoCursoAfetoImpl) cursosFound.get(0);
418
            cursosFound.remove(0);
419
            for(QuestionarioPedagogicoCursoAfeto ca: cursosFound)
420
                removeCursoAfeto(ca);
421
        }
422
        else if(cursosFound != null && cursosFound.size() == 1)
423
        {
424
            msg = "Curso " + c.getCode() + " encontrado, vai atualizar";
425
            serviceLogInfo(msg);
426
            logger.info(msg);
427
            cursoAfeto = (QuestionarioPedagogicoCursoAfetoImpl) cursosFound.get(0);
428
        }
429
        else
430
        {
431
            msg = "Criando novo curso para o código " + c.getCode();
432
            serviceLogInfo(msg);
433
            logger.info(msg);
434
            cursoAfeto = DomainObjectFactory.createQuestionarioPedagogicoCursoAfeto();
435
            DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().save(cursoAfeto);
1335 jmachado 436
            cursoAfeto.setUnidadesAfetas(new HashSet<QuestionarioPedagogicoUnidadeCurricularAfeta>());
1333 jmachado 437
        }
438
 
439
        cursoAfeto.resetStats();
440
 
441
        cursoAfeto.setCourse(c);
1336 jmachado 442
        cursoAfeto.setCodigoInstituicao(c.getInstitutionalCode());
443
        cursoAfeto.setNomeInstituicao(ConfigProperties.getProperty("institution.code."+c.getInstitutionalCode()));
1333 jmachado 444
        cursoAfeto.setAno(q.getYear());
445
        cursoAfeto.setCodigoCurso(c.getCode());
446
        cursoAfeto.setNome(c.getName());
447
        cursoAfeto.setQuestionario(q);
448
        cursoAfeto.setSemestre(q.getSemestre());
449
 
450
 
451
 
1335 jmachado 452
 
1333 jmachado 453
        List<String> newUnitCodesList = new ArrayList<String>();
454
        int countUnits = 0;
455
        List<CourseUnitDaoImpl.CourseUnitResult> results = DaoFactory.getCourseUnitDaoImpl().loadCourseUnits(c.getId(), q.getSemestre(), q.getYear());
456
        int totalUnits =  results.size();
457
        for(CourseUnitDaoImpl.CourseUnitResult cur : results)
458
        {
459
            countUnits++;
460
            CourseUnit cu = DaoFactory.getCourseUnitDaoImpl().load(cur.id);
461
            newUnitCodesList.add(cu.getCode());
462
            /** logging **/
463
            msg = "---->(" + countUnits + " of " + totalUnits  +") CourseUnit loaded: " + cu.getName() + "(" + cu.getCode() + ")";
464
            serviceLogInfo(msg);
465
            logger.info(msg);
466
            /** logging **/
467
            createUnidadeAfeta(cursoAfeto, cur,cu, logMessages);
468
            DaoFactory.getCourseUnitDaoImpl().evict(cu);
469
        }
470
 
471
        removeUnselectedUnits(cursoAfeto,newUnitCodesList);
472
    }
473
 
474
    /**
475
     *
476
     * @param cursoAfeto
477
     * @param cur
478
     * @throws IOException
479
     * @throws TransformationException
480
     */
481
    private void createUnidadeAfeta(QuestionarioPedagogicoCursoAfetoImpl cursoAfeto, CourseUnitDaoImpl.CourseUnitResult cur, CourseUnit cu, DefaultLogMessages logMessages) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
482
 
483
        1.5.0/docs/api/java/lang/String.html">String msg;
484
        QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta = null;
485
        List<QuestionarioPedagogicoUnidadeCurricularAfeta> unidadesFound = DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().find(cursoAfeto.getQuestionario().getId(), cursoAfeto.getCodigoCurso(), cu.getCode());
486
        if(unidadesFound != null && unidadesFound.size() > 1)
487
        {
488
            msg = "Encontradas mais que uma unidade nos mesmos códigos: curso:" +cursoAfeto.getCodigoCurso() + ", unidade " + cu.getCode() + " apagando um";
489
            serviceLogWarn(msg);
490
            logger.warn(msg);
491
            logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.WARNING,msg));
492
            unidadeAfeta = (QuestionarioPedagogicoUnidadeCurricularAfetaImpl) unidadesFound.get(0);
493
            unidadesFound.remove(0);
494
            DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().delete(unidadesFound);
495
        }
496
        else if(unidadesFound != null && unidadesFound.size() == 1)
497
        {
498
            msg = "Unidade " +  cu.getCode() + " encontrada, vai atualizar";
499
            serviceLogInfo(msg);
500
            logger.info(msg);
501
            unidadeAfeta = (QuestionarioPedagogicoUnidadeCurricularAfetaImpl) unidadesFound.get(0);
502
        }
503
        else
504
        {
505
            msg = "Criando nova unidade para o código " + cu.getCode();
506
            serviceLogInfo(msg);
507
            logger.info(msg);
508
            unidadeAfeta = DomainObjectFactory.createQuestionarioPedagogicoUnidadeCurricularAfeta();
1338 jmachado 509
            unidadeAfeta.setUsar(true);
510
            unidadeAfeta.setVista(false);
1333 jmachado 511
            DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().save(unidadeAfeta);
512
        }
513
 
514
        unidadeAfeta.resetStats();
515
        unidadeAfeta.setCursoAfeto(cursoAfeto);//so metemos de um dos lados
516
        unidadeAfeta.setCourseUnit(cu);
517
        unidadeAfeta.setCodigoUnidade(cu.getCode());
1396 jmachado 518
        unidadeAfeta.addObs("");
1336 jmachado 519
        unidadeAfeta.setNome(cu.getName());
1333 jmachado 520
 
521
        unidadeAfeta.setMarked(false);
522
 
523
        ArrayList<CourseUnitImpl.Tipologia> mergedTipologias = copiarTipologias(cu, unidadeAfeta);
524
 
525
 
526
        checkTurmaAndProfs(cu, unidadeAfeta, mergedTipologias);
527
        checkProfs(cur, unidadeAfeta);
528
        checkTurmas(cur, unidadeAfeta);
529
        checkStudents(cur, unidadeAfeta);
530
 
1338 jmachado 531
 
1333 jmachado 532
        if(unidadeAfeta.isMarked())
533
            cursoAfeto.incMarcadas();
534
 
535
 
536
    }
537
 
538
    /**
539
     *
540
     * @param cur
541
     * @param unidadeAfeta
542
     */
543
    private void checkTurmas(CourseUnitDaoImpl.CourseUnitResult cur, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) {
544
        if(cur.turmas == 0)
545
        {
546
            unidadeAfeta.setTurmas(0);
547
            unidadeAfeta.setMarked(true); //WARNING
548
            unidadeAfeta.addObs("Não tem turmas");
549
        }
550
        else
551
            unidadeAfeta.setTurmas(cur.turmas);
552
    }
553
 
554
    /**
555
     *
556
     * @param cur
557
     * @param unidadeAfeta
558
     */
559
    private void checkProfs(CourseUnitDaoImpl.CourseUnitResult cur, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) {
560
        if(cur.teachers == 0)
561
        {
562
            unidadeAfeta.setProfs(0);
563
            unidadeAfeta.setMarked(true); //WARNING
564
            unidadeAfeta.addObs("Não tem professores");
565
        }
566
        else
567
            unidadeAfeta.setProfs(cur.teachers);
568
    }
569
 
570
    /**
571
     *
572
     * @param cur
573
     * @param unidadeAfeta
574
     */
575
    private void checkStudents(CourseUnitDaoImpl.CourseUnitResult cur, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) {
576
        if(cur.students == 0)
577
        {
578
            unidadeAfeta.setStudents(0);
579
            unidadeAfeta.setMarked(true); //WARNING
580
            unidadeAfeta.addObs("Não tem estudantes");
581
        }
582
        else
583
            unidadeAfeta.setStudents(cur.students);
584
    }
585
 
586
    /**
587
     *
588
     * @param cu
589
     * @param unidadeAfeta
590
     * @return
591
     * @throws IOException
592
     * @throws TransformationException
593
     */
594
    private ArrayList<CourseUnitImpl.Tipologia> copiarTipologias(CourseUnit cu, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
595
        try
596
        {
597
            CourseUnitImpl.Tipologias tipologias = ((CourseUnitImpl)cu).getTipologiasClass();
598
            ArrayList<CourseUnitImpl.Tipologia> mergedTipologias = tipologias.obtainMergeTipologias();
599
            unidadeAfeta.setTipologias(mergedTipologias.size());
600
            unidadeAfeta.setTipologiasJson(CourseUnitImpl.Tipologias.serializeMergedList(mergedTipologias));
601
            unidadeAfeta.setAddedTipologias(tipologias.getTipologiasExtraAdicionadas().size());
602
            return mergedTipologias;
603
        }
604
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
605
        {
606
            ArrayList<CourseUnitImpl.Tipologia> tipologias = new ArrayList<CourseUnitImpl.Tipologia>();
607
            unidadeAfeta.setMarked(true);
608
            unidadeAfeta.addObs("Erro a descodificar tipologias");
609
            unidadeAfeta.setTipologiasJson(CourseUnitImpl.Tipologias.serializeMergedList(tipologias));
610
            return tipologias;
611
        }
612
    }
613
 
614
    /**
615
     *
616
     * @param cu
617
     * @param unidadeAfeta
618
     * @param mergedTipologias
619
     */
620
    private void checkTurmaAndProfs(CourseUnit cu, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta, ArrayList<CourseUnitImpl.Tipologia> mergedTipologias) {
621
        if(cu.getTeachers() != null)
622
        {
623
            HashMap<String,Boolean> turmaWithProfs = new HashMap<String, Boolean>();
624
            HashMap<String,Boolean> profsWithTurma = new HashMap<String, Boolean>();
625
            for(CourseUnitImpl.Tipologia t: mergedTipologias)
626
            {
627
                turmaWithProfs.put(t.getCdTurma(),true);
628
                profsWithTurma.put(t.getCdDocente(),true);
629
            }
630
            for(Teacher t: cu.getTeachers())
631
            {
632
                if(profsWithTurma.get(""+t.getSigesCode())==null)
633
                {
634
                    unidadeAfeta.setProfsWithoutTurma(unidadeAfeta.getProfsWithoutTurma()+1);
635
                    unidadeAfeta.setMarked(true);
636
                }
637
                DaoFactory.getTeacherDaoImpl().evict(t);
638
            }
639
 
640
            for(CourseUnitTurma t: cu.getTurmas())
641
            {
642
                if(turmaWithProfs.get(t.getTurma())==null)
643
                {
644
                    unidadeAfeta.setTurmaWithoutProf(unidadeAfeta.getTurmaWithoutProf() + 1);
645
                    unidadeAfeta.setMarked(true);
646
                }
647
                DaoFactory.getCourseUnitTurmaDaoImpl().evict(t);
648
            }
649
        }
650
    }
1337 jmachado 651
 
652
 
653
    /**
654
     * SERVIÇO
655
     * @param questionarioId
656
     * @param cursosAfetos
657
     * @param session
658
     * @param questionarioCleared
659
     * @throws IOException
660
     * @throws TransformationException
661
     * @throws NotAuthorizedException
662
     */
663
    public void updateTipologiasPedagogico(long questionarioId, List<QuestionarioPedagogicoCursoAfeto> cursosAfetos, UserSession session,QuestionarioImpl questionarioCleared) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException, NotAuthorizedException {
664
 
665
        if(!questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_TIPOLOGIES.name()))
666
        {
667
            throw new NotAuthorizedException("Nao tem autorização para alterar as tipologias");
668
        }
669
        for(QuestionarioPedagogicoCursoAfeto cursoAfeto: cursosAfetos)
670
        {
671
            QuestionarioPedagogicoCursoAfeto cuAfetoPersistent = DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().load(cursoAfeto.getId());
672
            if(cuAfetoPersistent.getQuestionario().getId() == questionarioId)
673
            {
674
                cuAfetoPersistent.setUsarTipologias(cursoAfeto.isUsarTipologias());
675
            }
676
            else
677
                logger.warn("Curso pedido no serviço não faz parte do questionario requisitado: " + cursoAfeto.getId() + " " + cursoAfeto.getQuestionario().getId() + " != " + questionarioId);
678
 
679
        }
680
 
681
    }
1338 jmachado 682
 
683
    public void updateCheckVarPedagogico(long questionarioId,long unidadeAfetaId, 1.5.0/docs/api/java/lang/String.html">String op,1.5.0/docs/api/java/lang/String.html">String val,UserSession session, QuestionarioImpl questionarioCleared) throws NotAuthorizedException {
684
 
1395 jmachado 685
        if(!questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_ASSIGNEMENTS_USE_UNIT.name()) &&
686
                !questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_ASSIGNEMENTS_CHECK_TEACHERS.name()) &&
1378 jmachado 687
                !questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_ASSIGNEMENTS.name()) &&
688
                !questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_TIPOLOGIES.name()))
1338 jmachado 689
        {
690
            throw new NotAuthorizedException("Nao tem autorização para alterar as tipologias");
691
        }
692
        QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidade = (QuestionarioPedagogicoUnidadeCurricularAfetaImpl) DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().load(unidadeAfetaId);
693
        if(op.equals("usar"))
694
        {
695
            unidade.setUsar(1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(val));
696
        }
697
        else if(op.equals("vista"))
698
        {
699
            unidade.setVista(1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(val));
700
        }
1378 jmachado 701
        else if(op.equals("vistaProfs"))
702
        {
703
            unidade.setVistaProfs(1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(val));
704
        }
1338 jmachado 705
        else if(op.equals("observacoes"))
706
        {
707
            unidade.setObs(val);
708
        }
709
    }
1378 jmachado 710
 
1327 jmachado 711
}