Subversion Repositories bacoAlunos

Rev

Rev 1378 | Rev 1380 | 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
                    {
161
                        1.5.0/docs/api/java/lang/String.html">String msg = "A unidade tem tipologias requisitadas que tem de ser removidas primeiro, iremos remover todas as tipologias e respostas associadas";
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
 
179
    /**
180
     *
181
     */
182
    private void removeTipologiasERespostasCascade(QuestionarioPedagogicoUnidadeCurricularAfeta unidadeAfeta)
183
    {
184
        for(QuestionarioPedagogicoTipologiaRequisitada tr: unidadeAfeta.getTipologiasRequisitadas())
185
        {
186
            logger.warn("deleting: " + tr);
187
            if(tr.getAlunosRequisitados() != null)
188
            {
189
                for(QuestionarioPedagogicoAlunoRequisitado ar: tr.getAlunosRequisitados())
190
                {
191
                    logger.warn("deleting: " + ar);
192
                    if(ar.getRespostaRequisitada() != null)
193
                    {
194
                        logger.warn("deleting: Resposta Requisitada " + ar.getRespostaRequisitada().getId());
195
                        if(ar.getRespostaRequisitada().getResposta() != null)
196
                        {
197
                            logger.warn("deleting resposta: " + ar.getRespostaRequisitada().getResposta());
198
                            DaoFactory.getQuestionarioRespostaDaoImpl().delete(ar.getRespostaRequisitada().getResposta());
199
                            ar.getRespostaRequisitada().setResposta(null);
200
                        }
201
                        DaoFactory.getQuestionarioRespostaRequisitadaDaoImplImpl().delete(ar.getRespostaRequisitada());
202
                        ar.setRespostaRequisitada(null);
203
                    }
204
                    DaoFactory.getQuestionarioPedagogicoAlunoRequisitadoDaoImpl().delete(ar);
205
                }
206
                tr.setAlunosRequisitados(null);
207
            }
208
            DaoFactory.getQuestionarioPedagogicoTipologiaRequisitadaDaoImpl().delete(tr);
209
        }
210
        unidadeAfeta.setTipologiasRequisitadas(null);
211
    }
212
 
213
    /**
214
     *
1333 jmachado 215
     * @return
216
     * @throws Throwable
217
     */
1327 jmachado 218
    @1.5.0/docs/api/java/lang/Override.html">Override
1329 jmachado 219
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable
220
    {
1333 jmachado 221
 
1332 jmachado 222
        DefaultLogMessages logMessages = new DefaultLogMessages();
1329 jmachado 223
        long questionarioId = 1.5.0/docs/api/java/lang/Long.html">Long.parseLong(getParametersMap().get(ServiceJob.JOB_questionario_id_KEY).getObject());
224
        QuestionarioImpl q = (QuestionarioImpl) DaoFactory.getQuestionarioDaoImpl().load(questionarioId);
225
 
1332 jmachado 226
        1.5.0/docs/api/java/lang/String.html">String[] coursesList = deserializeCoursesList(q);
1329 jmachado 227
        //Colocamos já aqui o estado para nao se poder mudar o Ano e o Semestre
228
 
1333 jmachado 229
        /**logging**/
230
        1.5.0/docs/api/java/lang/String.html">String msg = "Starting running service for questionario: " + q.getId() + " - " + q.getiAnswersProcessorClass().getTitle();
231
        serviceLogInfo(msg);
232
        logger.info(msg);
233
        /**logging**/
1332 jmachado 234
 
1333 jmachado 235
        List<String> newCourseCodesList = new ArrayList<String>();
1332 jmachado 236
        int count = 0;
237
        int totalCourses = coursesList.length;
238
        for(1.5.0/docs/api/java/lang/String.html">String courseStrId: coursesList)
1328 jmachado 239
        {
1332 jmachado 240
            count++;
241
            try{
242
                1.5.0/docs/api/java/lang/Long.html">Long courseLong = 1.5.0/docs/api/java/lang/Long.html">Long.parseLong(courseStrId);
243
                /** logging **/
1333 jmachado 244
                msg = "Loading Course BACO ID: " + courseStrId;
1332 jmachado 245
                serviceLogInfo(msg);
246
                logger.info(msg);
247
                /** logging **/
248
 
249
                Course c = DaoFactory.getCourseDaoImpl().load(courseLong);
1333 jmachado 250
                newCourseCodesList.add(c.getCode());
1332 jmachado 251
                /** logging **/
252
                msg = "(" + count + " of " + totalCourses + ")-> Course loaded: " + c.getName() + "(" + c.getCode() + ")";
253
                serviceLogInfo(msg);
254
                logger.info(msg);
255
                /** logging **/
256
 
1333 jmachado 257
                createCursoAfeto(q, c, logMessages);
1332 jmachado 258
 
1333 jmachado 259
                /** COMMIT OPERATION **/
1332 jmachado 260
                setProgress((int)((((float)count)/((float)totalCourses))*100.0f));
261
                commitPartially();
1333 jmachado 262
                DaoFactory.getQuestionarioDaoImpl().update(q);
263
                /** COMMIT OPERATION **/
1332 jmachado 264
            }
265
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
266
            {
267
                logger.error(t,t);
268
                serviceLogError(t.toString(),t);
269
                logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.ERROR,t.toString()));
270
            }
271
 
1328 jmachado 272
        }
1333 jmachado 273
 
274
        removeUnselectedCourses(q, newCourseCodesList);
275
 
276
        /** COMMIT OPERATION **/
1328 jmachado 277
        setProgress(100);
1332 jmachado 278
        commitPartially();
1333 jmachado 279
        DaoFactory.getQuestionarioDaoImpl().update(q);
280
        /** COMMIT OPERATION **/
1328 jmachado 281
 
1333 jmachado 282
 
283
        msg = "Set courses state as " + QuestionarioImpl.SubStatePedagogico.COURSES_ASSIGNED.name();
1332 jmachado 284
        serviceLogInfo(msg);
285
        logger.info(msg);
1329 jmachado 286
        q.setSubStatePedagogicoClass(QuestionarioImpl.SubStatePedagogico.COURSES_ASSIGNED);
287
        commitPartially();
1332 jmachado 288
 
289
        return logMessages;
1327 jmachado 290
    }
