def validate_form(self, form):
        is_valid = super(OfficeAdminExtraGeoLocationModelView, self).validate_form(form)
        if is_valid and form.data.get('date_end'):
            if datetime.datetime.utcnow() >= form.data['date_end']:
                msg = ("La date de fin doit être dans le futur.")
                flash(msg, 'error')
                return False
        if is_valid and form.data.get('codes'):
            for code in OfficeAdminExtraGeoLocation.codes_as_list(form.data['codes']):
                if not any([geocoding.is_departement(code), geocoding.is_commune_id(code)]):
                    msg = (
                        "`%s` n'est pas un code commune (INSEE) ou un numéro de département valide."
                        "<br>"
                        "Assurez-vous de ne saisir qu'un élément par ligne."
                        % code
                    )
                    flash(Markup(msg), 'error')
                    return False

        return is_valid
Пример #2
0
 def codes_as_geolocations(codes):
     """
     Converts the given string of codes to an array of `lat/lon tuples`.
     E.g.:
     [
         (48.68, 6.17),
         (49.15, 6.22),
     ]
     """
     geolocations = []
     codes_list = OfficeAdminExtraGeoLocation.codes_as_list(codes)
     for code in codes_list:
         if geocoding.is_departement(code):
             for city in geocoding.get_all_cities_from_departement(code):
                 geolocations.append(
                     (city['coords']['lat'], city['coords']['lon']))
         elif geocoding.is_commune_id(code):
             city = geocoding.get_city_by_commune_id(code)
             geolocations.append(
                 (city['coords']['lat'], city['coords']['lon']))
     return geolocations
Пример #3
0
def create_hidden_market_fetcher(location, departements, request_args):
    """
    Returns the filters given a set of parameters.

    Required parameters:
    - `location` (Location): location near which to search. May be None if departements is set.
    - `departements`: a list of french "departements". May be None if location is set.
    - `rome_codes`: one or more "Pôle emploi ROME" codes, comma separated.

    Optional parameters:
    - `distance`: perimeter of the search radius (in Km) in which to search.
    - `page`: number of the requested page.
    - `page_size`: number of results per page (
        maximum : pagination.OFFICES_MAXIMUM_PAGE_SIZE,
        default: pagination.OFFICES_PER_PAGE
        ).
    - `naf_codes`: one or more naf_codes, comma separated. If empty or missing, no filter will be used
    - `contract`: one value, only between 'all' (default) or 'alternance'
    - `sort`: one value, only between 'score' (default) and 'distance'
    - `headcount`: one value, only between 'all' (default), 'small' or 'big'
    - `departments`: one or more departments, comma separated.
    - `flag_pmsmp`: 1 to see only companies having flag_pmsmp=1, all companies otherwise.
    """
    # Arguments to build the HiddenMarketFetcher object
    kwargs = {}

    # Sort
    sort = sorting.SORT_FILTER_DEFAULT
    if 'sort' in request_args:
        sort = request_args.get('sort')
        if sort not in sorting.SORT_FILTERS:
            raise InvalidFetcherArgument('sort. Possible values : %s' % ', '.join(sorting.SORT_FILTERS))
    if sort != sorting.SORT_FILTER_SCORE and location is None:
        raise InvalidFetcherArgument('sort. %s is the only possible value with departement search. Please remove sort or departments.' % sorting.SORT_FILTER_SCORE)

    kwargs['sort'] = sort

    # Rome_code
    rome_codes = request_args.get('rome_codes')
    rome_codes_keyword_search = request_args.get('rome_codes_keyword_search')

    if not rome_codes_keyword_search:
        if not rome_codes:
            raise InvalidFetcherArgument('you must use rome_codes or rome_codes_keyword_search')
    else:
        if rome_codes:
            raise InvalidFetcherArgument('you must either use rome_codes or rome_codes_keyword_search but not both')
        else:
            # ROME keyword search : select first match of what the autocomplete result would be
            suggestions = autocomplete.build_job_label_suggestions(rome_codes_keyword_search, size=1)
            if len(suggestions) >= 1:
                rome_codes = suggestions[0]['id']
            else:
                msg = 'No match found for rome_codes_keyword_search.'
                raise InvalidFetcherArgument(msg)

    rome_code_list = [code.upper() for code in rome_codes.split(',')]

    validate_rome_codes(rome_code_list)

    kwargs['romes'] = rome_code_list

    # Page and page_size
    page, page_size = get_page_and_page_size(request_args)
    kwargs['to_number'] = page * page_size
    kwargs['from_number'] = kwargs['to_number'] - page_size + 1

    # Distance
    # WARNING: MAP uses distance=0 in their use of the API.
    kwargs['distance'] = get_distance(request_args)
    if request_args.get('distance') is not None and location is None:
        raise InvalidFetcherArgument('filter. Long/lat is not provided so distance can not be computed. Please remove the distance param.')

    # Naf
    naf_codes = {}
    if request_args.get('naf_codes'):
        naf_codes = [naf.upper() for naf in request_args['naf_codes'].split(',')]
        expected_naf_codes = mapping_util.map_romes_to_nafs(kwargs['romes'])
        invalid_nafs = [naf for naf in naf_codes if naf not in expected_naf_codes]
        if invalid_nafs:
            raise InvalidFetcherArgument('NAF code(s): %s. Possible values : %s ' % (
                ' '.join(invalid_nafs), ', '.join(expected_naf_codes)
            ))
    kwargs['naf_codes'] = naf_codes

    # Convert contract to hiring type (DPAE/LBB or Alternance/LBA)
    contract = request_args.get('contract', hiring_type_util.CONTRACT_DEFAULT)
    if contract not in hiring_type_util.CONTRACT_VALUES:
        raise InvalidFetcherArgument('contract. Possible values : %s' % ', '.join(hiring_type_util.CONTRACT_VALUES))
    kwargs['hiring_type'] = hiring_type_util.CONTRACT_TO_HIRING_TYPE[contract]

    # Headcount
    headcount = settings.HEADCOUNT_WHATEVER
    if 'headcount' in request_args:
        headcount = settings.HEADCOUNT_VALUES.get(request_args.get('headcount'))
        if not headcount:
            raise InvalidFetcherArgument('headcount. Possible values : %s' % ', '.join(sorted(settings.HEADCOUNT_VALUES.keys())))
    kwargs['headcount'] = headcount

    # Departments
    departments = []
    if 'departments' in request_args and request_args.get('departments'):
        departments = request_args.get('departments').split(',')
        unknown_departments = [dep for dep in departments if not geocoding.is_departement(dep)]
        if unknown_departments:
            raise InvalidFetcherArgument('departments : %s' % ', '.join(unknown_departments))
    kwargs['departments'] = departments

    # from value in GET to enum
    # audience filter defaults to ALL
    kwargs['audience'] = get_enum_from_value(AudienceFilter, request_args.get('audience'), AudienceFilter.ALL)

    if (api_util.has_scope(request.args['user'], request.args.get('origin_user'),  Scope.COMPANY_PMSMP)):
        kwargs['flag_pmsmp'] = check_bool_argument(request_args, 'flag_pmsmp', 0)

    if location is not None:
        return HiddenMarketFetcher(location.longitude, location.latitude, **kwargs)

    return HiddenMarketFetcher(None, None, **kwargs)
 def test_is_departement(self):
     self.assertFalse(geocoding.is_departement("AAAAA"))
     self.assertTrue(geocoding.is_departement("57"))