Search in sources :

Example 1 with PhoneNumberDAO

use of fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO in project pyramus by otavanopisto.

the class StudentsService method createStudent.

public StudentEntity createStudent(@WebParam(name = "abstractStudentId") Long abstractStudentId, @WebParam(name = "firstName") String firstName, @WebParam(name = "lastName") String lastName, @WebParam(name = "nickname") String nickname, @WebParam(name = "phone") String phone, @WebParam(name = "additionalInfo") String additionalInfo, @WebParam(name = "parentalInfo") String parentalInfo, @WebParam(name = "studyTimeEnd") Date studyTimeEnd, @WebParam(name = "activityTypeId") Long activityTypeId, @WebParam(name = "examinationTypeId") Long examinationTypeId, @WebParam(name = "educationalLevelId") Long educationalLevelId, @WebParam(name = "education") String education, @WebParam(name = "nationalityId") Long nationalityId, @WebParam(name = "municipalityId") Long municipalityId, @WebParam(name = "languageId") Long languageId, @WebParam(name = "schoolId") Long schoolId, @WebParam(name = "studyProgrammeId") Long studyProgrammeId, @WebParam(name = "previousStudies") Double previousStudies, @WebParam(name = "studyStartDate") Date studyStartDate, @WebParam(name = "studyEndDate") Date studyEndDate, @WebParam(name = "studyEndReasonId") Long studyEndReasonId, @WebParam(name = "studyEndText") String studyEndText, @WebParam(name = "lodging") Boolean lodging) {
    StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    StudentActivityTypeDAO activityTypeDAO = DAOFactory.getInstance().getStudentActivityTypeDAO();
    StudentExaminationTypeDAO examinationTypeDAO = DAOFactory.getInstance().getStudentExaminationTypeDAO();
    StudentEducationalLevelDAO educationalLevelDAO = DAOFactory.getInstance().getStudentEducationalLevelDAO();
    StudentStudyEndReasonDAO studyEndReasonDAO = DAOFactory.getInstance().getStudentStudyEndReasonDAO();
    LanguageDAO languageDAO = DAOFactory.getInstance().getLanguageDAO();
    MunicipalityDAO municipalityDAO = DAOFactory.getInstance().getMunicipalityDAO();
    NationalityDAO nationalityDAO = DAOFactory.getInstance().getNationalityDAO();
    SchoolDAO schoolDAO = DAOFactory.getInstance().getSchoolDAO();
    StudyProgrammeDAO studyProgrammeDAO = DAOFactory.getInstance().getStudyProgrammeDAO();
    ContactInfoDAO contactInfoDAO = DAOFactory.getInstance().getContactInfoDAO();
    PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
    ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
    StudentLodgingPeriodDAO studentLodgingPeriodDAO = DAOFactory.getInstance().getStudentLodgingPeriodDAO();
    Person person = personDAO.findById(abstractStudentId);
    Nationality nationality = nationalityId == null ? null : nationalityDAO.findById(nationalityId);
    Municipality municipality = municipalityId == null ? null : municipalityDAO.findById(municipalityId);
    Language language = languageId == null ? null : languageDAO.findById(languageId);
    StudentActivityType activityType = activityTypeId == null ? null : activityTypeDAO.findById(activityTypeId);
    StudentExaminationType examinationType = examinationTypeId == null ? null : examinationTypeDAO.findById(examinationTypeId);
    StudentEducationalLevel educationalLevel = educationalLevelId == null ? null : educationalLevelDAO.findById(educationalLevelId);
    School school = schoolId == null ? null : schoolDAO.findById(schoolId);
    StudyProgramme studyProgramme = studyProgrammeId == null ? null : studyProgrammeDAO.findById(studyProgrammeId);
    StudentStudyEndReason studyEndReason = studyEndReasonId == null ? null : studyEndReasonDAO.findById(studyEndReasonId);
    firstName = StringUtils.trim(firstName);
    lastName = StringUtils.trim(lastName);
    nickname = StringUtils.trim(nickname);
    Student student = studentDAO.create(person, firstName, lastName, nickname, additionalInfo, studyTimeEnd, activityType, examinationType, educationalLevel, education, nationality, municipality, language, school, studyProgramme, null, previousStudies, studyStartDate, studyEndDate, studyEndReason, studyEndText, false);
    if (lodging && studyStartDate != null)
        studentLodgingPeriodDAO.create(student, studyStartDate, studyEndDate);
    if (phone != null) {
        ContactType contactType = contactTypeDAO.findById(new Long(1));
        phoneNumberDAO.create(student.getContactInfo(), contactType, Boolean.TRUE, phone);
    }
    contactInfoDAO.update(student.getContactInfo(), parentalInfo);
    // Default user
    personDAO.updateDefaultUser(person, student);
    validateEntity(student);
    return EntityFactoryVault.buildFromDomainObject(student);
}
Also used : PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) StudyProgramme(fi.otavanopisto.pyramus.domainmodel.base.StudyProgramme) StudentStudyEndReason(fi.otavanopisto.pyramus.domainmodel.students.StudentStudyEndReason) StudentStudyEndReasonDAO(fi.otavanopisto.pyramus.dao.students.StudentStudyEndReasonDAO) StudentEducationalLevel(fi.otavanopisto.pyramus.domainmodel.students.StudentEducationalLevel) StudentLodgingPeriodDAO(fi.otavanopisto.pyramus.dao.students.StudentLodgingPeriodDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) School(fi.otavanopisto.pyramus.domainmodel.base.School) Language(fi.otavanopisto.pyramus.domainmodel.base.Language) MunicipalityDAO(fi.otavanopisto.pyramus.dao.base.MunicipalityDAO) StudentEducationalLevelDAO(fi.otavanopisto.pyramus.dao.students.StudentEducationalLevelDAO) SchoolDAO(fi.otavanopisto.pyramus.dao.base.SchoolDAO) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) StudentExaminationTypeDAO(fi.otavanopisto.pyramus.dao.students.StudentExaminationTypeDAO) Municipality(fi.otavanopisto.pyramus.domainmodel.base.Municipality) StudentExaminationType(fi.otavanopisto.pyramus.domainmodel.students.StudentExaminationType) LanguageDAO(fi.otavanopisto.pyramus.dao.base.LanguageDAO) NationalityDAO(fi.otavanopisto.pyramus.dao.base.NationalityDAO) StudentActivityTypeDAO(fi.otavanopisto.pyramus.dao.students.StudentActivityTypeDAO) Student(fi.otavanopisto.pyramus.domainmodel.students.Student) StudyProgrammeDAO(fi.otavanopisto.pyramus.dao.base.StudyProgrammeDAO) Nationality(fi.otavanopisto.pyramus.domainmodel.base.Nationality) StudentDAO(fi.otavanopisto.pyramus.dao.students.StudentDAO) ContactInfoDAO(fi.otavanopisto.pyramus.dao.base.ContactInfoDAO) StudentActivityType(fi.otavanopisto.pyramus.domainmodel.students.StudentActivityType) Person(fi.otavanopisto.pyramus.domainmodel.base.Person)

