Example #1
0
        def import_postal_address(info: Dict[str, Any]) -> None:
            if "PostalAddress" not in info:
                return
            postal_address = info["PostalAddress"]

            if "StandardAddressIdentifier" not in postal_address:
                return
            address_string = postal_address["StandardAddressIdentifier"]

            if "PostalCode" not in postal_address:
                return
            zip_code = postal_address["PostalCode"]

            logger.debug("Look in Dawa: {}".format(address_string))
            dar_uuid = dawa_helper.dawa_lookup(address_string, zip_code)
            logger.debug("DAR: {}".format(dar_uuid))

            if dar_uuid is None:
                logger.error(
                    "Unable to lookup address: {}".format(address_string))
                self.address_errors[unit_id] = info
                return

            self.importer.add_address_type(
                organisation_unit=unit_id,
                type_ref="AddressMailUnit",
                value=dar_uuid,
                date_from=date_from,
            )
Example #2
0
    def _condense_employee_opus_addresses(self, employee):
        opus_addresses = {}
        if "email" in employee and not self.settings.get(
                "integrations.opus.skip_employee_email", False):
            opus_addresses["email"] = employee["email"]

        opus_addresses["phone"] = None
        if employee["workPhone"] is not None:
            phone = opus_helpers.parse_phone(employee["workPhone"])
            if phone is not None:
                opus_addresses["phone"] = phone

        if ("postalCode" in employee and employee["address"]
                and not self.settings.get(
                    "integrations.opus.skip_employee_address", False)):
            if isinstance(employee["address"], dict):
                logger.info("Protected addres, cannont import")
            else:
                address_string = employee["address"]
                zip_code = employee["postalCode"]
                try:
                    address_uuid = dawa_helper.dawa_lookup(
                        address_string, zip_code)
                except:
                    address_uuid = None
                if address_uuid:
                    opus_addresses["dar"] = address_uuid
                else:
                    logger.warning("Could not find address in DAR")
        return opus_addresses
Example #3
0
    def _update_unit_addresses(self, unit):
        calculated_uuid = opus_helpers.generate_uuid(unit["@id"])
        unit_addresses = self.helper.read_ou_address(calculated_uuid,
                                                     scope=None,
                                                     return_all=True)

        address_dict = {}
        for address in unit_addresses:
            if address_dict.get(address["type"]) is not None:
                # More than one of this type exist in MO, this is not allowed.
                msg = "Inconsistent addresses for unit: {}"
                logger.error(msg.format(calculated_uuid))
            # if address['value'] not in ('9999999999999', '0000000000'):
            address_dict[address["type"]] = {
                "value": address["value"],
                "uuid": address["uuid"],
            }

        if unit.get("street") and unit.get("zipCode"):
            try:
                address_uuid = dawa_helper.dawa_lookup(unit["street"],
                                                       unit["zipCode"])
            except:
                address_uuid = None
            if address_uuid:
                logger.debug("Found DAR uuid: {}".format(address_uuid))
                unit["dar"] = address_uuid
            else:
                logger.warning("Failed to lookup {}, {}".format(
                    unit["street"], unit["zipCode"]))

        for addr_type, mo_addr_type in UNIT_ADDRESS_CHECKS.items():
            # addr_type is the opus name for the address, mo_addr_type
            # is read from MO
            if unit.get(addr_type) is None:
                continue

            addr_type_uuid = self.helper.ensure_class_in_facet(
                "org_unit_address_type",
                mo_addr_type,
                scope=predefined_scopes.get(mo_addr_type),
            )
            current = address_dict.get(str(addr_type_uuid))
            args = {
                "address_type": {
                    "uuid": str(addr_type_uuid)
                },
                "value": unit[addr_type],
                "validity": {
                    "from": self.xml_date.strftime("%Y-%m-%d"),
                    "to": None
                },
                "unit_uuid": str(calculated_uuid),
            }
            self._perform_address_update(args, current)