1333 jmachado 291
 
292
    /**
293
     *
294
     * @param q
295
     * @param newCourseCodesList
296
     */
297
    private void removeUnselectedCourses(QuestionarioImpl q, List<String> newCourseCodesList) {
298
        /** logging **/
299
        1.5.0/docs/api/java/lang/String.html">String msg = "Removing unselected courses ";
300
        serviceLogInfo(msg);
301
        logger.info(msg);
302
        /** logging **/
303
        List<QuestionarioPedagogicoCursoAfeto> allCoursesInQuestionario =  DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().find(q.getId());
304
        for(QuestionarioPedagogicoCursoAfeto cursoAfeto: allCoursesInQuestionario)
305
        {
306
            if(!newCourseCodesList.contains(cursoAfeto.getCodigoCurso()))
307
            {
308
                removeCursoAfeto(cursoAfeto);
309
            }
310
        }
311
    }
312
 
313
    private void removeCursoAfeto(QuestionarioPedagogicoCursoAfeto cursoAfeto) {
314
        1.5.0/docs/api/java/lang/String.html">String msg; /** logging **/
315
        msg = "Deleting course: " + cursoAfeto.getCodigoCurso();
316
        serviceLogInfo(msg);
317
        logger.info(msg);
318
        /** logging **/
319
        for(QuestionarioPedagogicoUnidadeCurricularAfeta unidade: cursoAfeto.getUnidadesAfetas())
320
        {
321
            /** logging **/
322
            msg = "--->Deleting unit from course: " + unidade.getCodigoUnidade();
323
            serviceLogInfo(msg);
324
            logger.info(msg);
325
            /** logging **/
326
            DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().delete(unidade);
327
        }
328
        cursoAfeto.setUnidadesAfetas(null);
329
        DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().delete(cursoAfeto);
330
    }
331
 
332
    private void removeUnselectedUnits(QuestionarioPedagogicoCursoAfeto cursoAfetado, List<String> newUnidadesCodesList) {
333
        /** logging **/
334
        1.5.0/docs/api/java/lang/String.html">String msg = "Removing unselected units from course: " + cursoAfetado.getCodigoCurso();
335
        serviceLogInfo(msg);
336
        logger.info(msg);
337
        /** logging **/
338
        Set<QuestionarioPedagogicoUnidadeCurricularAfeta> allUnidades =  cursoAfetado.getUnidadesAfetas();
339
        for(QuestionarioPedagogicoUnidadeCurricularAfeta unidadeAfeta: allUnidades)
340
        {
341
            if(!newUnidadesCodesList.contains(unidadeAfeta.getCodigoUnidade()))
342
            {
343
                /** logging **/
344
                msg = "--->Deleting unidade: " + unidadeAfeta.getCodigoUnidade();
345
                serviceLogInfo(msg);
346
                logger.info(msg);
347
                /** logging **/
348
                DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().delete(unidadeAfeta);
349
            }
350
        }
351
    }
352
 
353
 
354
    /**
355
     *
356
     * @param q
357
     * @param c
358
     * @throws IOException
359
     * @throws TransformationException
360
     */
361
    private void createCursoAfeto(QuestionarioImpl q, Course c, DefaultLogMessages logMessages) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException
362
    {
363
        1.5.0/docs/api/java/lang/String.html">String msg;
364
        QuestionarioPedagogicoCursoAfetoImpl cursoAfeto = null;
1335 jmachado 365
        //todo fazer aqui um teste a ver se na lista de unidades found vem as unidades do curso afeto
366
        //reativar o set e testar isso
1333 jmachado 367
        List<QuestionarioPedagogicoCursoAfeto> cursosFound = DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().find(q.getId(),c.getCode());
368
        if(cursosFound != null && cursosFound.size() > 1)
369
        {
370
            msg = "Encontrados mais que um curso nos mesmos códigos:" + c.getCode() + " apagando um";
371
            serviceLogWarn(msg);
372
            logger.warn(msg);
373
            logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.WARNING,msg));
374
            cursoAfeto = (QuestionarioPedagogicoCursoAfetoImpl) cursosFound.get(0);
375
            cursosFound.remove(0);
376
            for(QuestionarioPedagogicoCursoAfeto ca: cursosFound)
377
                removeCursoAfeto(ca);
378
        }
379
        else if(cursosFound != null && cursosFound.size() == 1)
380
        {
381
            msg = "Curso " + c.getCode() + " encontrado, vai atualizar";
382
            serviceLogInfo(msg);
383
            logger.info(msg);
384
            cursoAfeto = (QuestionarioPedagogicoCursoAfetoImpl) cursosFound.get(0);
385
        }
386
        else
387
        {
388
            msg = "Criando novo curso para o código " + c.getCode();
389
            serviceLogInfo(msg);
390
            logger.info(msg);
391
            cursoAfeto = DomainObjectFactory.createQuestionarioPedagogicoCursoAfeto();
392
            DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().save(cursoAfeto);
1335 jmachado 393
            cursoAfeto.setUnidadesAfetas(new HashSet<QuestionarioPedagogicoUnidadeCurricularAfeta>());
1333 jmachado 394
        }
395
 
396
        cursoAfeto.resetStats();
397
 
398
        cursoAfeto.setCourse(c);
1336 jmachado 399
        cursoAfeto.setCodigoInstituicao(c.getInstitutionalCode());
400
        cursoAfeto.setNomeInstituicao(ConfigProperties.getProperty("institution.code."+c.getInstitutionalCode()));
1333 jmachado 401
        cursoAfeto.setAno(q.getYear());
402
        cursoAfeto.setCodigoCurso(c.getCode());
403
        cursoAfeto.setNome(c.getName());
404
        cursoAfeto.setQuestionario(q);
405
        cursoAfeto.setSemestre(q.getSemestre());
406
 
407
 
408
 
1335 jmachado 409
 
1333 jmachado 410
        List<String> newUnitCodesList = new ArrayList<String>();
