Example #1
0
    def get_aggs(self, obj_list):
        """Apply aggregations transformation."""
        aggs = obj_list.get("aggregations")
        if not aggs:
            return missing

        for name, agg in aggs.items():
            # Aggregation key/name must match vocabulary id.
            vocab = Vocabularies.get_vocabulary(name)
            if not vocab:
                continue

            buckets = agg.get('buckets')
            if buckets:
                apply_labels(vocab, buckets)

        # FIXME: This is hardcoded because vocabularies has not been
        # fully migrated. Ideally all would be treated equally in the for
        # loop above.
        # languages = aggs.get("languages")

        # if languages:
        #     languages["buckets"] = serialize_vocabulary(
        #         "languages", languages["buckets"])

        return aggs
Example #2
0
def test_dump_contributors_role(config, vocabulary_clear):
    prev_config = config.get('RDM_RECORDS_CUSTOM_VOCABULARIES')
    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = {
        'contributors.role': {
            'path':
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data',
                         'contributor_role.csv')
        },
    }

    dumped_vocabularies = Vocabularies.dump()

    assert dumped_vocabularies['contributors']['role'] == [{
        'value':
        'Librarian',
        'text':
        _('Librarian')
    }, {
        'value':
        'DataCollector',
        'text':
        _('Data Collector')
    }]

    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = prev_config
    def deposits_edit(pid_value):
        """Deposit edit page."""
        links_config = BibliographicDraftResourceConfig.links_config
        draft = service.read_draft(id_=pid_value,
                                   identity=g.identity,
                                   links_config=links_config)

        files_service = BibliographicDraftFilesService()
        files_list = files_service.list_files(
            id_=pid_value,
            identity=g.identity,
            links_config=BibliographicDraftFilesResourceConfig.links_config)

        forms_config = dict(apiUrl=f"/api/records/{pid_value}/draft",
                            vocabularies=Vocabularies.dump(),
                            current_locale=str(current_i18n.locale))

        # Dereference relations (languages, licenses, etc.)
        draft._record.relations.dereference()
        # TODO: get the `is_published` field when reading the draft
        _record = draft.to_dict()
        from invenio_pidstore.errors import PIDUnregistered
        try:
            _ = service.draft_cls.pid.resolve(pid_value, registered_only=True)
            _record["is_published"] = True
        except PIDUnregistered:
            _record["is_published"] = False

        searchbar_config = dict(searchUrl=search_url)
        return render_template(
            current_app.config['DEPOSITS_FORMS_BASE_TEMPLATE'],
            forms_config=forms_config,
            record=_record,
            files=files_list.to_dict(),
            searchbar_config=searchbar_config)
Example #4
0
    def get_aggs(self, obj_list):
        """Apply aggregations transformation."""
        aggs = obj_list.get("aggregations")
        if not aggs:
            return missing

        for name, agg in aggs.items():
            # Aggregation key/name must match vocabulary id.
            vocab = Vocabularies.get_vocabulary(name)
            if not vocab:
                continue

            buckets = agg.get('buckets')
            if buckets:
                apply_labels(vocab, buckets)

        # TODO: temporary hack until vocabularies can be fixed
        is_published_agg = aggs.get('is_published')
        if is_published_agg:
            for b in is_published_agg.get('buckets', []):
                if b.get('key') == 1:
                    b['label'] = _("Published")
                elif b.get('key') == 0:
                    b['label'] = _("New")

        # FIXME: This is hardcoded because vocabularies has not been
        # fully migrated. Ideally all would be treated equally in the for
        # loop above.
        # languages = aggs.get("languages")

        # if languages:
        #     languages["buckets"] = serialize_vocabulary(
        #         "languages", languages["buckets"])

        return aggs
Example #5
0
def get_form_config(**kwargs):
    """Get the react form configration."""
    return dict(
        vocabularies=Vocabularies.dump(),
        current_locale=str(current_i18n.locale),
        **kwargs
    )
Example #6
0
 def get_type(self, obj):
     """Get resource type."""
     resource_type = obj["metadata"]["resource_type"]
     vocabulary = Vocabularies.get_vocabulary('resource_type')
     entry = vocabulary.get_entry_by_dict(resource_type)
     return {
         'resourceTypeGeneral': entry.get("datacite_general", "Other"),
         'resourceType': entry.get("datacite_type", "Other"),
     }
Example #7
0
def deposits_create():
    """Record creation page."""
    forms_config = dict(apiUrl='/api/records/',
                        vocabularies=Vocabularies.dump())
    searchbar_config = dict(searchUrl='/search')
    empty_record = dump_empty(MetadataSchemaV1)
    return render_template(current_app.config['DEPOSITS_FORMS_BASE_TEMPLATE'],
                           forms_config=forms_config,
                           record=empty_record,
                           searchbar_config=searchbar_config)
Example #8
0
    def vocabulary_title(dict_key, vocabulary_key, alt_key=None):
        """Returns formatted vocabulary-corresponding human-readable string.

        In some cases the dict needs to be reconstructed. `alt_key` will be the
        key while `dict_key` will become the value.
        """
        if alt_key:
            dict_key = {alt_key: dict_key}
        vocabulary = Vocabularies.get_vocabulary(vocabulary_key)
        return vocabulary.get_title_by_dict(dict_key) if vocabulary else ""
Example #9
0
 def deposits_create():
     """Record creation page."""
     forms_config = dict(
         createUrl=("/api/records"),
         vocabularies=Vocabularies.dump(),
     )
     return render_template(
         current_app.config['DEPOSITS_FORMS_BASE_TEMPLATE'],
         forms_config=forms_config,
         record=dump_empty(RDMRecordSchema),
         searchbar_config=dict(searchUrl=search_url))
Example #10
0
def get_form_config(**kwargs):
    """Get the react form configuration."""
    vocabularies = Vocabularies.dump()
    vocabularies["resource_type"] = _dump_resource_type_vocabulary()
    vocabularies["titles"] = dict(
        type=_dump_title_types_vocabulary()
    )
    return dict(
        vocabularies=vocabularies,
        current_locale=str(current_i18n.locale),
        pids=get_form_pids_config(),
        **kwargs
    )
Example #11
0
 def deposits_create():
     """Record creation page."""
     forms_config = dict(createUrl=("/api/records"),
                         vocabularies=Vocabularies.dump(),
                         current_locale=str(current_i18n.locale))
     return render_template(
         current_app.config['DEPOSITS_FORMS_BASE_TEMPLATE'],
         forms_config=forms_config,
         record=dump_empty(RDMRecordSchema),
         files=dict(default_preview=None,
                    enabled=True,
                    entries=[],
                    links={}),
         searchbar_config=dict(searchUrl=search_url))
Example #12
0
def test_dump_resource_type(config, vocabulary_clear):
    prev_config = config.get('RDM_RECORDS_CUSTOM_VOCABULARIES')
    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = {
        'resource_type': {
            'path': os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                'data',
                'resource_types.csv'
            )
        },
    }

    dumped_vocabularies = Vocabularies.dump()

    assert dumped_vocabularies['resource_type'] == {
        'type': [
            {
                'icon': 'file alternate',
                'text': _('Publication'),
                'value': 'publication',
            },
            {
                'icon': 'chart bar outline',
                'text': _('Image'),
                'value': 'my_image',
            },
            {
                'icon': 'code',
                'text': _('Software'),
                'value': 'software',
            }
        ],
        'subtype': [
            {
                'parent-text': _('Publication'),
                'parent-value': 'publication',
                'text': _('Book'),
                'value': 'publication-book',
            },
            {
                'parent-text': _('Image'),
                'parent-value': 'my_image',
                'text': _('Photo'),
                'value': 'my_photo',
            }
        ]
    }

    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = prev_config
Example #13
0
    def deposits_edit(pid_value):
        """Deposit edit page."""
        links_config = BibliographicDraftResourceConfig.links_config
        draft = service.read_draft(id_=pid_value,
                                   identity=g.identity,
                                   links_config=links_config)

        forms_config = dict(apiUrl=f"/api/records/{pid_value}/draft",
                            vocabularies=Vocabularies.dump())

        searchbar_config = dict(searchUrl=search_url)
        return render_template(
            current_app.config['DEPOSITS_FORMS_BASE_TEMPLATE'],
            forms_config=forms_config,
            record=draft.to_dict(),
            searchbar_config=searchbar_config)
Example #14
0
    def get_aggs(self, obj_list):
        """Apply aggregations transformation."""
        aggs = obj_list.get("aggregations")
        if not aggs:
            return missing

        for name, agg in aggs.items():
            # Aggregation key/name must match vocabulary id.
            vocab = Vocabularies.get_vocabulary(name)
            if not vocab:
                continue

            buckets = agg.get('buckets')
            if buckets:
                apply_labels(vocab, buckets)

        return aggs
Example #15
0
def get_form_config(**kwargs):
    """Get the react form configuration."""
    vocabularies = Vocabularies.dump()
    vocabularies["resource_type"] = _dump_resource_type_vocabulary()
    vocabularies["titles"] = dict(type=_dump_title_types_vocabulary())
    vocabularies["creators"] = dict(role=_dump_creators_role_vocabulary())
    vocabularies["contributors"] = dict(
        role=_dump_contributors_role_vocabulary())
    vocabularies["descriptions"] = dict(
        type=_dump_description_types_vocabulary())
    vocabularies["dates"] = dict(type=_dump_date_types_vocabulary())
    vocabularies["relation_type"] = _dump_relation_types_vocabulary()

    return dict(vocabularies=vocabularies,
                current_locale=str(current_i18n.locale),
                pids=get_form_pids_config(),
                **kwargs)
Example #16
0
def test_dump_titles_type(config, vocabulary_clear):
    prev_config = config.get('RDM_RECORDS_CUSTOM_VOCABULARIES')
    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = {
        'titles.type': {
            'path':
            os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data',
                         'title_type.csv')
        }
    }

    dumped_vocabularies = Vocabularies.dump()

    assert dumped_vocabularies['titles']['type'] == [{
        'value':
        'AlternateTitle',
        'text':
        _('Alternate Title')
    }]

    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = prev_config
Example #17
0
    def _serialize_ui_options_from_vocabulary(self,
                                              vocabulary_name,
                                              top_bucket_key=None):
        """Creates UI facet label options from RDM vocabularies.

        :params top_bucket_key: Key used for nested buckets to indicate
                                the top level aggregation.
        """
        ui_options = {}
        vocabulary = Vocabularies.get_vocabulary(
            vocabulary_name).dump_options()
        if type(vocabulary) is dict:
            ui_options[top_bucket_key] = {}
            for key in vocabulary.keys():
                for option in vocabulary[key]:
                    ui_options[top_bucket_key][option['value']] = \
                        str(option['text'])
        else:
            for option in vocabulary:
                ui_options[option['value']] = str(option['text'])
        return ui_options
Example #18
0
def test_dump_access_right(config, vocabulary_clear):
    prev_config = config.get('RDM_RECORDS_CUSTOM_VOCABULARIES')
    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = {
        'access_right': {
            'path': os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                'data',
                'access_right.csv'
            )
        }
    }

    dumped_vocabularies = Vocabularies.dump()

    assert dumped_vocabularies['access_right'] == [
        {
            'icon': 'lock open',
            'value': 'open',
            'text': _('Open Access')
        },
    ]

    config['RDM_RECORDS_CUSTOM_VOCABULARIES'] = prev_config
Example #19
0
def deposits_edit(id):
    """Fake deposits edit page."""
    forms_config = dict(apiUrl='/api/records/',
                        vocabularies=Vocabularies.dump())
    # minimal record
    record = {
        "_access": {
            "metadata_restricted": False,
            "files_restricted": False
        },
        "_owners": [1],
        "_created_by": 1,
        "access_right": "open",
        "id": "{}".format(id),
        "resource_type": {
            "type": "image",
            "subtype": "image-photo"
        },
        # Technically not required
        "creators": [],
        "titles": [{
            "title": "A Romans story",
            "type": "Other",
            "lang": "eng"
        }],
        "links": {
            "edit": "/deposits/{}/edit".format(id)
        }
    }
    searchbar_config = dict(searchUrl='/search')

    initial_record = dump_empty(MetadataSchemaV1)
    initial_record.update(record)
    return render_template(current_app.config['DEPOSITS_FORMS_BASE_TEMPLATE'],
                           forms_config=forms_config,
                           record=initial_record,
                           searchbar_config=searchbar_config)
Example #20
0
def vocabulary_clear(app):
    """Clears the Vocabulary singleton and pushes an application context.

    NOTE: app fixture pushes an application context
    """
    Vocabularies.clear()
Example #21
0
def vocabulary_clear(appctx):
    """Clears the Vocabulary singleton and pushes an appctx."""
    Vocabularies.clear()
Example #22
0
 def vocabulary(self):
     """Get the vocabulary."""
     return Vocabularies.get_vocabulary(self.vocabulary_name)