Example 2 with PhoneNumberDAO

use of fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO in project pyramus by otavanopisto.

the class EditStudentJSONRequestController method process.

public void process(JSONRequestContext requestContext) {
    StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    StudentActivityTypeDAO activityTypeDAO = DAOFactory.getInstance().getStudentActivityTypeDAO();
    StudentExaminationTypeDAO examinationTypeDAO = DAOFactory.getInstance().getStudentExaminationTypeDAO();
    StudentEducationalLevelDAO educationalLevelDAO = DAOFactory.getInstance().getStudentEducationalLevelDAO();
    StudentStudyEndReasonDAO studyEndReasonDAO = DAOFactory.getInstance().getStudentStudyEndReasonDAO();
    UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
    LanguageDAO languageDAO = DAOFactory.getInstance().getLanguageDAO();
    MunicipalityDAO municipalityDAO = DAOFactory.getInstance().getMunicipalityDAO();
    NationalityDAO nationalityDAO = DAOFactory.getInstance().getNationalityDAO();
    SchoolDAO schoolDAO = DAOFactory.getInstance().getSchoolDAO();
    AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
    ContactInfoDAO contactInfoDAO = DAOFactory.getInstance().getContactInfoDAO();
    EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
    PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
    TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
    ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
    UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
    UserDAO userDAO = DAOFactory.getInstance().getUserDAO();
    CurriculumDAO curriculumDAO = DAOFactory.getInstance().getCurriculumDAO();
    StudentLodgingPeriodDAO lodgingPeriodDAO = DAOFactory.getInstance().getStudentLodgingPeriodDAO();
    PersonVariableDAO personVariableDAO = DAOFactory.getInstance().getPersonVariableDAO();
    StudentStudyPeriodDAO studentStudyPeriodDAO = DAOFactory.getInstance().getStudentStudyPeriodDAO();
    StaffMemberDAO staffMemberDAO = DAOFactory.getInstance().getStaffMemberDAO();
    User loggedUser = userDAO.findById(requestContext.getLoggedUserId());
    Long personId = NumberUtils.createLong(requestContext.getRequest().getParameter("personId"));
    Person person = personDAO.findById(personId);
    Date birthday = requestContext.getDate("birthday");
    String ssecId = requestContext.getString("ssecId");
    Sex sex = (Sex) requestContext.getEnum("gender", Sex.class);
    String basicInfo = requestContext.getString("basicInfo");
    Long version = requestContext.getLong("version");
    Boolean secureInfo = requestContext.getBoolean("secureInfo");
    String username = requestContext.getString("username");
    String password = requestContext.getString("password1");
    String password2 = requestContext.getString("password2");
    if (UserUtils.allowEditCredentials(loggedUser, person)) {
        if (!person.getVersion().equals(version)) {
            throw new StaleObjectStateException(Person.class.getName(), person.getId());
        }
        boolean usernameBlank = StringUtils.isBlank(username);
        boolean passwordBlank = StringUtils.isBlank(password);
        UserIdentification userIdentification = userIdentificationDAO.findByAuthSourceAndPerson("internal", person);
        if (usernameBlank && passwordBlank) {
            // #1108: Existing credential deletion
            if (userIdentification != null && NumberUtils.isNumber(userIdentification.getExternalId())) {
                InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
                InternalAuth internalAuth = internalAuthDAO.findById(new Long(userIdentification.getExternalId()));
                if (internalAuth != null) {
                    internalAuthDAO.delete(internalAuth);
                }
                userIdentificationDAO.delete(userIdentification);
            }
        } else if (!usernameBlank || !passwordBlank) {
            if (!passwordBlank && !password.equals(password2)) {
                throw new SmvcRuntimeException(PyramusStatusCode.PASSWORD_MISMATCH, "Passwords don't match");
            }
            // #921: Check username
            InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
            InternalAuth internalAuth = internalAuthDAO.findByUsername(username);
            if (internalAuth != null) {
                userIdentification = userIdentificationDAO.findByAuthSourceAndExternalId("internal", internalAuth.getId().toString());
                if (userIdentification != null && !person.getId().equals(userIdentification.getPerson().getId())) {
                    throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.usernameInUse"));
                }
            } else if (!usernameBlank && passwordBlank) {
                throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.nopassword"));
            }
            // TODO: Support for multiple internal authentication providers
            List<InternalAuthenticationProvider> internalAuthenticationProviders = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders();
            if (internalAuthenticationProviders.size() == 1) {
                InternalAuthenticationProvider internalAuthenticationProvider = internalAuthenticationProviders.get(0);
                if (internalAuthenticationProvider != null) {
                    userIdentification = userIdentificationDAO.findByAuthSourceAndPerson(internalAuthenticationProvider.getName(), person);
                    if (internalAuthenticationProvider.canUpdateCredentials()) {
                        if (userIdentification == null) {
                            String externalId = internalAuthenticationProvider.createCredentials(username, password);
                            userIdentificationDAO.create(person, internalAuthenticationProvider.getName(), externalId);
                        } else {
                            if ("-1".equals(userIdentification.getExternalId())) {
                                String externalId = internalAuthenticationProvider.createCredentials(username, password);
                                userIdentificationDAO.updateExternalId(userIdentification, externalId);
                            } else {
                                if (!StringUtils.isBlank(username))
                                    internalAuthenticationProvider.updateUsername(userIdentification.getExternalId(), username);
                                if (!StringUtils.isBlank(password))
                                    internalAuthenticationProvider.updatePassword(userIdentification.getExternalId(), password);
                            }
                        }
                    }
                }
            }
        }
    }
    // Abstract student
    personDAO.update(person, birthday, ssecId, sex, basicInfo, secureInfo);
    // Person Variables
    Integer personVariableCount = requestContext.getInteger("personVariablesTable.rowCount");
    if (personVariableCount != null) {
        for (int i = 0; i < personVariableCount; i++) {
            String colPrefix = "personVariablesTable." + i;
            Long edited = requestContext.getLong(colPrefix + ".edited");
            if (Objects.equals(new Long(1), edited)) {
                String variableKey = requestContext.getString(colPrefix + ".key");
                String variableValue = requestContext.getString(colPrefix + ".value");
                personVariableDAO.setPersonVariable(person, variableKey, variableValue);
            }
        }
    }
    List<Student> students = UserUtils.canAccessAllOrganizations(loggedUser) ? studentDAO.listByPerson(person) : studentDAO.listByPersonAndOrganization(person, loggedUser.getOrganization());
    for (Student student : students) {
        int rowCount = requestContext.getInteger("emailTable." + student.getId() + ".rowCount");
        for (int i = 0; i < rowCount; i++) {
            String colPrefix = "emailTable." + student.getId() + "." + i;
            String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
            if (StringUtils.isNotBlank(email)) {
                ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
                if (!UserUtils.isAllowedEmail(email, contactType, person.getId()))
                    throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.emailInUse"));
            }
        }
    }
    for (Student student : students) {
        Long studentVersion = requestContext.getLong("studentVersion." + student.getId());
        if (!student.getVersion().equals(studentVersion))
            throw new StaleObjectStateException(Student.class.getName(), student.getId());
        String firstName = StringUtils.trim(requestContext.getString("firstName." + student.getId()));
        String lastName = StringUtils.trim(requestContext.getString("lastName." + student.getId()));
        String nickname = StringUtils.trim(requestContext.getString("nickname." + student.getId()));
        String additionalInfo = requestContext.getString("additionalInfo." + student.getId());
        String additionalContactInfo = requestContext.getString("otherContactInfo." + student.getId());
        String education = requestContext.getString("education." + student.getId());
        Double previousStudies = requestContext.getDouble("previousStudies." + student.getId());
        Date studyTimeEnd = requestContext.getDate("studyTimeEnd." + student.getId());
        Date studyStartDate = requestContext.getDate("studyStartDate." + student.getId());
        Date studyEndDate = requestContext.getDate("studyEndDate." + student.getId());
        String studyEndText = requestContext.getString("studyEndText." + student.getId());
        String tagsText = requestContext.getString("tags." + student.getId());
        StudentFunding funding = (StudentFunding) requestContext.getEnum("funding." + student.getId(), StudentFunding.class);
        Set<Tag> tagEntities = new HashSet<>();
        if (!StringUtils.isBlank(tagsText)) {
            List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
            for (String tag : tags) {
                if (!StringUtils.isBlank(tag)) {
                    Tag tagEntity = tagDAO.findByText(tag.trim());
                    if (tagEntity == null)
                        tagEntity = tagDAO.create(tag);
                    tagEntities.add(tagEntity);
                }
            }
        }
        Long entityId = requestContext.getLong("language." + student.getId());
        Language language = entityId == null ? null : languageDAO.findById(entityId);
        entityId = requestContext.getLong("activityType." + student.getId());
        StudentActivityType activityType = entityId == null ? null : activityTypeDAO.findById(entityId);
        entityId = requestContext.getLong("examinationType." + student.getId());
        StudentExaminationType examinationType = entityId == null ? null : examinationTypeDAO.findById(entityId);
        entityId = requestContext.getLong("educationalLevel." + student.getId());
        StudentEducationalLevel educationalLevel = entityId == null ? null : educationalLevelDAO.findById(entityId);
        entityId = requestContext.getLong("nationality." + student.getId());
        Nationality nationality = entityId == null ? null : nationalityDAO.findById(entityId);
        entityId = requestContext.getLong("municipality." + student.getId());
        Municipality municipality = entityId == null ? null : municipalityDAO.findById(entityId);
        entityId = requestContext.getLong("school." + student.getId());
        School school = entityId != null && entityId > 0 ? schoolDAO.findById(entityId) : null;
        entityId = requestContext.getLong("studyEndReason." + student.getId());
        StudentStudyEndReason studyEndReason = entityId == null ? null : studyEndReasonDAO.findById(entityId);
        entityId = requestContext.getLong("curriculum." + student.getId());
        Curriculum curriculum = entityId == null ? null : curriculumDAO.findById(entityId);
        entityId = requestContext.getLong("studyApprover." + student.getId());
        StaffMember approver = entityId == null ? null : staffMemberDAO.findById(entityId);
        Integer variableCount = requestContext.getInteger("variablesTable." + student.getId() + ".rowCount");
        if (variableCount != null) {
            for (int i = 0; i < variableCount; i++) {
                String colPrefix = "variablesTable." + student.getId() + "." + i;
                Long edited = requestContext.getLong(colPrefix + ".edited");
                if (Objects.equals(new Long(1), edited)) {
                    String variableKey = requestContext.getString(colPrefix + ".key");
                    String variableValue = requestContext.getString(colPrefix + ".value");
                    userVariableDAO.setUserVariable(student, variableKey, variableValue);
                }
            }
        }
        Integer lodgingPeriodsCount = requestContext.getInteger("lodgingPeriodsTable." + student.getId() + ".rowCount");
        if (lodgingPeriodsCount != null) {
            Set<Long> remainingIds = new HashSet<>();
            for (int i = 0; i < lodgingPeriodsCount; i++) {
                String colPrefix = "lodgingPeriodsTable." + student.getId() + "." + i;
                Long id = requestContext.getLong(colPrefix + ".id");
                Date begin = requestContext.getDate(colPrefix + ".begin");
                Date end = requestContext.getDate(colPrefix + ".end");
                if (id == -1 && begin != null) {
                    StudentLodgingPeriod lodgingPeriod = lodgingPeriodDAO.create(student, begin, end);
                    remainingIds.add(lodgingPeriod.getId());
                } else if (id > 0) {
                    StudentLodgingPeriod lodgingPeriod = lodgingPeriodDAO.findById(id);
                    remainingIds.add(id);
                    if (begin != null) {
                        if (lodgingPeriod != null) {
                            lodgingPeriodDAO.update(lodgingPeriod, begin, end);
                        }
                    }
                }
            }
            List<StudentLodgingPeriod> periods = lodgingPeriodDAO.listByStudent(student);
            periods.removeIf(period -> remainingIds.contains(period.getId()));
            periods.forEach(period -> lodgingPeriodDAO.delete(period));
        }
        Integer studyPeriodsCount = requestContext.getInteger("studentStudyPeriodsTable." + student.getId() + ".rowCount");
        if (studyPeriodsCount != null) {
            Set<Long> remainingIds = new HashSet<>();
            for (int i = 0; i < studyPeriodsCount; i++) {
                String colPrefix = "studentStudyPeriodsTable." + student.getId() + "." + i;
                Long id = requestContext.getLong(colPrefix + ".id");
                StudentStudyPeriodType periodType = (StudentStudyPeriodType) requestContext.getEnum(colPrefix + ".type", StudentStudyPeriodType.class);
                Date begin = requestContext.getDate(colPrefix + ".begin");
                // Null out the end date when period type allows only begin dates
                Date end = !StudentStudyPeriodType.BEGINDATE_ONLY.contains(periodType) ? requestContext.getDate(colPrefix + ".end") : null;
                if (id == -1 && begin != null) {
                    StudentStudyPeriod studyPeriod = studentStudyPeriodDAO.create(student, begin, end, periodType);
                    remainingIds.add(studyPeriod.getId());
                } else if (id > 0) {
                    StudentStudyPeriod studyPeriod = studentStudyPeriodDAO.findById(id);
                    remainingIds.add(id);
                    if (begin != null) {
                        if (studyPeriod != null) {
                            studentStudyPeriodDAO.update(studyPeriod, begin, end, periodType);
                        }
                    }
                }
            }
            List<StudentStudyPeriod> periods = studentStudyPeriodDAO.listByStudent(student);
            periods.removeIf(period -> remainingIds.contains(period.getId()));
            periods.forEach(period -> studentStudyPeriodDAO.delete(period));
        }
        boolean studiesEnded = student.getStudyEndDate() == null && studyEndDate != null;
        // Student
        studentDAO.update(student, firstName, lastName, nickname, additionalInfo, studyTimeEnd, activityType, examinationType, educationalLevel, education, nationality, municipality, language, school, curriculum, previousStudies, studyStartDate, studyEndDate, studyEndReason, studyEndText);
        studentDAO.updateApprover(student, approver);
        studentDAO.updateFunding(student, funding);
        // Tags
        studentDAO.setStudentTags(student, tagEntities);
        // Contact info
        contactInfoDAO.update(student.getContactInfo(), additionalContactInfo);
        // Student addresses
        Set<Long> existingAddresses = new HashSet<>();
        int rowCount = requestContext.getInteger("addressTable." + student.getId() + ".rowCount");
        for (int i = 0; i < rowCount; i++) {
            String colPrefix = "addressTable." + student.getId() + "." + i;
            Long addressId = requestContext.getLong(colPrefix + ".addressId");
            Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
            ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
            String name = requestContext.getString(colPrefix + ".name");
            String street = requestContext.getString(colPrefix + ".street");
            String postal = requestContext.getString(colPrefix + ".postal");
            String city = requestContext.getString(colPrefix + ".city");
            String country = requestContext.getString(colPrefix + ".country");
            boolean hasAddress = name != null || street != null || postal != null || city != null || country != null;
            if (addressId == -1 && hasAddress) {
                Address address = addressDAO.create(student.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
                existingAddresses.add(address.getId());
            } else if (addressId > 0) {
                Address address = addressDAO.findById(addressId);
                if (hasAddress) {
                    existingAddresses.add(addressId);
                    addressDAO.update(address, defaultAddress, contactType, name, street, postal, city, country);
                }
            }
        }
        List<Address> addresses = student.getContactInfo().getAddresses();
        for (int i = addresses.size() - 1; i >= 0; i--) {
            Address address = addresses.get(i);
            if (!existingAddresses.contains(address.getId())) {
                addressDAO.delete(address);
            }
        }
        // Email addresses
        Set<Long> existingEmails = new HashSet<>();
        rowCount = requestContext.getInteger("emailTable." + student.getId() + ".rowCount");
        for (int i = 0; i < rowCount; i++) {
            String colPrefix = "emailTable." + student.getId() + "." + i;
            Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
            ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
            String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
            if (StringUtils.isNotBlank(email)) {
                Long emailId = requestContext.getLong(colPrefix + ".emailId");
                if (emailId == -1) {
                    emailId = emailDAO.create(student.getContactInfo(), contactType, defaultAddress, email).getId();
                } else {
                    emailDAO.update(emailDAO.findById(emailId), contactType, defaultAddress, email);
                }
                existingEmails.add(emailId);
            }
        }
        List<Email> emails = student.getContactInfo().getEmails();
        for (int i = emails.size() - 1; i >= 0; i--) {
            Email email = emails.get(i);
            if (!existingEmails.contains(email.getId())) {
                emailDAO.delete(email);
            }
        }
        // Phone numbers
        Set<Long> existingPhoneNumbers = new HashSet<>();
        rowCount = requestContext.getInteger("phoneTable." + student.getId() + ".rowCount");
        for (int i = 0; i < rowCount; i++) {
            String colPrefix = "phoneTable." + student.getId() + "." + i;
            Boolean defaultNumber = requestContext.getBoolean(colPrefix + ".defaultNumber");
            ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
            String number = requestContext.getString(colPrefix + ".phone");
            Long phoneId = requestContext.getLong(colPrefix + ".phoneId");
            if (phoneId == -1 && number != null) {
                phoneId = phoneNumberDAO.create(student.getContactInfo(), contactType, defaultNumber, number).getId();
                existingPhoneNumbers.add(phoneId);
            } else if (phoneId > 0 && number != null) {
                phoneNumberDAO.update(phoneNumberDAO.findById(phoneId), contactType, defaultNumber, number);
                existingPhoneNumbers.add(phoneId);
            }
        }
        List<PhoneNumber> phoneNumbers = student.getContactInfo().getPhoneNumbers();
        for (int i = phoneNumbers.size() - 1; i >= 0; i--) {
            PhoneNumber phoneNumber = phoneNumbers.get(i);
            if (!existingPhoneNumbers.contains(phoneNumber.getId())) {
                phoneNumberDAO.delete(phoneNumber);
            }
        }
        Long studyProgrammeId = student.getStudyProgramme() != null ? student.getStudyProgramme().getId() : null;
        // #4226: Remove applications of nettipk/nettilukio students when their studies end
        if (studiesEnded && studyProgrammeId != null && (studyProgrammeId == 6L || studyProgrammeId == 7L)) {
            ApplicationDAO applicationDAO = DAOFactory.getInstance().getApplicationDAO();
            Application application = applicationDAO.findByStudent(student);
            if (application != null) {
                ApplicationUtils.deleteApplication(application);
            }
        }
    }
    // Contact information of a student won't be reflected to Person
    // used when searching students, so a manual re-index is needed
    person = personDAO.findById(person.getId());
    personDAO.forceReindex(person);
    requestContext.setRedirectURL(requestContext.getReferer(true));
}
Also used : ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) Email(fi.otavanopisto.pyramus.domainmodel.base.Email) Address(fi.otavanopisto.pyramus.domainmodel.base.Address) StudentStudyEndReason(fi.otavanopisto.pyramus.domainmodel.students.StudentStudyEndReason) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StudentEducationalLevel(fi.otavanopisto.pyramus.domainmodel.students.StudentEducationalLevel) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) StudentLodgingPeriodDAO(fi.otavanopisto.pyramus.dao.students.StudentLodgingPeriodDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) InternalAuthenticationProvider(fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider) MunicipalityDAO(fi.otavanopisto.pyramus.dao.base.MunicipalityDAO) StudentEducationalLevelDAO(fi.otavanopisto.pyramus.dao.students.StudentEducationalLevelDAO) List(java.util.List) UserIdentificationDAO(fi.otavanopisto.pyramus.dao.users.UserIdentificationDAO) HashSet(java.util.HashSet) Municipality(fi.otavanopisto.pyramus.domainmodel.base.Municipality) StudentExaminationType(fi.otavanopisto.pyramus.domainmodel.students.StudentExaminationType) LanguageDAO(fi.otavanopisto.pyramus.dao.base.LanguageDAO) NationalityDAO(fi.otavanopisto.pyramus.dao.base.NationalityDAO) StudentActivityTypeDAO(fi.otavanopisto.pyramus.dao.students.StudentActivityTypeDAO) Student(fi.otavanopisto.pyramus.domainmodel.students.Student) StudentDAO(fi.otavanopisto.pyramus.dao.students.StudentDAO) ContactInfoDAO(fi.otavanopisto.pyramus.dao.base.ContactInfoDAO) StudentActivityType(fi.otavanopisto.pyramus.domainmodel.students.StudentActivityType) StudentStudyPeriodType(fi.otavanopisto.pyramus.domainmodel.students.StudentStudyPeriodType) Person(fi.otavanopisto.pyramus.domainmodel.base.Person) StaleObjectStateException(org.hibernate.StaleObjectStateException) Application(fi.otavanopisto.pyramus.domainmodel.application.Application) PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) User(fi.otavanopisto.pyramus.domainmodel.users.User) Sex(fi.otavanopisto.pyramus.domainmodel.students.Sex) StudentStudyEndReasonDAO(fi.otavanopisto.pyramus.dao.students.StudentStudyEndReasonDAO) ApplicationDAO(fi.otavanopisto.pyramus.dao.application.ApplicationDAO) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) School(fi.otavanopisto.pyramus.domainmodel.base.School) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) UserDAO(fi.otavanopisto.pyramus.dao.users.UserDAO) Language(fi.otavanopisto.pyramus.domainmodel.base.Language) UserVariableDAO(fi.otavanopisto.pyramus.dao.users.UserVariableDAO) SchoolDAO(fi.otavanopisto.pyramus.dao.base.SchoolDAO) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) InternalAuth(fi.otavanopisto.pyramus.domainmodel.users.InternalAuth) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) StudentStudyPeriodDAO(fi.otavanopisto.pyramus.dao.students.StudentStudyPeriodDAO) StudentExaminationTypeDAO(fi.otavanopisto.pyramus.dao.students.StudentExaminationTypeDAO) CurriculumDAO(fi.otavanopisto.pyramus.dao.base.CurriculumDAO) TagDAO(fi.otavanopisto.pyramus.dao.base.TagDAO) StudentFunding(fi.otavanopisto.pyramus.domainmodel.students.StudentFunding) Date(java.util.Date) Nationality(fi.otavanopisto.pyramus.domainmodel.base.Nationality) StudentLodgingPeriod(fi.otavanopisto.pyramus.domainmodel.students.StudentLodgingPeriod) PersonVariableDAO(fi.otavanopisto.pyramus.dao.users.PersonVariableDAO) InternalAuthDAO(fi.otavanopisto.pyramus.dao.users.InternalAuthDAO) Curriculum(fi.otavanopisto.pyramus.domainmodel.base.Curriculum) PhoneNumber(fi.otavanopisto.pyramus.domainmodel.base.PhoneNumber) Tag(fi.otavanopisto.pyramus.domainmodel.base.Tag) StudentStudyPeriod(fi.otavanopisto.pyramus.domainmodel.students.StudentStudyPeriod) UserIdentification(fi.otavanopisto.pyramus.domainmodel.users.UserIdentification)