411
        int countUnits = 0;
412
        List<CourseUnitDaoImpl.CourseUnitResult> results = DaoFactory.getCourseUnitDaoImpl().loadCourseUnits(c.getId(), q.getSemestre(), q.getYear());
413
        int totalUnits =  results.size();
414
        for(CourseUnitDaoImpl.CourseUnitResult cur : results)
415
        {
416
            countUnits++;
417
            CourseUnit cu = DaoFactory.getCourseUnitDaoImpl().load(cur.id);
418
            newUnitCodesList.add(cu.getCode());
419
            /** logging **/
420
            msg = "---->(" + countUnits + " of " + totalUnits  +") CourseUnit loaded: " + cu.getName() + "(" + cu.getCode() + ")";
421
            serviceLogInfo(msg);
422
            logger.info(msg);
423
            /** logging **/
424
            createUnidadeAfeta(cursoAfeto, cur,cu, logMessages);
425
            DaoFactory.getCourseUnitDaoImpl().evict(cu);
426
        }
427
 
428
        removeUnselectedUnits(cursoAfeto,newUnitCodesList);
429
    }
430
 
431
    /**
432
     *
433
     * @param cursoAfeto
434
     * @param cur
435
     * @throws IOException
436
     * @throws TransformationException
437
     */
438
    private void createUnidadeAfeta(QuestionarioPedagogicoCursoAfetoImpl cursoAfeto, CourseUnitDaoImpl.CourseUnitResult cur, CourseUnit cu, DefaultLogMessages logMessages) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
439
 
440
        1.5.0/docs/api/java/lang/String.html">String msg;
441
        QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta = null;
442
        List<QuestionarioPedagogicoUnidadeCurricularAfeta> unidadesFound = DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().find(cursoAfeto.getQuestionario().getId(), cursoAfeto.getCodigoCurso(), cu.getCode());
443
        if(unidadesFound != null && unidadesFound.size() > 1)
444
        {
445
            msg = "Encontradas mais que uma unidade nos mesmos códigos: curso:" +cursoAfeto.getCodigoCurso() + ", unidade " + cu.getCode() + " apagando um";
446
            serviceLogWarn(msg);
447
            logger.warn(msg);
448
            logMessages.addMessage(new DefaultLogMessage("questionario.courses.selection", LogMessageTypeEnum.WARNING,msg));
449
            unidadeAfeta = (QuestionarioPedagogicoUnidadeCurricularAfetaImpl) unidadesFound.get(0);
450
            unidadesFound.remove(0);
451
            DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().delete(unidadesFound);
452
        }
453
        else if(unidadesFound != null && unidadesFound.size() == 1)
454
        {
455
            msg = "Unidade " +  cu.getCode() + " encontrada, vai atualizar";
456
            serviceLogInfo(msg);
457
            logger.info(msg);
458
            unidadeAfeta = (QuestionarioPedagogicoUnidadeCurricularAfetaImpl) unidadesFound.get(0);
459
        }
460
        else
461
        {
462
            msg = "Criando nova unidade para o código " + cu.getCode();
463
            serviceLogInfo(msg);
464
            logger.info(msg);
465
            unidadeAfeta = DomainObjectFactory.createQuestionarioPedagogicoUnidadeCurricularAfeta();
1338 jmachado 466
            unidadeAfeta.setUsar(true);
467
            unidadeAfeta.setVista(false);
1333 jmachado 468
            DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().save(unidadeAfeta);
469
        }
470
 
471
        unidadeAfeta.resetStats();
472
        unidadeAfeta.setCursoAfeto(cursoAfeto);//so metemos de um dos lados
473
        unidadeAfeta.setCourseUnit(cu);
474
        unidadeAfeta.setCodigoUnidade(cu.getCode());
475
        unidadeAfeta.setObs("");
1336 jmachado 476
        unidadeAfeta.setNome(cu.getName());
1333 jmachado 477
 
478
        unidadeAfeta.setMarked(false);
479
 
480
        ArrayList<CourseUnitImpl.Tipologia> mergedTipologias = copiarTipologias(cu, unidadeAfeta);