Example #4
0
    def read_locations(self, unit):
        # url = 'app-organisation/GetOrganisationEnhedIntegration?uuid={}'
        # integration_values = self._apos_lookup(url.format(unit['@uuid']))
        # print(integration_values)

        url = 'app-organisation/GetLocations?uuid={}'
        locations = self._apos_lookup(url.format(unit['@uuid']))

        mo_locations = []
        if int(locations['total']) == 0:
            # Return imidiately if no locations are found
            return mo_locations
        locations = locations['location']
        if not isinstance(locations, list):
            locations = [locations]

        for location in locations:
            address_string = None
            if '@adresse' not in location:
                if len(location['@navn']) > 0:
                    address = location['@navn'].split(' ')
                    if len(address) == 1:
                        continue
                    zip_code = address[-2][:4]
                    address_string = ''
                    for i in range(0, len(address) - 2):
                        address_string += address[i] + ' '
                    address_string = address_string[:-2]
            else:
                uuid = location['@adresse']
                url = 'app-part/GetAdresseList?uuid={}'
                apos_address = self._apos_lookup(url.format(uuid))
                address_string = apos_address['adresse'][
                    '@vejadresseringsnavn']
                zip_code = apos_address['adresse']['@postnummer']

            if address_string:
                dawa_uuid = dawa_helper.dawa_lookup(address_string, zip_code)
            else:
                dawa_uuid = None

            pnummer = location.get('@pnummer', None)
            primary = (location.get('@primary', None) == 'JA')
            mo_location = {
                'pnummer': pnummer,
                'primary': primary,
                'dawa_uuid': dawa_uuid
            }
            mo_locations.append(mo_location)
        return mo_locations
Example #5
0
    def _import_employee(self, employee):
        # UNUSED KEYS:
        # '@lastChanged'

        logger.debug('Employee object: {}'.format(employee))
        if 'cpr' in employee:
            cpr = employee['cpr']['#text']
            if employee['firstName'] is None and employee['lastName'] is None:
                # Service user, skip
                logger.info(
                    'Skipped {}, we think it is a serviceuser'.format(cpr))
                return

        else:  # This employee has left the organisation
            if not employee['@action'] == 'leave':
                msg = 'Unknown action: {}'.format(employee['@action'])
                logger.error(msg)
                raise UnknownOpusAction(msg)
            return

        self._update_ad_map(cpr)

        uuid = self.employee_forced_uuids.get(cpr)
        logger.info('Employee in force list: {} {}'.format(cpr, uuid))
        if uuid is None and 'ObjectGuid' in self.ad_people[cpr]:
            uuid = self.ad_people[cpr]['ObjectGuid']

        date_from = employee['entryDate']
        date_to = employee['leaveDate']
        if date_from is None:
            date_from = '1930-01-01'

        # Only add employee and address information once, this info is duplicated
        # if the employee has multiple engagements
        if not self.importer.check_if_exists('employee', cpr):
            self.employee_addresses[cpr] = {}
            self.importer.add_employee(identifier=cpr,
                                       name=(employee['firstName'],
                                             employee['lastName']),
                                       cpr_no=cpr,
                                       uuid=uuid)

        if 'SamAccountName' in self.ad_people[cpr]:
            self.importer.join_itsystem(
                employee=cpr,
                user_key=self.ad_people[cpr]['SamAccountName'],
                itsystem_ref='AD',
                date_from='1930-01-01')

        if 'userId' in employee:
            self.importer.join_itsystem(employee=cpr,
                                        user_key=employee['userId'],
                                        itsystem_ref='Opus',
                                        date_from=date_from,
                                        date_to=date_to)

        if 'email' in employee:
            self.employee_addresses[cpr]['EmailEmployee'] = employee['email']
        if employee['workPhone'] is not None:
            phone = opus_helpers.parse_phone(employee['workPhone'])
            self.employee_addresses[cpr]['PhoneEmployee'] = phone

        if 'postalCode' in employee and employee['address']:
            if isinstance(employee['address'], dict):
                # This is a protected address, cannot import
                pass
            else:
                address_string = employee['address']
                zip_code = employee["postalCode"]
                addr_uuid = dawa_helper.dawa_lookup(address_string, zip_code)
                if addr_uuid:
                    self.employee_addresses[cpr][
                        'AdressePostEmployee'] = addr_uuid

        job = employee["position"]
        self._add_klasse(job, job, 'engagement_job_function')

        if 'workContractText' in employee:
            contract = employee['workContractText']
        else:
            contract = 'Ansat'
        self._add_klasse(contract, contract, 'engagement_type')

        org_unit = employee['orgUnit']
        job_id = employee['@id']
        # engagement_uuid = opus_helpers.generate_uuid(job_id)

        # Every engagement is initially imported as non-primary,
        # a seperate script will correct this after import.
        # This allows separate rules for primary calculation.
        logger.info('Add engagement: {} to {}'.format(job_id, cpr))
        self.importer.add_engagement(
            employee=cpr,
            # uuid=str(engagement_uuid),
            organisation_unit=org_unit,
            primary_ref='non-primary',
            user_key=job_id,
            job_function_ref=job,
            engagement_type_ref=contract,
            date_from=date_from,
            date_to=date_to)

        if employee['isManager'] == 'true':
            manager_type_ref = 'manager_type_' + job
            self._add_klasse(manager_type_ref, job, 'manager_type')

            # Opus has two levels of manager_level, since MO handles only one
            # they are concatenated into one.
            manager_level = '{}.{}'.format(employee['superiorLevel'],
                                           employee['subordinateLevel'])
            self._add_klasse(manager_level, manager_level, 'manager_level')
            logger.info('{} is manager {}'.format(cpr, manager_level))
            self.importer.add_manager(employee=cpr,
                                      user_key=job_id,
                                      organisation_unit=org_unit,
                                      manager_level_ref=manager_level,
                                      manager_type_ref=manager_type_ref,
                                      responsibility_list=['Lederansvar'],
                                      date_from=date_from,
                                      date_to=date_to)

        if 'function' in employee:
            if not isinstance(employee['function'], list):
                roles = [employee['function']]
            else:
                roles = employee['function']

            for role in roles:
                logger.debug('{} has role {}'.format(cpr, role))
                # We have only a single class for roles, must combine the information
                if 'roleText' in role:
                    combined_role = '{} - {}'.format(role['artText'],
                                                     role['roleText'])
                else:
                    combined_role = role['artText']
                self._add_klasse(combined_role, combined_role, 'role_type')

                date_from = role['@startDate']
                if role['@endDate'] == '9999-12-31':
                    date_to = None
                else:
                    date_to = role['@endDate']

                self.importer.add_role(employee=cpr,
                                       organisation_unit=org_unit,
                                       role_type_ref=combined_role,
                                       date_from=date_from,
                                       date_to=date_to)