Example 3 with PhoneNumberDAO

use of fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO in project pyramus by otavanopisto.

the class CopyStudentStudyProgrammeJSONRequestController method process.

public void process(JSONRequestContext requestContext) {
    StudentDAO studentDAO = DAOFactory.getInstance().getStudentDAO();
    AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
    ContactInfoDAO contactInfoDAO = DAOFactory.getInstance().getContactInfoDAO();
    EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
    PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
    CreditLinkDAO creditLinkDAO = DAOFactory.getInstance().getCreditLinkDAO();
    CourseAssessmentDAO courseAssessmentDAO = DAOFactory.getInstance().getCourseAssessmentDAO();
    TransferCreditDAO transferCreditDAO = DAOFactory.getInstance().getTransferCreditDAO();
    StaffMemberDAO userDAO = DAOFactory.getInstance().getStaffMemberDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    StudyProgrammeDAO studyProgrammeDAO = DAOFactory.getInstance().getStudyProgrammeDAO();
    UserVariableDAO userVariableDAO = DAOFactory.getInstance().getUserVariableDAO();
    Long studentId = requestContext.getLong("studentId");
    Student oldStudent = studentDAO.findById(studentId);
    StaffMember loggedUser = userDAO.findById(requestContext.getLoggedUserId());
    if (!UserUtils.canAccessOrganization(loggedUser, oldStudent.getOrganization())) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Cannot access specified student");
    }
    Long newStudyProgrammeId = requestContext.getLong("newStudyProgrammeId");
    StudyProgramme newStudyProgramme = studyProgrammeDAO.findById(newStudyProgrammeId);
    if (newStudyProgramme == null) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNDEFINED, "New Study Programme not defined");
    }
    if (!UserUtils.canAccessOrganization(loggedUser, newStudyProgramme.getOrganization())) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Cannot access specified study programme");
    }
    Boolean linkCredits = requestContext.getBoolean("linkCredits");
    Boolean setAsDefaultUser = requestContext.getBoolean("setAsDefaultUser");
    Person person = oldStudent.getPerson();
    String firstName = oldStudent.getFirstName();
    String lastName = oldStudent.getLastName();
    String nickname = oldStudent.getNickname();
    String additionalInfo = oldStudent.getAdditionalInfo();
    // student.getPreviousStudies();
    Double previousStudies = null;
    // student.getStudyTimeEnd();
    Date studyTimeEnd = null;
    // student.getStudyStartDate();
    Date studyStartTime = null;
    // student.getStudyEndDate();
    Date studyEndTime = null;
    // student.getStudyEndText();
    String studyEndText = null;
    Language language = oldStudent.getLanguage();
    Municipality municipality = oldStudent.getMunicipality();
    StudentActivityType activityType = oldStudent.getActivityType();
    StudentExaminationType examinationType = oldStudent.getExaminationType();
    StudentEducationalLevel educationalLevel = oldStudent.getEducationalLevel();
    String education = oldStudent.getEducation();
    Nationality nationality = oldStudent.getNationality();
    School school = oldStudent.getSchool();
    // oldStudent.getStudyProgramme();
    StudyProgramme studyProgramme = newStudyProgramme;
    // student.getStudyEndReason();
    StudentStudyEndReason studyEndReason = null;
    Curriculum curriculum = oldStudent.getCurriculum();
    Student newStudent = studentDAO.create(person, firstName, lastName, nickname, additionalInfo, studyTimeEnd, activityType, examinationType, educationalLevel, education, nationality, municipality, language, school, studyProgramme, curriculum, previousStudies, studyStartTime, studyEndTime, studyEndReason, studyEndText, false);
    // Variables are not copied, but the default values are applied
    userVariableDAO.createDefaultValueVariables(newStudent);
    // Contact info
    contactInfoDAO.update(newStudent.getContactInfo(), oldStudent.getContactInfo().getAdditionalInfo());
    if (person.getDefaultUser() == null || Boolean.TRUE.equals(setAsDefaultUser)) {
        personDAO.updateDefaultUser(person, newStudent);
    }
    // Addresses
    List<Address> addresses = oldStudent.getContactInfo().getAddresses();
    for (int i = 0; i < addresses.size(); i++) {
        Address add = addresses.get(i);
        addressDAO.create(newStudent.getContactInfo(), add.getContactType(), add.getName(), add.getStreetAddress(), add.getPostalCode(), add.getCity(), add.getCountry(), add.getDefaultAddress());
    }
    // Email addresses
    List<Email> emails = oldStudent.getContactInfo().getEmails();
    for (int i = 0; i < emails.size(); i++) {
        Email email = emails.get(i);
        emailDAO.create(newStudent.getContactInfo(), email.getContactType(), email.getDefaultAddress(), email.getAddress());
    }
    // Phone numbers
    List<PhoneNumber> phoneNumbers = oldStudent.getContactInfo().getPhoneNumbers();
    for (int i = 0; i < phoneNumbers.size(); i++) {
        PhoneNumber phoneNumber = phoneNumbers.get(i);
        phoneNumberDAO.create(newStudent.getContactInfo(), phoneNumber.getContactType(), phoneNumber.getDefaultNumber(), phoneNumber.getNumber());
    }
    if (linkCredits) {
        List<CourseAssessment> assessments = courseAssessmentDAO.listByStudent(oldStudent);
        for (CourseAssessment assessment : assessments) {
            creditLinkDAO.create(assessment, newStudent, loggedUser);
        }
        List<TransferCredit> transferCredits = transferCreditDAO.listByStudent(oldStudent);
        for (TransferCredit transferCredit : transferCredits) {
            creditLinkDAO.create(transferCredit, newStudent, loggedUser);
        }
        List<CreditLink> creditLinks = creditLinkDAO.listByStudent(oldStudent);
        for (CreditLink creditLink : creditLinks) {
            creditLinkDAO.create(creditLink.getCredit(), newStudent, loggedUser);
        }
    }
    String redirectURL = requestContext.getRequest().getContextPath() + "/students/editstudent.page?student=" + newStudent.getPerson().getId();
    String refererAnchor = requestContext.getRefererAnchor();
    if (!StringUtils.isBlank(refererAnchor))
        redirectURL += "#" + refererAnchor;
    requestContext.setRedirectURL(redirectURL);
}
Also used : PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) Email(fi.otavanopisto.pyramus.domainmodel.base.Email) StudyProgramme(fi.otavanopisto.pyramus.domainmodel.base.StudyProgramme) Address(fi.otavanopisto.pyramus.domainmodel.base.Address) StudentStudyEndReason(fi.otavanopisto.pyramus.domainmodel.students.StudentStudyEndReason) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) StudentEducationalLevel(fi.otavanopisto.pyramus.domainmodel.students.StudentEducationalLevel) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) School(fi.otavanopisto.pyramus.domainmodel.base.School) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) TransferCreditDAO(fi.otavanopisto.pyramus.dao.grading.TransferCreditDAO) Language(fi.otavanopisto.pyramus.domainmodel.base.Language) UserVariableDAO(fi.otavanopisto.pyramus.dao.users.UserVariableDAO) CreditLink(fi.otavanopisto.pyramus.domainmodel.grading.CreditLink) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) Municipality(fi.otavanopisto.pyramus.domainmodel.base.Municipality) CourseAssessmentDAO(fi.otavanopisto.pyramus.dao.grading.CourseAssessmentDAO) StudentExaminationType(fi.otavanopisto.pyramus.domainmodel.students.StudentExaminationType) Student(fi.otavanopisto.pyramus.domainmodel.students.Student) CreditLinkDAO(fi.otavanopisto.pyramus.dao.grading.CreditLinkDAO) StudyProgrammeDAO(fi.otavanopisto.pyramus.dao.base.StudyProgrammeDAO) Date(java.util.Date) Nationality(fi.otavanopisto.pyramus.domainmodel.base.Nationality) CourseAssessment(fi.otavanopisto.pyramus.domainmodel.grading.CourseAssessment) StudentDAO(fi.otavanopisto.pyramus.dao.students.StudentDAO) ContactInfoDAO(fi.otavanopisto.pyramus.dao.base.ContactInfoDAO) StudentActivityType(fi.otavanopisto.pyramus.domainmodel.students.StudentActivityType) Curriculum(fi.otavanopisto.pyramus.domainmodel.base.Curriculum) PhoneNumber(fi.otavanopisto.pyramus.domainmodel.base.PhoneNumber) TransferCredit(fi.otavanopisto.pyramus.domainmodel.grading.TransferCredit) Person(fi.otavanopisto.pyramus.domainmodel.base.Person)