481
 
482
 
483
        checkTurmaAndProfs(cu, unidadeAfeta, mergedTipologias);
484
        checkProfs(cur, unidadeAfeta);
485
        checkTurmas(cur, unidadeAfeta);
486
        checkStudents(cur, unidadeAfeta);
487
 
1338 jmachado 488
 
1333 jmachado 489
        if(unidadeAfeta.isMarked())
490
            cursoAfeto.incMarcadas();
491
 
492
 
493
    }
494
 
495
    /**
496
     *
497
     * @param cur
498
     * @param unidadeAfeta
499
     */
500
    private void checkTurmas(CourseUnitDaoImpl.CourseUnitResult cur, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) {
501
        if(cur.turmas == 0)
502
        {
503
            unidadeAfeta.setTurmas(0);
504
            unidadeAfeta.setMarked(true); //WARNING
505
            unidadeAfeta.addObs("Não tem turmas");
506
        }
507
        else
508
            unidadeAfeta.setTurmas(cur.turmas);
509
    }
510
 
511
    /**
512
     *
513
     * @param cur
514
     * @param unidadeAfeta
515
     */
516
    private void checkProfs(CourseUnitDaoImpl.CourseUnitResult cur, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) {
517
        if(cur.teachers == 0)
518
        {
519
            unidadeAfeta.setProfs(0);
520
            unidadeAfeta.setMarked(true); //WARNING
521
            unidadeAfeta.addObs("Não tem professores");
522
        }
523
        else
524
            unidadeAfeta.setProfs(cur.teachers);
525
    }
526
 
527
    /**
528
     *
529
     * @param cur
530
     * @param unidadeAfeta
531
     */
532
    private void checkStudents(CourseUnitDaoImpl.CourseUnitResult cur, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) {
533
        if(cur.students == 0)
534
        {
535
            unidadeAfeta.setStudents(0);
536
            unidadeAfeta.setMarked(true); //WARNING
537
            unidadeAfeta.addObs("Não tem estudantes");
538
        }
539
        else
540
            unidadeAfeta.setStudents(cur.students);
541
    }
542
 
543
    /**
544
     *
545
     * @param cu
546
     * @param unidadeAfeta
547
     * @return
548
     * @throws IOException
549
     * @throws TransformationException
550
     */
551
    private ArrayList<CourseUnitImpl.Tipologia> copiarTipologias(CourseUnit cu, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta) throws 1.5.0/docs/api/java/io/IOException.html">IOException, TransformationException {
552
        try
553
        {
554
            CourseUnitImpl.Tipologias tipologias = ((CourseUnitImpl)cu).getTipologiasClass();
555
            ArrayList<CourseUnitImpl.Tipologia> mergedTipologias = tipologias.obtainMergeTipologias();
556
            unidadeAfeta.setTipologias(mergedTipologias.size());
557
            unidadeAfeta.setTipologiasJson(CourseUnitImpl.Tipologias.serializeMergedList(mergedTipologias));
558
            unidadeAfeta.setAddedTipologias(tipologias.getTipologiasExtraAdicionadas().size());
559
            return mergedTipologias;
560
        }
561
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
562
        {
563
            ArrayList<CourseUnitImpl.Tipologia> tipologias = new ArrayList<CourseUnitImpl.Tipologia>();
564
            unidadeAfeta.setMarked(true);
565
            unidadeAfeta.addObs("Erro a descodificar tipologias");
566
            unidadeAfeta.setTipologiasJson(CourseUnitImpl.Tipologias.serializeMergedList(tipologias));
567
            return tipologias;
568
        }
569
    }
570
 
571
    /**
572
     *
573
     * @param cu
574
     * @param unidadeAfeta
575
     * @param mergedTipologias
576
     */
