• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rero / sonar / 17425918180

03 Sep 2025 07:11AM UTC coverage: 95.796% (-0.6%) from 96.378%
17425918180

push

github

PascalRepond
translations: extract messages

Co-Authored-by: Pascal Repond <pascal.repond@rero.ch>

7816 of 8159 relevant lines covered (95.8%)

0.96 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.44
/sonar/modules/organisations/api.py
1
# Swiss Open Access Repository
2
# Copyright (C) 2021 RERO
3
#
4
# This program is free software: you can redistribute it and/or modify
5
# it under the terms of the GNU Affero General Public License as published by
6
# the Free Software Foundation, version 3 of the License.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU Affero General Public License for more details.
12
#
13
# You should have received a copy of the GNU Affero General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

16
"""Organisation Api."""
17

18
from functools import partial
1✔
19

20
from flask import has_request_context
1✔
21
from flask.globals import request_ctx
1✔
22
from invenio_db import db
1✔
23
from invenio_oaiserver.models import OAISet
1✔
24
from werkzeug.local import LocalProxy
1✔
25

26
from sonar.modules.users.api import current_user_record
1✔
27

28
from ..api import SonarIndexer, SonarRecord, SonarSearch
1✔
29
from ..fetchers import id_fetcher
1✔
30
from ..providers import Provider
1✔
31
from .minters import id_minter
1✔
32

33

34
def get_current_organisation():
1✔
35
    """Return current organisation from context."""
36
    if has_request_context() and not hasattr(request_ctx, "organisation_record"):
1✔
37
        request_ctx.organisation_record = (
1✔
38
            None
39
            if (not current_user_record or not current_user_record.get("organisation"))
40
            else OrganisationRecord.get_record_by_ref_link(current_user_record["organisation"]["$ref"])
41
        )
42

43
    return getattr(request_ctx, "organisation_record", None)
1✔
44

45

46
current_organisation = LocalProxy(get_current_organisation)
1✔
47

48
# provider
49
OrganisationProvider = type("OrganisationProvider", (Provider,), {"pid_type": "org"})
1✔
50
# minter
51
organisation_pid_minter = partial(id_minter, provider=OrganisationProvider)
1✔
52
# fetcher
53
organisation_pid_fetcher = partial(id_fetcher, provider=OrganisationProvider)
1✔
54

55

56
class OrganisationSearch(SonarSearch):
1✔
57
    """Search organisations."""
58

59
    class Meta:
1✔
60
        """Search only on item index."""
61

62
        index = "organisations"
1✔
63
        doc_types = []
1✔
64

65
    def get_shared_or_dedicated_list(self):
1✔
66
        """Get the list of dedicated or shared organisations.
67

68
        :returns: Iterator of dedicated or shared organisations.
69
        """
70
        return (
1✔
71
            self.filter(
72
                "bool",
73
                should=[{"term": {"isDedicated": True}}, {"term": {"isShared": True}}],
74
            )
75
            .source(["pid", "name", "isShared", "isDedicated"])
76
            .execute()
77
            .hits
78
        )
79

80
    def get_organisation_pid_by_server_name(self, server_name):
1✔
81
        """Get organisation by server_name.
82

83
        :param server_name: server name for the dedicated organisation.
84
        :returns: pid of the dedicated organisation.
85
        """
86
        if hits := self.filter("term", serverName=server_name).source(["pid"]).execute().hits:
1✔
87
            return hits[0].pid
1✔
88
        return None
1✔
89

90
    def get_dedicated_list(self):
1✔
91
        """Get the list of dedicated organisations.
92

93
        :returns: Iterator of dedicated organisations.
94
        """
95
        return self.filter("term", isDedicated=True).execute().hits
×
96

97
    def get_organisation_from_naan(self, naan):
1✔
98
        """Get organisation from a given naan.
99

100
        :param naan: Name Assigning Authority Number for the dedicated
101
                     organisation.
102
        :returns: pid of the dedicated organisation.
103
        """
104
        try:
1✔
105
            return next(self.filter("term", arkNAAN=naan).scan())
1✔
106
        except StopIteration:
1✔
107
            return None
1✔
108

109

110
class OrganisationRecord(SonarRecord):
1✔
111
    """Organisation record class."""
112

113
    minter = organisation_pid_minter
1✔
114
    fetcher = organisation_pid_fetcher
1✔
115
    provider = OrganisationProvider
1✔
116
    schema = "organisations/organisation-v1.0.0.json"
1✔
117

118
    @classmethod
1✔
119
    def create(cls, data, id_=None, dbcommit=False, with_bucket=True, **kwargs):
1✔
120
        """Create organisation record."""
121
        # Create OAI set
122
        code = data["code"]
1✔
123
        oaiset = OAISet(
1✔
124
            spec=code,
125
            name=data["name"],
126
            search_pattern=f'organisation.code:"{code}"',
127
            system_created=True,
128
        )
129
        db.session.add(oaiset)
1✔
130

131
        return super().create(data, id_=id_, dbcommit=dbcommit, with_bucket=with_bucket, **kwargs)
1✔
132

133
    @classmethod
1✔
134
    def get_or_create(cls, code, name=None):
1✔
135
        """Get or create an organisation.
136

137
        :param code: Organisation's code, equivalent to PID.
138
        :param name: Organisation's name.
139
        :returns: Organisations object.
140
        """
141
        organisation = cls.get_record_by_pid(code)
1✔
142

143
        if organisation:
1✔
144
            return organisation
1✔
145

146
        organisation = cls.create({"code": code, "name": name if name else code}, dbcommit=True)
1✔
147
        organisation.reindex()
1✔
148
        return organisation
1✔
149

150
    def update(self, data):
1✔
151
        """Update data for record."""
152
        # Update OAI set name according to organisation's name
153
        oaiset = OAISet.query.filter(OAISet.spec == data["code"]).first()
1✔
154

155
        if oaiset:
1✔
156
            oaiset.name = data["name"]
1✔
157
            db.session.commit()
1✔
158

159
        super().update(data)
1✔
160
        return self
1✔
161

162

163
class OrganisationIndexer(SonarIndexer):
1✔
164
    """Indexing documents in Elasticsearch."""
165

166
    record_cls = OrganisationRecord
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc