Subversion Repositories bacoAlunos

Rev

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

Rev Author Line No. Line
116 jmachado 1
package pt.estgp.estgweb.services.sigesimports;
2
 
333 jmachado 3
import jomm.dao.impl.AbstractDao;
4
import org.apache.log4j.Logger;
996 jmachado 5
import org.hibernate.HibernateException;
6
import org.hibernate.StaleStateException;
1814 jmachado 7
import pt.estgp.estgweb.utils.Globals;
996 jmachado 8
import pt.estgp.estgweb.domain.*;
333 jmachado 9
import pt.estgp.estgweb.domain.dao.DaoFactory;
10
import pt.estgp.estgweb.services.common.CommonServicesManager;
863 jmachado 11
import pt.estgp.estgweb.services.email.SendEmailService;
116 jmachado 12
import pt.estgp.estgweb.services.expceptions.ServiceException;
996 jmachado 13
import pt.estgp.estgweb.services.jobs.ServiceJob;
333 jmachado 14
import pt.estgp.estgweb.services.logresults.ILogMessages;
15
import pt.estgp.estgweb.services.logresults.LogMessageTypeEnum;
16
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessage;
165 jmachado 17
import pt.estgp.estgweb.services.logresults.impl.DefaultLogMessages;
1553 jmachado 18
import pt.estgp.estgweb.services.sigesimports.oracle.dao.AlunoDao;
1246 jmachado 19
import pt.estgp.estgweb.services.sigesimports.oracle.dao.DocenteDao;
1270 jmachado 20
import pt.estgp.estgweb.services.sigesimports.oracle.dao.connection.ConnectionManager;
1246 jmachado 21
import pt.estgp.estgweb.services.sigesimports.oracle.domain.Disciplina;
22
import pt.estgp.estgweb.services.sigesimports.oracle.domain.Docente;
1553 jmachado 23
import pt.estgp.estgweb.services.sigesimports.oracle.domain.Nacionalidade;
863 jmachado 24
import pt.estgp.estgweb.utils.ConfigProperties;
25
import pt.estgp.estgweb.utils.Email;
333 jmachado 26
import pt.utl.ist.berserk.logic.serviceManager.IService;
116 jmachado 27
 
1270 jmachado 28
import java.sql.Connection;
863 jmachado 29
import java.util.*;
116 jmachado 30
 
31
/**
32
 * @author Jorge Machado
33
 * @date 11/May/2008
34
 * @time 12:51:32
35
 * @see pt.estgp.estgweb
36
 */
996 jmachado 37
public class ImportTeachersService extends ServiceJob implements IService
116 jmachado 38
{
39
 
40
    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(ImportTeachersService.class);
41
 
1076 jmachado 42
    private static final int MAX_COMMIT = 20;
996 jmachado 43
 
44
    //int studentsMerged = 0;
45
    int teachersNew = 0;
46
    int teachersZeroUnits = 0;
47
    int unitsNotFound = 0;
1226 jmachado 48
    int unitsNotFoundCourseNotFound = 0;
1244 jmachado 49
    int unitsFoundForCourseNotFoundMult = 0;
50
    int unitsFoundForCourseNotFoundSingle = 0;
51
    int unitsDuplicated = 0;
996 jmachado 52
    int unitsAddedToTeachers = 0;
53
    int unitsRemovedToTeachers = 0;
54
    int unitsLocalAddedNotRemoved = 0;
55
    int teachersFound = 0;
56
    int teachersChangeBI = 0;
57
    int unitsLocallyRemovedNotAdded = 0;
1312 jmachado 58
    int professoresDesaparecidosDoSigesNesteAno = 0;
1315 jmachado 59
    int cursosFicticios = 0;
996 jmachado 60
 
61
 
1315 jmachado 62
 
1312 jmachado 63
    public ILogMessages run(1.5.0/docs/api/java/lang/String.html">String year,int institutionCode) throws ServiceException
116 jmachado 64
    {
996 jmachado 65
 
66
        teachersNew = 0;
67
        teachersZeroUnits = 0;
68
        unitsNotFound = 0;
1226 jmachado 69
        unitsNotFoundCourseNotFound = 0;
1244 jmachado 70
        unitsFoundForCourseNotFoundMult = 0;
71
        unitsFoundForCourseNotFoundSingle = 0;
72
        unitsDuplicated = 0;
996 jmachado 73
        unitsAddedToTeachers = 0;
74
        unitsRemovedToTeachers = 0;
75
        unitsLocalAddedNotRemoved = 0;
76
        teachersFound = 0;
77
        teachersChangeBI = 0;
78
        unitsLocallyRemovedNotAdded = 0;
1315 jmachado 79
        cursosFicticios = 0;
996 jmachado 80
 
81
        1.5.0/docs/api/java/lang/String.html">String msgS = "STARTING TEACHERS IMPORT SERVICE FOR YEAR: " + year;
82
        serviceLogInfo(msgS);
83
        logger.info(msgS);
84
 
165 jmachado 85
        DefaultLogMessages logMessages = new DefaultLogMessages();
1312 jmachado 86
        logMessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.INFO, "instituicao " + institutionCode));
996 jmachado 87
 
165 jmachado 88
        try
116 jmachado 89
        {
1312 jmachado 90
            List<Integer> codigosDocentes = DocenteDao.getInstance().loadCodigosDocentes(institutionCode, year);
996 jmachado 91
 
1312 jmachado 92
            /**
1315 jmachado 93
             * Este método vai procurar processores no BACO neste ano que não vieram do SIGES
94
             * Os professores que não vieram da extração do SIGES e terão de ser consistidos
1312 jmachado 95
             * pois as suas unidades ter desaparecido todas de uma vez e vão aqui ficar penduradas
96
             * Se foram adicionadas manualmente então nao serao removidas
97
             */
98
            removerUnidadesDosDesaparecidosDoSiges(year, institutionCode, codigosDocentes);
99
 
1270 jmachado 100
            1.5.0/docs/api/java/sql/Connection.html">Connection conn = ConnectionManager.openConnection();
1553 jmachado 101
 
102
            HashMap<Integer,Nacionalidade> nacionalidades = AlunoDao.getInstance().loadNacionalidades(conn);
103
 
996 jmachado 104
            int i = 1;
1246 jmachado 105
            for (1.5.0/docs/api/java/lang/Integer.html">Integer c : codigosDocentes)
165 jmachado 106
            {
996 jmachado 107
                teachersFound++;
108
                if (i++ > MAX_COMMIT)
109
                {
110
                    i = 0;
1246 jmachado 111
                    setProgress((int) (((float)teachersFound)/((float)codigosDocentes.size())*100.0f));
1312 jmachado 112
                    conn.close();
1076 jmachado 113
                    commitPartially();
1312 jmachado 114
                    conn = ConnectionManager.openConnection();
996 jmachado 115
                }
1312 jmachado 116
                logger.info("Starting import Funcionario: SIGES:" + c);
996 jmachado 117
 
1312 jmachado 118
                Docente d = DocenteDao.getInstance().load(c, institutionCode, year,conn);
996 jmachado 119
 
1312 jmachado 120
                /******Logging****/
892 jmachado 121
                logger.info("Codigo Funcionario Importado: SIGES(" + d.getCodigoFuncionario().intValue() + ") email IPP SIGES: " + d.getEmail());
1253 jmachado 122
                serviceLogInfo("Codigo Funcionario Importado: SIGES(" + d.getCodigoFuncionario().intValue() + ") email IPP SIGES: " + d.getEmail());
894 jmachado 123
                logger.info("SIGES IMPORTED INFO: " + docenteToString(d));
1253 jmachado 124
                serviceLogInfo("SIGES IMPORTED INFO: " + docenteToString(d));
1312 jmachado 125
                /******Logging****/
126
 
127
                Teacher t = DaoFactory.getTeacherDaoImpl().loadBySigesCode(d.getCodigoFuncionario().intValue());
128
 
223 jmachado 129
                boolean newUser = false;
165 jmachado 130
                if (t == null)
131
                {
1312 jmachado 132
                    /******Logging****/
996 jmachado 133
                    msgS = "Teacher does not exist in baco, will create SIGES:" + d.getCodigoFuncionario().intValue();
134
                    logger.info(msgS);
135
                    serviceLogInfo(msgS);
1312 jmachado 136
                    /******Logging****/
996 jmachado 137
 
165 jmachado 138
                    t = DomainObjectFactory.createTeacherImpl();
139
                    DaoFactory.getTeacherDaoImpl().save(t);
223 jmachado 140
                    newUser = true;
1226 jmachado 141
                    //teachersNew++;
165 jmachado 142
                }
892 jmachado 143
                else
144
                {
1312 jmachado 145
                    /******Logging****/
996 jmachado 146
                    msgS = "Teacher EXIST in baco with SIGES: " + d.getCodigoFuncionario().intValue();
147
                    logger.info(msgS);
148
                    //serviceLogInfo(msgS);  //NOT NEED EXCESS OF INFORMATION
1312 jmachado 149
                    /******Logging****/
892 jmachado 150
                }
1312 jmachado 151
 
152
                /******Logging****/
996 jmachado 153
                msgS = "Will persist SIGES(" + d.getCodigoFuncionario().intValue() + ")  baco (username:" + t.getUsername() + ") baco name:" + t.getName();
154
                logger.info(msgS);
155
                serviceLogInfo(msgS);
1312 jmachado 156
                /******Logging****/
157
 
332 jmachado 158
                try
159
                {
1553 jmachado 160
                    persist(d, t, newUser,year,logMessages,institutionCode,nacionalidades);
332 jmachado 161
                }
162
                catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
163
                {
164
                    logger.error(e, e);
165
                    throw e;
166
                }
1312 jmachado 167
 
168
                newUserSystemAdvise(t, newUser);
165 jmachado 169
            }
1270 jmachado 170
            conn.close();
996 jmachado 171
 
116 jmachado 172
        }
996 jmachado 173
        catch(StaleStateException e)
174
        {
175
            AbstractDao.getCurrentSession().getTransaction().rollback();
176
            AbstractDao.getCurrentSession().beginTransaction();
1312 jmachado 177
            /******Logging****/
996 jmachado 178
            logger.error(e,e);
179
            serviceLogError("Rolling back will lost previous updates: " + e.toString(),e);
1000 jmachado 180
            sendNotificationAdmin("Erro de importacao de docentes",e.toString());
1312 jmachado 181
            /******Logging****/
996 jmachado 182
        }
183
        catch(HibernateException e)
184
        {
185
            AbstractDao.getCurrentSession().getTransaction().rollback();
186
            AbstractDao.getCurrentSession().beginTransaction();
1312 jmachado 187
            /******Logging****/
996 jmachado 188
            logger.error(e,e);
189
            serviceLogError("Rolling back will lost previous updates: " + e.toString(),e);
190
            sendNotificationAdmin("Erro de base de dados importacao de docentes, provavelmente chave errada, corrigir no MySql",e.toString());
1312 jmachado 191
            /******Logging****/
996 jmachado 192
        }
165 jmachado 193
        catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
194
        {
1312 jmachado 195
            /******Logging****/
165 jmachado 196
            logMessages.addMessage(new DefaultLogMessage("import.error", e.toString(), "see log for details", LogMessageTypeEnum.ERROR));
197
            logger.error(e, e);
1312 jmachado 198
            /******Logging****/
165 jmachado 199
            throw new ServiceException(e.toString(), e);
200
        }
996 jmachado 201
 
1024 jmachado 202
 
203
 
204
 
205
 
1312 jmachado 206
        /******Logging****/
996 jmachado 207
        serviceLogInfo("############################");
208
        serviceLogInfo("############################");
209
        serviceLogInfo("#Teachers found: " + teachersFound);
210
        serviceLogInfo("#Teachers New: " + teachersNew);
211
        serviceLogInfo("#Teachers Zero Units: " + teachersZeroUnits);
212
        serviceLogInfo("#Units not found: " + unitsNotFound);
1226 jmachado 213
        serviceLogInfo("#Units with NULL COURSE : " + unitsNotFoundCourseNotFound);
1244 jmachado 214
        serviceLogInfo("#Units added to one possible course because NULL COURSE : " + unitsFoundForCourseNotFoundSingle);
215
        serviceLogInfo("#Units added to multiple possible courses because NULL COURSE : " + unitsFoundForCourseNotFoundMult);
216
        serviceLogInfo("#Units duplicated : " + unitsDuplicated);
996 jmachado 217
        serviceLogInfo("#Units removed to Teachers: " + unitsRemovedToTeachers);
218
        serviceLogInfo("#Units added to Teachers: " + unitsAddedToTeachers);
219
        serviceLogInfo("#Units not Removed because localy added: " + unitsLocalAddedNotRemoved);
220
        serviceLogInfo("#Units not Added because localy removed: " + unitsLocallyRemovedNotAdded);
1312 jmachado 221
        if(professoresDesaparecidosDoSigesNesteAno > 0)
222
        {
223
            serviceLogInfo("########!!!!!!!Professores que desapareceram do Siges neste ano e tinham cadeiras no BACO: " + professoresDesaparecidosDoSigesNesteAno);
224
        }
225
        else
226
        {
227
            serviceLogInfo("CHECK DESAPARECIDOS OK - Não existem professores desaparecidos");
228
        }
1315 jmachado 229
        if(cursosFicticios > 0)
230
        {
231
            serviceLogInfo("#######Cursos Ficticios Encontrados (SITUACAO NAO PREVISTA):" + cursosFicticios);
232
        }
996 jmachado 233
 
1025 jmachado 234
        logger.info("############################");
235
        logger.info("############################");
236
        logger.info("#Teachers found: " + teachersFound);
237
        logger.info("#Teachers New: " + teachersNew);
238
        logger.info("#Teachers Zero Units: " + teachersZeroUnits);
239
        logger.info("#Units not found: " + unitsNotFound);
1226 jmachado 240
        logger.info("#Units with NULL COURSE : " + unitsNotFoundCourseNotFound);
1244 jmachado 241
        logger.info("#Units added to one possible course because NULL COURSE : " + unitsFoundForCourseNotFoundSingle);
242
        logger.info("#Units added to multiple possible courses because NULL COURSE : " + unitsFoundForCourseNotFoundMult);
243
        logger.info("#Units duplicated : " + unitsDuplicated);
1025 jmachado 244
        logger.info("#Units removed to Teachers: " + unitsRemovedToTeachers);
245
        logger.info("#Units added to Teachers: " + unitsAddedToTeachers);
246
        logger.info("#Units not Removed because localy added: " + unitsLocalAddedNotRemoved);
247
        logger.info("#Units not Added because localy removed: " + unitsLocallyRemovedNotAdded);
1312 jmachado 248
        if(professoresDesaparecidosDoSigesNesteAno > 0)
249
        {
250
            logger.info("########!!!!!!!Professores que desapareceram do Siges neste ano e tinham cadeiras no BACO: " + professoresDesaparecidosDoSigesNesteAno);
251
        }
252
        else
253
        {
254
            logger.info("CHECK DESAPARECIDOS OK - Não existem professores desaparecidos");
255
        }
1315 jmachado 256
        if(cursosFicticios > 0)
257
        {
258
            logger.info("#######Cursos Ficticios Encontrados (SITUACAO NAO PREVISTA):" + cursosFicticios);
259
        }
1025 jmachado 260
 
996 jmachado 261
        if(teachersChangeBI>0)
262
        {
263
            serviceLogInfo("#>>>>>AVISO AVISO<<<<<<<<<: ");
264
            serviceLogInfo("#>>>>>AVISO AVISO<<<<<<<<<: ");
265
            serviceLogInfo("#>>>>>NUMEROS DE PROFESSORES MUDARAM DE BI<<<<<<<<<: CONSULTAR LOG");
266
            serviceLogInfo("#CODIGO SIGES COM BIs DIFERENTES:" + teachersChangeBI);
1025 jmachado 267
 
268
            logger.info("#>>>>>AVISO AVISO<<<<<<<<<: ");
269
            logger.info("#>>>>>AVISO AVISO<<<<<<<<<: ");
270
            logger.info("#>>>>>NUMEROS DE PROFESSORES MUDARAM DE BI<<<<<<<<<: CONSULTAR LOG");
271
            logger.info("#CODIGO SIGES COM BIs DIFERENTES:" + teachersChangeBI);
996 jmachado 272
        }
273
        setProgress(100);
274
 
165 jmachado 275
        logMessages.addMessage(new DefaultLogMessage("import.teachers.terminating", LogMessageTypeEnum.INFO));
276
        logger.info("terminating teacher import");
996 jmachado 277
        serviceLogInfo("terminating teacher import");
1312 jmachado 278
        /******Logging****/
165 jmachado 279
        return logMessages;
116 jmachado 280
    }
281
 
996 jmachado 282
 
1312 jmachado 283
 
116 jmachado 284
    /**
1312 jmachado 285
     * Este métido vai consistir os alunos que não eram tratados porque não vinham do SIGES logo não constavam do
286
     * ciclo
287
     * @param year
288
     * @param institutionCode
289
     * @param codigos
290
     */
1399 jmachado 291
    private void  removerUnidadesDosDesaparecidosDoSiges(1.5.0/docs/api/java/lang/String.html">String year, int institutionCode, List<Integer> codigos) {
1312 jmachado 292
        1.5.0/docs/api/java/lang/String.html">String msgS;
293
        List<Integer> codesInBaco = DaoFactory.getTeacherDaoImpl().findAllSigesCodesYear(year,institutionCode);
294
        codesInBaco.removeAll(codigos);
295
 
296
        if(codesInBaco.size() > 0)
297
        {
298
            msgS = "Existem professores no BACO que não estao no SIGES no ano: " + year + " institution:" + institutionCode + " possiveis adicionados manualmente, confirmar";
299
            serviceLogWarn(msgS);
300
            logger.warn(msgS);
301
            msgS = "";
302
            for (1.5.0/docs/api/java/lang/Integer.html">Integer c : codesInBaco)
303
            {
304
                msgS+=c + ", ";
305
            }
306
            serviceLogWarn(msgS);
307
            logger.warn(msgS);
308
            for (1.5.0/docs/api/java/lang/Integer.html">Integer c : codesInBaco)
309
            {
310
                professoresDesaparecidosDoSigesNesteAno++;
311
                Teacher t = DaoFactory.getTeacherDaoImpl().loadBySigesCode(c);
312
                TeacherImpl teacherImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(t);
1396 jmachado 313
                removerUnidadesQueDesapareceramNoSiges(year, teacherImpl, new HashSet<CourseUnit>(),institutionCode);
1312 jmachado 314
                //consistirTurmasAluno(studentImpl, year, new HashMap<CourseUnit, String>());
315
            }
316
        }
317
        else
318
        {
319
            msgS = "OK check - Não existem alunos desaparecidos no SIGES ano: " + year + " institution:" + institutionCode + " possiveis adicionados manualmente, confirmar";
320
            serviceLogInfo(msgS);
321
            logger.info(msgS);
322
        }
323
    }
324
 
325
    private void newUserSystemAdvise(Teacher t, boolean newUser) {
326
        if (newUser)
327
            CommonServicesManager.getInstance().adviseNew(t);
328
        else
329
        {
330
            1.5.0/docs/api/java/lang/String.html">String password = t.getPassword();
331
            t.setPassword(null);
332
            CommonServicesManager.getInstance().adviseUpdate(t);
333
            t.setPassword(password);
334
        }
335
    }
336
 
337
 
338
    /**
996 jmachado 339
     * Envio de Notificação aos operadores do CI
340
     * @param subject
341
     * @param cause
342
     */
343
    private void sendNotificationAdmin(1.5.0/docs/api/java/lang/String.html">String subject, 1.5.0/docs/api/java/lang/String.html">String cause)
344
    {
1000 jmachado 345
 
996 jmachado 346
        List<String> emails = ConfigProperties.getListValues("admin.email");
347
        for(1.5.0/docs/api/java/lang/String.html">String email:emails)
348
        {
349
            serviceLogWarn(">>>>>>>>ENVIANDO NOTIFICACAO A ADMINISTRACAO: " + email);
350
            logger.warn(">>>>>>>>ENVIANDO NOTIFICACAO A ADMINISTRACAO: " + email);
351
        }
352
        List<String> arguments = new ArrayList<String>();
353
        arguments.add(cause.replace("\n","<br/>"));
354
        Email email = new Email(subject,emails,Globals.SYSTEM_EMAIL_BOX,"messageToAdmin_pt.txt",arguments);
1038 jmachado 355
        email.setHtml(true);
996 jmachado 356
        try {
357
            new SendEmailService().sendEmail(email);
358
        } catch (ServiceException e) {
359
            e.printStackTrace();
360
        }
1000 jmachado 361
 
996 jmachado 362
    }
363
 
364
    /**
893 jmachado 365
     * Implementação local do toString para a class Docente que foi gerada pelos web-services
366
     * @param d
367
     * @return
368
     */
369
 
370
    public 1.5.0/docs/api/java/lang/String.html">String docenteToString(Docente d)
371
    {
372
        return "Docente{" +
373
                "codigoFuncionario=" + d.getCodigoFuncionario() +
374
                ", nomeFuncionario='" + d.getNomeFuncionario() + '\'' +
375
                ", nomeFuncionarioInt='" + d.getNomeFuncionarioInt() + '\'' +
376
                ", nomeAcademico='" + d.getNomeAcademico() + '\'' +
377
                ", sexo='" + d.getSexo() + '\'' +
1246 jmachado 378
                ", dataNascimento=" + d.getData_nascimento() +
893 jmachado 379
                ", morada='" + d.getMorada() + '\'' +
380
                ", codigoPostal=" + d.getCodigoPostal() +
381
                ", subCodigoPostal=" + d.getSubCodigoPostal() +
382
                ", email='" + d.getEmail() + '\'' +
383
                ", numeroBi='" + d.getNumeroBi() + '\'' +
384
                ", usernameNetpa='" + d.getUsernameNetpa() + '\'' +
385
                ", disciplinas=" + d.getDisciplinas() +
386
                '}';
387
    }
996 jmachado 388
 
1553 jmachado 389
    private void cloneFields(Docente teacherSiges, Teacher teacher, HashMap<Integer, Nacionalidade> nacionalidades)
996 jmachado 390
    {
391
 
392
        teacher.setName(teacherSiges.getNomeFuncionarioInt());
393
        teacher.setEmail(teacherSiges.getEmail());
394
        1.5.0/docs/api/java/lang/String.html">String msgS;
395
 
396
        if(teacherSiges.getEmail() != null && teacherSiges.getEmail().endsWith(Globals.EMAIL_LOCAL_SUFFIX))
397
        {
398
            int atIndex = teacherSiges.getEmail().indexOf("@");
399
            if (atIndex > 0)
400
            {
401
                teacher.setUsername(teacherSiges.getEmail().substring(0, atIndex));
402
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " foi-lhe atribuido o username d" + teacherSiges.getEmail().substring(0, atIndex);
403
                logger.info(msgS);
404
                serviceLogInfo(msgS);
405
            }
406
            else
407
            {
408
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " NAO lhe foi atribuido username o email não tem o caracter @";
409
                logger.info(msgS);
410
                serviceLogInfo(msgS);
411
            }
412
        }
413
        else
414
        {
415
            msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao tem email no SIGES foi-lhe atribuido o username d" + teacherSiges.getCodigoFuncionario().intValue();
416
            logger.info(msgS);
417
            serviceLogInfo(msgS);
418
            teacher.setUsername("d" + teacherSiges.getCodigoFuncionario().intValue());
419
        }
420
        teacher.setSigesCode(teacherSiges.getCodigoFuncionario().intValue());
421
        teacher.setAddress(teacherSiges.getMorada());
422
        teacher.setZip("" + teacherSiges.getCodigoPostal().intValue());
423
        teacher.setBi(teacherSiges.getNumeroBi());
424
        teacher.setEmployerName(teacherSiges.getNomeFuncionario());
425
        teacher.setAcademicName(teacherSiges.getNomeAcademico());
1246 jmachado 426
        teacher.setBirthDate(teacherSiges.getData_nascimento());
1553 jmachado 427
        actualizaNacionalidade(teacherSiges, teacher, nacionalidades);
996 jmachado 428
    }
1244 jmachado 429
 
430
    private static class TipologiaCourseUnitPair
431
    {
432
        CourseUnit cu;
433
        1.5.0/docs/api/java/lang/Integer.html">Integer cdTipologia;
434
        1.5.0/docs/api/java/lang/Integer.html">Integer cdFuncaoDocente;
435
    }
893 jmachado 436
    /**
116 jmachado 437
     * Nao esta testado
438
     * jm
165 jmachado 439
     *
1553 jmachado 440
     *
996 jmachado 441
     * @param teacherSiges docente
442
     * @param teacher teacher
1553 jmachado 443
     * @param nacionalidades
333 jmachado 444
     * @throws Exception .
116 jmachado 445
     */
1553 jmachado 446
    private void persist(Docente teacherSiges, Teacher teacher, boolean newUser, 1.5.0/docs/api/java/lang/String.html">String year, DefaultLogMessages logmessages, int institutionCode, HashMap<Integer, Nacionalidade> nacionalidades) throws 1.5.0/docs/api/java/lang/Exception.html">Exception
116 jmachado 447
    {
996 jmachado 448
        1.5.0/docs/api/java/lang/String.html">String msgS;
332 jmachado 449
        try
221 jmachado 450
        {
1553 jmachado 451
            updateTeacherFields(teacherSiges, teacher, newUser,nacionalidades);
1312 jmachado 452
            //Desta forma as relacoes antigas sao ignoradas cria-se uma lista nova e atribui-se ao Teacher, o Hibernate faz resto e apaga as chaves estrangeiras antigas
453
            if (teacherSiges.getDisciplinas() == null ||  teacherSiges.getDisciplinas().size() == 0)
116 jmachado 454
            {
1312 jmachado 455
                /******Logging****/
456
                msgS = "ATENTION TEACHER WITH ZERO UNITS: codigoFuncionario " + teacherSiges.getCodigoFuncionario();
457
                logger.warn(msgS);
458
                serviceLogInfo(msgS);
459
                /******Logging****/
1315 jmachado 460
 
461
                TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
1396 jmachado 462
                removerUnidadesQueDesapareceramNoSiges(year, tImpl, new HashSet<CourseUnit>(),institutionCode);
996 jmachado 463
            }
1312 jmachado 464
            else
996 jmachado 465
            {
1312 jmachado 466
                //1 - PROCEDIMENTO CADEIRAS SAO CARREGADAS DO BACO DA LISTA QUE VEM DO SIGES -> units
467
                //2 - Sao retiradas da lista units as que o teacher tem mas que foram removidas localmente
468
                //3 - Sao adicionadas ao teacher as que o docente ainda nao tiver da lista units
469
                //4 - Remover da lista do teacher as unidades que não vêm do SIGES e que não foram adicionadas localmente
996 jmachado 470
 
1315 jmachado 471
                //o mapa nao esta a ser usado neste momento mas fica porque podera vir a ser necessario
472
                //o docente e' colocado nas unidades todas e as turmas ficam nas tipologias tratadas na importacao de cursos
1312 jmachado 473
                Map<CourseUnit,String> map_CourseUnit_x_Turma = new HashMap<CourseUnit, String>();
996 jmachado 474
 
1312 jmachado 475
                //PASSO 1
1315 jmachado 476
                Set<CourseUnit> unitsFromSigesPersistentInBaco = obterCadeirasBacoCorrespondentes(year,teacherSiges, teacher, logmessages,map_CourseUnit_x_Turma);
1312 jmachado 477
                //PASSO 2
1315 jmachado 478
                TeacherImpl tImpl = removerRemovidasLocalmente(teacher, unitsFromSigesPersistentInBaco);
1312 jmachado 479
                //PASSO 3
1315 jmachado 480
                adicionarCadeirasNovasAoDocente(tImpl, unitsFromSigesPersistentInBaco);
1312 jmachado 481
                //PASSO 4
1396 jmachado 482
                removerUnidadesQueDesapareceramNoSiges(year, tImpl, unitsFromSigesPersistentInBaco,institutionCode);
996 jmachado 483
 
1312 jmachado 484
            }
996 jmachado 485
 
486
 
1312 jmachado 487
        }
488
        catch (1.5.0/docs/api/java/lang/Exception.html">Exception e)
489
        {
490
            logger.error(e, e);
1426 jmachado 491
            List<String> emails = ConfigProperties.getListValues("admin.email");
1312 jmachado 492
            List<String> arguments = new ArrayList<String>();
493
            1.5.0/docs/api/java/lang/String.html">String cause = e.getCause() == null ? "" : e.getCause().toString();
494
            arguments.add((e.toString() + "\n" + cause).replace("\n","<br/>"));
1396 jmachado 495
            Email email = new Email("Erro de importacao de professores",emails,"baco@estgp.pt","messageToAdmin_pt.txt",arguments);
1312 jmachado 496
            new SendEmailService().sendEmail(email);
497
            throw e;
498
        }
996 jmachado 499
 
1312 jmachado 500
    }
996 jmachado 501
 
1396 jmachado 502
    private void removerUnidadesQueDesapareceramNoSiges(1.5.0/docs/api/java/lang/String.html">String year, Teacher teacher, Set<CourseUnit> units,int institutionCode)
1312 jmachado 503
    {
504
        //Remover unidades deste ano que nao vem do SIGES e que nao foram adicionadas localmente
505
        Iterator<CourseUnit> iterNowUnits = teacher.getTeachedUnits().iterator();
506
        TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
507
        while(iterNowUnits.hasNext())
508
        {
509
            CourseUnit cUNow = iterNowUnits.next();
1692 jmachado 510
            if(cUNow.getImportYear().equals(year) && cUNow.getCourse().getDepartment().getCourseSchool().getInstitutionalCode().equals(institutionCode+""))
996 jmachado 511
            {
1312 jmachado 512
                //Apenas tentamos apagar as unidades do ano corrente.
513
                //Este servico trabalha com unidades importadas do ano que e passado como argumento
514
                //Se importamos unidades desse ano, as dos outros anos nao vem na lista, logo
515
                //iriamos constatar que nenhuma estava no SIGES o que nao e verdade.
516
                //Assim so apagamos unidades do ano que estamos a importar e que nao venham
517
                //na importacao desse ano
996 jmachado 518
 
1312 jmachado 519
                boolean added = false;
520
                for(CourseUnit c: units)
892 jmachado 521
                {
1315 jmachado 522
                    if(cUNow.getId() == c.getId())
996 jmachado 523
                    {
1312 jmachado 524
                        added = true;
525
                        break;
996 jmachado 526
                    }
1312 jmachado 527
                }
528
                if(!added)
529
                {
530
 
531
                    if(!tImpl.isLocalUnit(cUNow))
532
                    {
533
                        /******Logging****/
534
                        1.5.0/docs/api/java/lang/String.html">String msg = "Removendo unidade: " + ((CourseUnitImpl)cUNow).getSigesUniqueIdentifiers() + " - do docente: " + teacher.getSigesCode() + " - Associacao desapareceu do SIGES";
535
                        serviceLogInfo(msg);
536
                        logger.info(msg);
537
                        unitsRemovedToTeachers++;
538
                        /******Logging****/
539
 
540
                        iterNowUnits.remove();
541
                    }
996 jmachado 542
                    else
543
                    {
1312 jmachado 544
                        /******Logging****/
545
                        1.5.0/docs/api/java/lang/String.html">String msg = "NAO REMOVIDA - Unidade: " + ((CourseUnitImpl)cUNow).getSigesUniqueIdentifiers() + " - do docente: " + teacher.getSigesCode() + " - Associacao desapareceu do SIGES mas foi adicionada localmente";
546
                        serviceLogInfo(msg);
547
                        logger.info(msg);
548
                        unitsLocalAddedNotRemoved++;
549
                        /******Logging****/
996 jmachado 550
                    }
892 jmachado 551
                }
1312 jmachado 552
            }
553
        }
554
    }
555
 
556
    private void adicionarCadeirasNovasAoDocente(Teacher teacher, Set<CourseUnit> units) {
557
        //3 - da lista units sao adicionadas  ao teacher as que sobraram do passo 2 e o docente ainda nao tiver
558
        if (teacher.getTeachedUnits() != null)
559
        {
560
            for (CourseUnit c : units)
561
            {
562
                boolean isIn = false;
563
                for (CourseUnit tc : teacher.getTeachedUnits())
996 jmachado 564
                {
1315 jmachado 565
                    if (tc.getId() == c.getId())
1312 jmachado 566
                    {
567
                        isIn = true;
568
                        break;
569
                    }
996 jmachado 570
                }
1312 jmachado 571
                if (!isIn)
892 jmachado 572
                {
1312 jmachado 573
 
574
                    /******Logging****/
575
                    1.5.0/docs/api/java/lang/String.html">String msg = "Adicionando unidade: " + ((CourseUnitImpl)c).getSigesUniqueIdentifiers() + " - ao teacher: " + teacher.getSigesCode() + " turma " + c.getCdTurma() + " - Associacao nova no SIGES";
576
                    serviceLogInfo(msg);
577
                    logger.info(msg);
578
                    unitsAddedToTeachers++;
579
                    /******Logging****/
580
 
581
                    teacher.getTeachedUnits().add(c);
892 jmachado 582
                }
332 jmachado 583
            }
1312 jmachado 584
        }
585
        else
586
            teacher.setTeachedUnits(units);
587
    }
996 jmachado 588
 
1315 jmachado 589
    private TeacherImpl removerRemovidasLocalmente(Teacher teacher, Set<CourseUnit> units) {
1312 jmachado 590
        //2 - Sao retiradas da lista units as que o teacher tem mas que foram removidas localmente
591
        Iterator<CourseUnit> iter = units.iterator();
1315 jmachado 592
        TeacherImpl tImpl = (TeacherImpl) DaoFactory.getTeacherDaoImpl().narrow(teacher);
1312 jmachado 593
        while (iter.hasNext())
594
        {
595
            CourseUnit courseUnit = iter.next();
596
            //In case of a comming proxy
597
            if (tImpl.isLocalRemovedUnit(courseUnit))
892 jmachado 598
            {
1312 jmachado 599
                /******Logging****/
600
                unitsLocallyRemovedNotAdded++;
601
                1.5.0/docs/api/java/lang/String.html">String msg = "Removendo unidade: " + ((CourseUnitImpl)courseUnit).getSigesUniqueIdentifiers() + " - do professor: " + tImpl.getSigesCode() + " - Associacao existe no SIGES mas foi removido LOCALMENTE";
602
                serviceLogInfo(msg);
603
                logger.info(msg);
604
                /******Logging****/
996 jmachado 605
 
1312 jmachado 606
                iter.remove();
892 jmachado 607
            }
1312 jmachado 608
        }
1315 jmachado 609
        return tImpl;
1312 jmachado 610
    }
996 jmachado 611
 
1315 jmachado 612
    private Set<CourseUnit> obterCadeirasBacoCorrespondentes(1.5.0/docs/api/java/lang/String.html">String year, Docente teacherSiges, Teacher teacher, DefaultLogMessages logmessages,Map<CourseUnit,String> map_CourseUnit_x_Turma) {
1312 jmachado 613
        1.5.0/docs/api/java/lang/String.html">String msgS;
614
        Set<CourseUnit> units = new HashSet<CourseUnit>();
1244 jmachado 615
 
1312 jmachado 616
        for (Disciplina disciplina : teacherSiges.getDisciplinas())
617
        {
618
            List<CourseUnit> loadedunits = new ArrayList<CourseUnit>();
619
            if(disciplina.getCodigoCurso().intValue() < 0)
620
            {
621
                //O CODIGO DE CURSO VEM A NULL E E METIDO PELO DAO A -1
622
                //PORQUE OS ACADEMICOS NAO DEFINEM CURSO NA ASSOCIAÇÃO DO DOCENTE À TURMA NA TABELA T_DOC_TURMA
623
                //ISTO ACONTECE PORQUE A TURMA E MISTA E DE VARIOS CURSOS
1315 jmachado 624
                //NESTE CASO COLOCAMOS O DOCENTE NAS cadeiras dos cursos TODOS
1235 jmachado 625
 
626
 
1315 jmachado 627
                //todo futuro turmas separadas
628
                //neste caso das turmas separadas existe uma duvida:
629
                //Vir < 0 no codigo de curso significa que alunos de varios cursos podem estar nesta unidade
630
                //isso significa que nao temos cursos --> nao saber se é separated turmas
631
                //se nao sabemos se é separated turmas nunca podemos saber como ir buscar as unidades ao BACO
632
                // neste caso vamos busca-las sem a turma a descriminar e atribuimos todas ao docente.
633
                //a hipotese no futuro é, para todas as cadaeiras que forem devolvidas
634
                //corremos uma a uma e verificamos o seu curso, se for separated turmas e a turma for igual
635
                //a da disciplina adicionamos, se não for seprated turmas adicionamos sempre
1235 jmachado 636
 
1315 jmachado 637
 
1312 jmachado 638
                List<CourseUnit> courseUnits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUniqueAllCourses("" + disciplina.getCodigo(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
639
                if(courseUnits!=null)
640
                {
641
                    loadedunits = courseUnits;
642
                }
1123 jmachado 643
 
1312 jmachado 644
                /*******Logging************************/
645
                if(loadedunits.size() > 0)
646
                {
647
                    msgS = "Unit No Course -> course = " + disciplina.getCodigoCurso().intValue() + " semestre:" + disciplina.getCdDuracao() + " codigo:" + disciplina.getCodigo() + " year:" + disciplina.getCdLectivo()
648
                            + " will load of all possible courses:{ ";
649
                    for(CourseUnit cc : courseUnits)
332 jmachado 650
                    {
1312 jmachado 651
                        msgS+= cc.getCourseCode() + ",";
332 jmachado 652
                    }
1312 jmachado 653
                    msgS+=" } all added to teacher: " + teacher.getSigesCode();
654
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
655
                    if(loadedunits.size() > 1)
656
                        unitsFoundForCourseNotFoundMult++;
332 jmachado 657
                    else
1312 jmachado 658
                        unitsFoundForCourseNotFoundSingle++;
659
                    logger.warn(msgS);
660
                    serviceLogWarn(msgS);
332 jmachado 661
                }
1312 jmachado 662
                /******Logging****/
663
            }
1315 jmachado 664
            else{
1312 jmachado 665
 
1315 jmachado 666
                boolean cursoFicticio = ImportStudentsService.isCursoFicticio(disciplina.getCodigoCurso());
667
                if(cursoFicticio)
668
                {
669
                    msgS = "WARNING WARNING #### Docente com curso ficticio, nao esperamos aqui cursos ficticios: " + disciplina.getCodigoCurso();
670
                    serviceLogWarn(msgS);
671
                    logger.warn(msgS);
672
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
673
                    cursosFicticios++;
674
                    continue;
675
                }
676
 
677
                //Nao vamos usar este pormenor aqui. Caregamos todas e pronto. Os docentes ficam associados às duas unidades das duas turmas
678
                //mesmo no caso das turmas separadas. As tipologias tratam das associações às turmas para que não haja questionarios a mais
679
                //na criacao de questionarios é natural que falhe alguma coisa por haver aqui unidades a mais
680
                //por isso devera ser ai feita a verificacao destes casos
681
                boolean separateTurmas = ImportCourseService.loadCourseYearTurmasPolicy(disciplina.getCodigoCurso(), year, logmessages, this);
1415 jmachado 682
 
683
                //este procedimento requer que a turma venha do siges, neste momento nao vem
684
                //Este procedimento foi colocado por mim a 6 de Junho para que os questionarios tenham os profs certos nas disciplinas
685
                //e não em duplicado, daqui para baixo o código nunca compara com separateTurmas, o mapa apenas é acedido aqui
686
                //porque daqui para baixo uma vez carregadas as turmas persistentes do SIGES apenas o id é comparado para ver se fica ou se é removida
687
                //Vamos apenas ter de  verificar que o código de turma vem na associação do docente à turma.
688
                //NAO DA A TURMA NUNCA VEM DO SIGENS PARA NAO DUPLICAR TURMAS NO JOIN
689
                //RESOVE-SE NA ATRIBUICAO DE RESPOSTAS DOS QUESTINARIOS SO SE METE O QUE TEM SUMARIO SE O CURSO FOR DE TURMAS
690
                //SEPARADAS
691
                //if(separateTurmas)
692
                //    loadedunits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUniqueWithTurma("" + disciplina.getCodigo(), "" + disciplina.getCodigoCurso(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo(),disciplina.getCdTurma());
693
                //else
694
                //    loadedunits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUnique("" + disciplina.getCodigo(), "" + disciplina.getCodigoCurso(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
695
 
1312 jmachado 696
                loadedunits = DaoFactory.getCourseUnitDaoImpl().loadBySigesCodeUnique("" + disciplina.getCodigo(), "" + disciplina.getCodigoCurso(), "" + disciplina.getCdDuracao(), "" + disciplina.getCdLectivo());
697
                /*******Logging************************/
1315 jmachado 698
                if(loadedunits.size() > 1 && !separateTurmas)
225 jmachado 699
                {
1312 jmachado 700
                    unitsDuplicated++;
701
                    msgS = "WARNING WARNING #### UnitsDuplicated: ";
702
                    serviceLogWarn(msgS);
703
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
704
                    msgS = "WARNING WARNING ####String sigesCode, String courseCode, String semestre, String year = " + disciplina.getCodigo() + ", " + disciplina.getCodigoCurso() + ","+ disciplina.getCdDuracao() + "," +  disciplina.getCdLectivo();
705
                    serviceLogWarn(msgS);
706
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
707
                    msgS = "WARNING WARNING ####returning first one, this could be a case of units spared because of TURMAS split used in 201516: ";
708
                    serviceLogWarn(msgS);
709
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
225 jmachado 710
                }
1315 jmachado 711
                if(loadedunits.size() > 1 && separateTurmas)
712
                {
713
                    Map<String,String> turmas = new HashMap<String, String>();
714
 
715
                    for(CourseUnit c :loadedunits)
716
                    {
717
                        turmas.put(c.getCdTurma(),c.getCdTurma());
718
                    }
719
                    if(turmas.size() < loadedunits.size())
720
                    {
721
                        unitsDuplicated++;
722
                        msgS = "WARNING WARNING #### O Curso é de turmas separadas mas o docente tem unidades repetidas com a mesma turma: ";
723
                        serviceLogWarn(msgS);
724
                        logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
725
                        logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
726
                        msgS = "WARNING WARNING ####String sigesCode, String courseCode, String semestre, String year = " + disciplina.getCodigo() + ", " + disciplina.getCodigoCurso() + ","+ disciplina.getCdDuracao() + "," +  disciplina.getCdLectivo();
727
                        serviceLogWarn(msgS);
728
                    }
729
                    turmas.clear();
730
                }
1312 jmachado 731
                /*******Logging************************/
732
            }
733
 
734
 
735
            if (loadedunits.size() == 0)
736
            {
737
                /*******Logging************************/
738
                msgS = "Unit not found: semestre:" + disciplina.getCdDuracao() + " codigo:" + disciplina.getCodigo() + " course:" + disciplina.getCodigoCurso() + " year:" + disciplina.getCdLectivo();
739
                unitsNotFound++;
740
                if(disciplina.getCodigoCurso()==null || disciplina.getCodigoCurso().intValue() < 0)
251 jmachado 741
                {
1312 jmachado 742
                    unitsNotFoundCourseNotFound++;
743
                    msgS += "... unit with No Course Found in SIGES";
744
                    logmessages.addMessage(new DefaultLogMessage("import.teachers", LogMessageTypeEnum.WARNING,msgS ));
251 jmachado 745
                }
332 jmachado 746
                else
996 jmachado 747
                {
1312 jmachado 748
                    msgS += "... probably unit with zero students not imported in CoursesImport";
996 jmachado 749
                }
1312 jmachado 750
                logger.warn(msgS);
751
                serviceLogWarn(msgS);
752
                /*******Logging************************/
251 jmachado 753
            }
1312 jmachado 754
            else
755
            {
756
                for(CourseUnit found: loadedunits)
757
                {
758
                    map_CourseUnit_x_Turma.put(found,disciplina.getCdTurma());
759
                }
760
                units.addAll(loadedunits);
761
            }
762
        }
763
        return units;
764
    }
996 jmachado 765
 
1553 jmachado 766
    private void updateTeacherFields(Docente teacherSiges, Teacher teacher, boolean newUser, HashMap<Integer, Nacionalidade> nacionalidades) {
1312 jmachado 767
        1.5.0/docs/api/java/lang/String.html">String msgS;
768
        if(newUser)
769
        {
1553 jmachado 770
            cloneFields(teacherSiges, teacher,nacionalidades);
996 jmachado 771
 
1312 jmachado 772
            /*******Logging************************/
773
            teachersNew++;
774
            serviceLogInfo("NOVO PROFESSOR ENCONTRADO: siges:" + teacherSiges.getCodigoFuncionario() + " bi:" + teacher.getBi() + " nome:" + teacher.getName());
775
            /*******Logging************************/
116 jmachado 776
        }
1312 jmachado 777
 
778
        //CASO EM QUE O DOCENTE NO SIGES FOI ATRIBUIDO A OUTRO ESTUDANTE PARA PREENCHER BURACO NA NUMERACAO
779
        else if(teacherSiges.getNumeroBi() == null || teacher.getBi() == null || ! teacherSiges.getNumeroBi().equals(teacher.getBi()))
332 jmachado 780
        {
1312 jmachado 781
 
782
            teachersChangeBI++;
783
 
784
            1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder builder = new 1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder();
785
 
786
            /*******Logging************************/
787
            builder.append("ATENCAO NUMERO DE PROFESSOR " + teacherSiges.getCodigoFuncionario() + " MUDOU DE DONO Confirme dados\n");
788
            builder.append("ALTERANDO DADOS DO PROFESSOR " + teacherSiges.getCodigoFuncionario() + "\n");
789
            builder.append("-------ANTES: " + "\n");
790
            builder.append("-------BI: " + teacher.getBi() + "\n");
791
            builder.append("-------Nome: " + teacher.getName() + "\n");
792
            builder.append("-------Username: " + teacher.getUserNameNetpa() + "\n");
793
            builder.append("-------Address: " + teacher.getAddress() + "\n");
794
            builder.append("-------Zip: " + teacher.getZip() + "\n");
795
            builder.append("-------Email: " + teacher.getEmail() + "\n");
796
            builder.append("-------Phone: " + teacher.getPhonenumber() + "\n");
797
            /*******Logging************************/
798
 
799
 
1553 jmachado 800
            cloneFields(teacherSiges, teacher, nacionalidades);
1312 jmachado 801
 
802
            //teacher.setAutoBlockMode(false);
803
            //teacher.setManualBlock(true);
804
 
805
            /*******Logging************************/
806
            builder.append("DEPOIS: " + "\n");
807
            builder.append("BI: " + teacher.getBi() + "\n");
808
            builder.append("Nome: " + teacher.getName() + "\n");
809
            builder.append("Username: " + teacher.getUserNameNetpa() + "\n");
810
            builder.append("Address: " + teacher.getAddress() + "\n");
811
            builder.append("Zip: " + teacher.getZip() + "\n");
812
            builder.append("Email: " + teacher.getEmail() + "\n");
813
            builder.append("Phone: " + teacher.getPhonenumber() + "\n");
814
            serviceLogWarn(builder.toString());
815
            sendNotificationAdmin("CODIGO SIGES PROFESSOR " + teacherSiges.getCodigoFuncionario() + " MUDOU DE DONO - NAO FOI BLOQUEADO OS DADOS FORAM REPOSTOS ",builder.toString());
816
            /*******Logging************************/
817
 
332 jmachado 818
        }
1312 jmachado 819
        else
820
        {
1553 jmachado 821
            //ACTUALIZAR PAIS
822
            actualizaNacionalidade(teacherSiges, teacher, nacionalidades);
823
 
824
                //novo para termos sempre o email externo
1316 jmachado 825
            if(teacher.getOutEmail() == null ||teacher.getOutEmail().indexOf("@") < 0)
826
                teacher.setOutEmail(teacherSiges.getEmail());
1312 jmachado 827
            //VAMOS APENAS ADICIONAR CAMPOS QUE AINDA NAO EXISTAM IGUAL AO CLONE MAS NAO MECHE
828
            if(teacher.getName() == null || teacher.getName().length() == 0)
829
                teacher.setName(teacherSiges.getNomeFuncionarioInt());
830
            //Email instituicao
1316 jmachado 831
            //if(teacher.getEmail() == null || teacher.getEmail().indexOf("@") < 0)
832
            //    teacher.setEmail(teacherSiges.getEmail());
332 jmachado 833
 
1316 jmachado 834
            1.5.0/docs/api/java/lang/String.html">String suffixReaded = null;
835
            List<String> sufixes = ConfigProperties.getListValues("email.local.suffix.");
836
            for(1.5.0/docs/api/java/lang/String.html">String suffix: sufixes)
1312 jmachado 837
            {
1316 jmachado 838
                if(teacherSiges.getEmail()!=null && teacherSiges.getEmail().endsWith("@"+suffix))
839
                {
840
                    suffixReaded = suffix;
841
                    break;
842
                }
843
            }
844
 
845
            if (teacherSiges.getEmail() != null && (teacher.getUsername() == null || teacher.getUsername().trim().length() == 0)
846
                    && suffixReaded != null)
847
            {
1312 jmachado 848
                int atIndex = teacherSiges.getEmail().indexOf("@");
849
                if (atIndex > 0)
850
                {
851
                    teacher.setUsername(teacherSiges.getEmail().substring(0, atIndex));
852
                    /*******Logging************************/
853
                    msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " foi-lhe atribuido o username d" + teacherSiges.getEmail().substring(0, atIndex);
854
                    logger.info(msgS);
855
                    serviceLogInfo(msgS);
856
                    /*******Logging************************/
857
                }
858
                else
859
                {
860
                    /*******Logging************************/
861
                    msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " NAO lhe foi atribuido username o email não tem o caracter @";
862
                    logger.info(msgS);
863
                    serviceLogInfo(msgS);
864
                    /*******Logging************************/
865
                }
866
            }
867
            else if(teacher.getUsername() == null || teacher.getUsername().trim().length() == 0)
868
            {
869
                /*******Logging************************/
870
                msgS = "Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao tem email no SIGES foi-lhe atribuido o username d" + teacherSiges.getCodigoFuncionario().intValue();
871
                logger.info(msgS);
872
                serviceLogInfo(msgS);
873
                /*******Logging************************/
874
 
875
                teacher.setUsername("d" + teacherSiges.getCodigoFuncionario().intValue());
876
            }
877
            else
878
            {
879
                //ALL OK
880
                //username não foi alterado
881
                //msgS="Teacher SIGES:" + teacherSiges.getCodigoFuncionario().intValue() + " nao lhe foi alterado o username " + teacher.getUsername();
882
                //logger.info(msgS);
883
                //serviceLogInfo(msgS);
884
            }
885
            teacher.setSigesCode(teacherSiges.getCodigoFuncionario().intValue());
886
            if(teacher.getAddress() == null || teacher.getAddress().length() == 0)
887
                teacher.setAddress(teacherSiges.getMorada());
888
            if(teacher.getZip() == null || teacher.getZip().length() == 0)
889
                teacher.setZip("" + teacherSiges.getCodigoPostal().intValue());
890
            if(teacher.getBi() == null || teacher.getBi().length() == 0)
891
                teacher.setBi(teacherSiges.getNumeroBi());
892
            teacher.setEmployerName(teacherSiges.getNomeFuncionario());
893
            teacher.setAcademicName(teacherSiges.getNomeAcademico());
894
            if(teacher.getBirthDate() == null || teacher.getBirthDate().getTime() == 0)
895
                teacher.setBirthDate(teacherSiges.getData_nascimento());
896
        }
116 jmachado 897
    }
898
 
1553 jmachado 899
    private void actualizaNacionalidade(Docente teacherSiges, Teacher teacher, HashMap<Integer, Nacionalidade> nacionalidades) {
900
        try
901
        {
902
            if(teacherSiges.getCodigoNacionalidade() != null)
903
            {
904
                Nacionalidade nac = nacionalidades.get(teacherSiges.getCodigoNacionalidade());
905
                if(nac != null)
906
                {
907
                    teacher.setCountry(nac.getPais());
908
                    teacher.setNacionalidade(nac.getNacionalidade());
909
                }
910
            }
911
        }
912
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable t)
913
        {
914
            logger.error("NACIONALIDADE INVALIDA NO DOCENTE: " + teacherSiges.getCodigoFuncionario());
915
        }
916
    }
917
 
996 jmachado 918
    @1.5.0/docs/api/java/lang/Override.html">Override
1070 jmachado 919
    protected ILogMessages runJobServiceTask() throws 1.5.0/docs/api/java/lang/Throwable.html">Throwable {
996 jmachado 920
 
1070 jmachado 921
        1.5.0/docs/api/java/lang/String.html">String importYear = getParametersMap().get(JOB_importYear_KEY).getObject();
1312 jmachado 922
        1.5.0/docs/api/java/lang/String.html">String institutionCode = getParametersMap().get(JOB_institution_KEY).getObject();
923
        return run(importYear,1.5.0/docs/api/java/lang/Integer.html">Integer.parseInt(institutionCode));
996 jmachado 924
    }
925
 
926
    public static final 1.5.0/docs/api/java/lang/String.html">String JOB_importYear_KEY = "JOB_importYear_KEY";
927
 
928
 
116 jmachado 929
    /**
930
     * Testar por aqui poi requer Super Role e assim e' autmatico
165 jmachado 931
     *
116 jmachado 932
     * @param args of main
933
     * @throws ServiceException on error
934
     */
165 jmachado 935
    public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) throws ServiceException
116 jmachado 936
    {
995 jmachado 937
        1.5.0/docs/api/java/lang/String.html">String year = DaoFactory.getConfigurationDaoImpl().getImportsDefaultImportYearCreateTransaction();
491 jmachado 938
        if(args != null && args.length > 0)
939
            year = args[0];
1312 jmachado 940
        1.5.0/docs/api/java/lang/String.html">String institutionCode = "1";
941
        if(args != null && args.length > 1)
942
            institutionCode = args[1];
116 jmachado 943
        AbstractDao.getCurrentSession().beginTransaction();
1312 jmachado 944
        new ImportTeachersService().run(year,1.5.0/docs/api/java/lang/Integer.html">Integer.parseInt(institutionCode));
116 jmachado 945
        AbstractDao.getCurrentSession().getTransaction().commit();
946
    }
947
 
948
 
949
}