Example 4 with PhoneNumberDAO

use of fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO in project pyramus by otavanopisto.

the class CreateSchoolJSONRequestController method process.

/**
 * Processes the request to create a new grading scale.
 *
 * @param requestContext The JSON request context
 */
public void process(JSONRequestContext requestContext) {
    SchoolDAO schoolDAO = DAOFactory.getInstance().getSchoolDAO();
    SchoolFieldDAO schoolFieldDAO = DAOFactory.getInstance().getSchoolFieldDAO();
    SchoolVariableDAO schoolVariableDAO = DAOFactory.getInstance().getSchoolVariableDAO();
    AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
    EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
    PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
    TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
    ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
    BillingDetailsDAO billingDetailsDAO = DAOFactory.getInstance().getBillingDetailsDAO();
    String schoolCode = requestContext.getString("code");
    String schoolName = requestContext.getString("name");
    String tagsText = requestContext.getString("tags");
    Long schoolFieldId = requestContext.getLong("schoolFieldId");
    SchoolField schoolField = null;
    if (schoolFieldId != null && schoolFieldId.intValue() >= 0)
        schoolField = schoolFieldDAO.findById(schoolFieldId);
    Set<Tag> tagEntities = new HashSet<>();
    if (!StringUtils.isBlank(tagsText)) {
        List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
        for (String tag : tags) {
            if (!StringUtils.isBlank(tag)) {
                Tag tagEntity = tagDAO.findByText(tag.trim());
                if (tagEntity == null)
                    tagEntity = tagDAO.create(tag);
                tagEntities.add(tagEntity);
            }
        }
    }
    String billingPersonName = requestContext.getString("billingDetailsPersonName");
    String billingCompanyName = requestContext.getString("billingDetailsCompanyName");
    String billingStreetAddress1 = requestContext.getString("billingDetailsStreetAddress1");
    String billingStreetAddress2 = requestContext.getString("billingDetailsStreetAddress2");
    String billingPostalCode = requestContext.getString("billingDetailsPostalCode");
    String billingCity = requestContext.getString("billingDetailsCity");
    String billingRegion = requestContext.getString("billingDetailsRegion");
    String billingCountry = requestContext.getString("billingDetailsCountry");
    String billingPhoneNumber = requestContext.getString("billingDetailsPhoneNumber");
    String billingEmailAddress = requestContext.getString("billingDetailsEmailAddress");
    String billingElectronicBillingAddress = requestContext.getString("billingDetailsElectronicBillingAddress");
    String billingElectronicBillingOperator = requestContext.getString("billingDetailsElectronicBillingOperator");
    String billingCompanyIdentifier = requestContext.getString("billingDetailsCompanyIdentifier");
    String billingReferenceNumber = requestContext.getString("billingDetailsReferenceNumber");
    String billingNotes = requestContext.getString("billingDetailsNotes");
    BillingDetails billingDetails = billingDetailsDAO.create(billingPersonName, billingCompanyName, billingStreetAddress1, billingStreetAddress2, billingPostalCode, billingCity, billingRegion, billingCountry, billingPhoneNumber, billingEmailAddress, billingElectronicBillingAddress, billingElectronicBillingOperator, billingCompanyIdentifier, billingReferenceNumber, billingNotes);
    School school = schoolDAO.create(schoolCode, schoolName, schoolField, billingDetails);
    // Tags
    schoolDAO.updateTags(school, tagEntities);
    // Addresses
    int addressCount = requestContext.getInteger("addressTable.rowCount");
    for (int i = 0; i < addressCount; i++) {
        String colPrefix = "addressTable." + i;
        Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
        ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
        String name = requestContext.getString(colPrefix + ".name");
        String street = requestContext.getString(colPrefix + ".street");
        String postal = requestContext.getString(colPrefix + ".postal");
        String city = requestContext.getString(colPrefix + ".city");
        String country = requestContext.getString(colPrefix + ".country");
        boolean hasAddress = name != null || street != null || postal != null || city != null || country != null;
        if (hasAddress) {
            addressDAO.create(school.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
        }
    }
    // Email addresses
    int emailCount = requestContext.getInteger("emailTable.rowCount");
    for (int i = 0; i < emailCount; i++) {
        String colPrefix = "emailTable." + i;
        Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
        ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
        String email = requestContext.getString(colPrefix + ".email");
        // Trim the email address
        email = email != null ? email.trim() : null;
        if (email != null) {
            emailDAO.create(school.getContactInfo(), contactType, defaultAddress, email);
        }
    }
    // Phone numbers
    int phoneCount = requestContext.getInteger("phoneTable.rowCount");
    for (int i = 0; i < phoneCount; i++) {
        String colPrefix = "phoneTable." + i;
        Boolean defaultNumber = requestContext.getBoolean(colPrefix + ".defaultNumber");
        ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
        String number = requestContext.getString(colPrefix + ".phone");
        if (number != null) {
            phoneNumberDAO.create(school.getContactInfo(), contactType, defaultNumber, number);
        }
    }
    // Variables
    Integer variableCount = requestContext.getInteger("variablesTable.rowCount");
    if (variableCount != null) {
        for (int i = 0; i < variableCount; i++) {
            String colPrefix = "variablesTable." + i;
            String key = requestContext.getRequest().getParameter(colPrefix + ".key");
            String value = requestContext.getRequest().getParameter(colPrefix + ".value");
            schoolVariableDAO.setVariable(school, key, value);
        }
    }
    String redirectURL = requestContext.getRequest().getContextPath() + "/settings/editschool.page?school=" + school.getId();
    String refererAnchor = requestContext.getRefererAnchor();
    if (!StringUtils.isBlank(refererAnchor))
        redirectURL += "#" + refererAnchor;
    requestContext.setRedirectURL(redirectURL);
}
Also used : SchoolField(fi.otavanopisto.pyramus.domainmodel.base.SchoolField) PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) TagDAO(fi.otavanopisto.pyramus.dao.base.TagDAO) BillingDetails(fi.otavanopisto.pyramus.domainmodel.base.BillingDetails) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) School(fi.otavanopisto.pyramus.domainmodel.base.School) SchoolFieldDAO(fi.otavanopisto.pyramus.dao.base.SchoolFieldDAO) BillingDetailsDAO(fi.otavanopisto.pyramus.dao.base.BillingDetailsDAO) SchoolDAO(fi.otavanopisto.pyramus.dao.base.SchoolDAO) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) Tag(fi.otavanopisto.pyramus.domainmodel.base.Tag) SchoolVariableDAO(fi.otavanopisto.pyramus.dao.base.SchoolVariableDAO) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) HashSet(java.util.HashSet)