Example #6
0
    def _import_org_unit(self, unit):
        try:
            org_type = unit['orgType']
            self._add_klasse(org_type, unit['orgTypeTxt'], 'org_unit_type')
        except KeyError:
            org_type = 'Enhed'
            self._add_klasse(org_type, 'Enhed', 'org_unit_type')

        identifier = unit['@id']
        uuid = opus_helpers.generate_uuid(identifier)
        logger.debug('Generated uuid for {}: {}'.format(unit['@id'], uuid))

        user_key = unit['shortName']

        if unit['startDate'] == '1900-01-01':
            date_from = '1930-01-01'
        else:
            date_from = unit['startDate']

        if unit['endDate'] == '9999-12-31':
            date_to = None
        else:
            date_to = unit['endDate']

        name = unit['longName']

        parent_org = unit.get("parentOrgUnit")
        if parent_org == self.organisation_id and not self.import_first:
            parent_org = None

        self.importer.add_organisation_unit(identifier=identifier,
                                            name=name,
                                            uuid=str(uuid),
                                            user_key=user_key,
                                            parent_ref=parent_org,
                                            type_ref=org_type,
                                            date_from=date_from,
                                            date_to=date_to)

        if 'seNr' in unit:
            self.importer.add_address_type(organisation_unit=identifier,
                                           value=unit['seNr'],
                                           type_ref='SE',
                                           date_from=date_from,
                                           date_to=date_to)

        if 'cvrNr' in unit:
            self.importer.add_address_type(organisation_unit=identifier,
                                           value=unit['cvrNr'],
                                           type_ref='CVR',
                                           date_from=date_from,
                                           date_to=date_to)

        if 'eanNr' in unit and (not unit['eanNr'] == '9999999999999'):
            self.importer.add_address_type(organisation_unit=identifier,
                                           value=unit['eanNr'],
                                           type_ref='EAN',
                                           date_from=date_from,
                                           date_to=date_to)

        if 'pNr' in unit and (not unit['pNr'] == '0000000000'):
            self.importer.add_address_type(organisation_unit=identifier,
                                           value=unit['pNr'],
                                           type_ref='Pnummer',
                                           date_from=date_from,
                                           date_to=date_to)

        if unit['phoneNumber']:
            self.importer.add_address_type(organisation_unit=identifier,
                                           value=unit['phoneNumber'],
                                           type_ref='PhoneUnit',
                                           date_from=date_from,
                                           date_to=date_to)

        address_string = unit['street']
        zip_code = unit['zipCode']
        if address_string and zip_code:
            address_uuid = dawa_helper.dawa_lookup(address_string, zip_code)
            if address_uuid:
                self.importer.add_address_type(organisation_unit=identifier,
                                               value=address_uuid,
                                               type_ref='AddressPostUnit',
                                               date_from=date_from,
                                               date_to=date_to)