577
    private void checkTurmaAndProfs(CourseUnit cu, QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidadeAfeta, ArrayList<CourseUnitImpl.Tipologia> mergedTipologias) {
578
        if(cu.getTeachers() != null)
579
        {
580
            HashMap<String,Boolean> turmaWithProfs = new HashMap<String, Boolean>();
581
            HashMap<String,Boolean> profsWithTurma = new HashMap<String, Boolean>();
582
            for(CourseUnitImpl.Tipologia t: mergedTipologias)
583
            {
584
                turmaWithProfs.put(t.getCdTurma(),true);
585
                profsWithTurma.put(t.getCdDocente(),true);
586
            }
587
            for(Teacher t: cu.getTeachers())
588
            {
589
                if(profsWithTurma.get(""+t.getSigesCode())==null)
590
                {
591
                    unidadeAfeta.setProfsWithoutTurma(unidadeAfeta.getProfsWithoutTurma()+1);
592
                    unidadeAfeta.setMarked(true);
593
                }
594
                DaoFactory.getTeacherDaoImpl().evict(t);
595
            }
596
 
597
            for(CourseUnitTurma t: cu.getTurmas())
598
            {
599
                if(turmaWithProfs.get(t.getTurma())==null)
600
                {
601
                    unidadeAfeta.setTurmaWithoutProf(unidadeAfeta.getTurmaWithoutProf() + 1);
602
                    unidadeAfeta.setMarked(true);
603
                }
604
                DaoFactory.getCourseUnitTurmaDaoImpl().evict(t);
605
            }
606
        }
607
    }
1337 jmachado 608
 
609
 
610
    /**
611
     * SERVIÇO
612
     * @param questionarioId
613
     * @param cursosAfetos
614
     * @param session
615
     * @param questionarioCleared
616
     * @throws IOException
617
     * @throws TransformationException
618
     * @throws NotAuthorizedException
619
     */
620
    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 {
621
 
622
        if(!questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_TIPOLOGIES.name()))
623
        {
624
            throw new NotAuthorizedException("Nao tem autorização para alterar as tipologias");
625
        }
626
        for(QuestionarioPedagogicoCursoAfeto cursoAfeto: cursosAfetos)
627
        {
628
            QuestionarioPedagogicoCursoAfeto cuAfetoPersistent = DaoFactory.getQuestionarioPedagogicoCursoAfetoDaoImpl().load(cursoAfeto.getId());
629
            if(cuAfetoPersistent.getQuestionario().getId() == questionarioId)
630
            {
631
                cuAfetoPersistent.setUsarTipologias(cursoAfeto.isUsarTipologias());
632
            }
633
            else
634
                logger.warn("Curso pedido no serviço não faz parte do questionario requisitado: " + cursoAfeto.getId() + " " + cursoAfeto.getQuestionario().getId() + " != " + questionarioId);
635
 
636
        }
637
 
638
    }
1338 jmachado 639
 
640
    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 {
641
 
1378 jmachado 642
        if(!questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_ASSIGNEMENTS_CHECK_TEACHERS.name()) &&
643
                !questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_ASSIGNEMENTS.name()) &&
644
                !questionarioCleared.isClear((UserSessionImpl) session,QuestionarioImpl.QuestionarioClearancesOperation.QUESTIONARIO_CHANGE_TIPOLOGIES.name()))
1338 jmachado 645
        {
646
            throw new NotAuthorizedException("Nao tem autorização para alterar as tipologias");
647
        }
648
        QuestionarioPedagogicoUnidadeCurricularAfetaImpl unidade = (QuestionarioPedagogicoUnidadeCurricularAfetaImpl) DaoFactory.getQuestionarioPedagogicoUnidadeCurricularAfetaDaoImpl().load(unidadeAfetaId);
649
        if(op.equals("usar"))
650
        {
651
            unidade.setUsar(1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(val));
652
        }
653
        else if(op.equals("vista"))
654
        {
655
            unidade.setVista(1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(val));
656
        }
1378 jmachado 657
        else if(op.equals("vistaProfs"))
658
        {
659
            unidade.setVistaProfs(1.5.0/docs/api/java/lang/Boolean.html">Boolean.parseBoolean(val));
660
        }
1338 jmachado 661
        else if(op.equals("observacoes"))
662
        {
663
            unidade.setObs(val);
664
        }
665
    }
1378 jmachado 666
 
1327 jmachado 667
}