Example 5 with PhoneNumberDAO

use of fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO in project pyramus by otavanopisto.

the class CreateUserJSONRequestController method process.

/**
 * Processes the request to create a new user. Simply gathers the fields submitted from the
 * web page and adds the user to the database.
 *
 * @param requestContext The JSON request context
 */
public void process(JSONRequestContext requestContext) {
    StaffMemberDAO userDAO = DAOFactory.getInstance().getStaffMemberDAO();
    AddressDAO addressDAO = DAOFactory.getInstance().getAddressDAO();
    EmailDAO emailDAO = DAOFactory.getInstance().getEmailDAO();
    PhoneNumberDAO phoneNumberDAO = DAOFactory.getInstance().getPhoneNumberDAO();
    TagDAO tagDAO = DAOFactory.getInstance().getTagDAO();
    ContactTypeDAO contactTypeDAO = DAOFactory.getInstance().getContactTypeDAO();
    PersonDAO personDAO = DAOFactory.getInstance().getPersonDAO();
    UserIdentificationDAO userIdentificationDAO = DAOFactory.getInstance().getUserIdentificationDAO();
    OrganizationDAO organizationDAO = DAOFactory.getInstance().getOrganizationDAO();
    Long personId = requestContext.getLong("personId");
    int emailCount2 = requestContext.getInteger("emailTable.rowCount");
    for (int i = 0; i < emailCount2; i++) {
        String colPrefix = "emailTable." + i;
        String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
        if (StringUtils.isNotBlank(email)) {
            ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
            if (!UserUtils.isAllowedEmail(email, contactType, personId)) {
                throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.emailInUse"));
            }
        }
    }
    // Fields from the web page
    String firstName = requestContext.getString("firstName");
    String lastName = requestContext.getString("lastName");
    String title = requestContext.getString("title");
    Role role = Role.getRole(requestContext.getInteger("role"));
    String tagsText = requestContext.getString("tags");
    String username = requestContext.getString("username");
    String password = requestContext.getString("password1");
    String password2 = requestContext.getString("password2");
    Long organizationId = requestContext.getLong("organizationId");
    User loggedUser = userDAO.findById(requestContext.getLoggedUserId());
    Organization organization = organizationId != null ? organizationDAO.findById(organizationId) : null;
    if (!UserUtils.canAccessOrganization(loggedUser, organization)) {
        throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, "Invalid organization.");
    }
    Set<Tag> tagEntities = new HashSet<>();
    if (!StringUtils.isBlank(tagsText)) {
        List<String> tags = Arrays.asList(tagsText.split("[\\ ,]"));
        for (String tag : tags) {
            if (!StringUtils.isBlank(tag)) {
                Tag tagEntity = tagDAO.findByText(tag.trim());
                if (tagEntity == null)
                    tagEntity = tagDAO.create(tag);
                tagEntities.add(tagEntity);
            }
        }
    }
    // User
    Person person = personId != null ? personDAO.findById(personId) : personDAO.create(null, null, null, null, Boolean.FALSE);
    StaffMember user = userDAO.create(organization, firstName, lastName, role, person, false);
    if (title != null)
        userDAO.updateTitle(user, title);
    if (person.getDefaultUser() == null) {
        personDAO.updateDefaultUser(person, user);
    }
    if (AuthenticationProviderVault.getInstance().hasInternalStrategies()) {
        boolean usernameBlank = StringUtils.isBlank(username);
        boolean passwordBlank = StringUtils.isBlank(password);
        // TODO: Support multiple internal authentication sources
        if (!usernameBlank) {
            // #921: Check username
            InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO();
            InternalAuth internalAuth = internalAuthDAO.findByUsername(username);
            if (internalAuth != null) {
                throw new RuntimeException(Messages.getInstance().getText(requestContext.getRequest().getLocale(), "generic.errors.usernameInUse"));
            }
            InternalAuthenticationProvider internalAuthenticationProvider = AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders().get(0);
            if (!passwordBlank) {
                if (!password.equals(password2))
                    throw new SmvcRuntimeException(PyramusStatusCode.PASSWORD_MISMATCH, "Passwords don't match");
            }
            String externalId = internalAuthenticationProvider.createCredentials(username, password);
            userIdentificationDAO.create(person, internalAuthenticationProvider.getName(), externalId);
        }
    }
    // Tags
    userDAO.updateTags(user, tagEntities);
    // Addresses
    int addressCount = requestContext.getInteger("addressTable.rowCount");
    for (int i = 0; i < addressCount; i++) {
        String colPrefix = "addressTable." + i;
        Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
        ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
        String name = requestContext.getString(colPrefix + ".name");
        String street = requestContext.getString(colPrefix + ".street");
        String postal = requestContext.getString(colPrefix + ".postal");
        String city = requestContext.getString(colPrefix + ".city");
        String country = requestContext.getString(colPrefix + ".country");
        boolean hasAddress = name != null || street != null || postal != null || city != null || country != null;
        if (hasAddress) {
            addressDAO.create(user.getContactInfo(), contactType, name, street, postal, city, country, defaultAddress);
        }
    }
    // Email addresses
    int emailCount = requestContext.getInteger("emailTable.rowCount");
    for (int i = 0; i < emailCount; i++) {
        String colPrefix = "emailTable." + i;
        Boolean defaultAddress = requestContext.getBoolean(colPrefix + ".defaultAddress");
        ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
        String email = StringUtils.trim(requestContext.getString(colPrefix + ".email"));
        if (StringUtils.isNotBlank(email)) {
            emailDAO.create(user.getContactInfo(), contactType, defaultAddress, email);
        }
    }
    // Phone numbers
    int phoneCount = requestContext.getInteger("phoneTable.rowCount");
    for (int i = 0; i < phoneCount; i++) {
        String colPrefix = "phoneTable." + i;
        Boolean defaultNumber = requestContext.getBoolean(colPrefix + ".defaultNumber");
        ContactType contactType = contactTypeDAO.findById(requestContext.getLong(colPrefix + ".contactTypeId"));
        String number = requestContext.getString(colPrefix + ".phone");
        if (number != null) {
            phoneNumberDAO.create(user.getContactInfo(), contactType, defaultNumber, number);
        }
    }
    // Redirect to the Edit User view
    requestContext.setRedirectURL(requestContext.getRequest().getContextPath() + "/users/edituser.page?userId=" + user.getId());
}
Also used : PhoneNumberDAO(fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO) ContactType(fi.otavanopisto.pyramus.domainmodel.base.ContactType) User(fi.otavanopisto.pyramus.domainmodel.users.User) Organization(fi.otavanopisto.pyramus.domainmodel.base.Organization) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) EmailDAO(fi.otavanopisto.pyramus.dao.base.EmailDAO) PersonDAO(fi.otavanopisto.pyramus.dao.base.PersonDAO) StaffMemberDAO(fi.otavanopisto.pyramus.dao.users.StaffMemberDAO) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) InternalAuthenticationProvider(fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider) ContactTypeDAO(fi.otavanopisto.pyramus.dao.base.ContactTypeDAO) InternalAuth(fi.otavanopisto.pyramus.domainmodel.users.InternalAuth) OrganizationDAO(fi.otavanopisto.pyramus.dao.base.OrganizationDAO) AddressDAO(fi.otavanopisto.pyramus.dao.base.AddressDAO) UserIdentificationDAO(fi.otavanopisto.pyramus.dao.users.UserIdentificationDAO) HashSet(java.util.HashSet) TagDAO(fi.otavanopisto.pyramus.dao.base.TagDAO) UserRole(fi.otavanopisto.pyramus.framework.UserRole) Role(fi.otavanopisto.pyramus.domainmodel.users.Role) InternalAuthDAO(fi.otavanopisto.pyramus.dao.users.InternalAuthDAO) Tag(fi.otavanopisto.pyramus.domainmodel.base.Tag) Person(fi.otavanopisto.pyramus.domainmodel.base.Person)

Aggregations

PhoneNumberDAO (fi.otavanopisto.pyramus.dao.base.PhoneNumberDAO)10 AddressDAO (fi.otavanopisto.pyramus.dao.base.AddressDAO)9 EmailDAO (fi.otavanopisto.pyramus.dao.base.EmailDAO)9 ContactTypeDAO (fi.otavanopisto.pyramus.dao.base.ContactTypeDAO)8 PersonDAO (fi.otavanopisto.pyramus.dao.base.PersonDAO)8 ContactType (fi.otavanopisto.pyramus.domainmodel.base.ContactType)8 School (fi.otavanopisto.pyramus.domainmodel.base.School)8 SchoolDAO (fi.otavanopisto.pyramus.dao.base.SchoolDAO)6 TagDAO (fi.otavanopisto.pyramus.dao.base.TagDAO)6 StudentDAO (fi.otavanopisto.pyramus.dao.students.StudentDAO)6 Person (fi.otavanopisto.pyramus.domainmodel.base.Person)6 Tag (fi.otavanopisto.pyramus.domainmodel.base.Tag)6 Student (fi.otavanopisto.pyramus.domainmodel.students.Student)6 HashSet (java.util.HashSet)6 SmvcRuntimeException (fi.internetix.smvc.SmvcRuntimeException)5 ContactInfoDAO (fi.otavanopisto.pyramus.dao.base.ContactInfoDAO)5 UserVariableDAO (fi.otavanopisto.pyramus.dao.users.UserVariableDAO)5 Address (fi.otavanopisto.pyramus.domainmodel.base.Address)5 Email (fi.otavanopisto.pyramus.domainmodel.base.Email)5 Language (fi.otavanopisto.pyramus.domainmodel.base.Language)5