Example #1
0
class CorAcquisitionFrameworkActor(DB.Model):
    __tablename__ = "cor_acquisition_framework_actor"
    __table_args__ = {"schema": "gn_meta"}
    id_cafa = DB.Column(DB.Integer, primary_key=True)
    id_acquisition_framework = DB.Column(
        DB.Integer,
        ForeignKey(
            "gn_meta.t_acquisition_frameworks.id_acquisition_framework"),
    )
    id_role = DB.Column(DB.Integer, ForeignKey("utilisateurs.t_roles.id_role"))
    id_organism = DB.Column(
        DB.Integer, ForeignKey("utilisateurs.bib_organismes.id_organisme"))
    id_nomenclature_actor_role = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("ROLE_ACTEUR"),
    )

    nomenclature_actor_role = DB.relationship(
        TNomenclatures,
        primaryjoin=(
            TNomenclatures.id_nomenclature == id_nomenclature_actor_role),
    )

    role = DB.relationship(User,
                           primaryjoin=(User.id_role == id_role),
                           foreign_keys=[id_role])

    organism = relationship("BibOrganismes", foreign_keys=[id_organism])

    @staticmethod
    def get_actor(
        id_acquisition_framework,
        id_nomenclature_actor_role,
        id_role=None,
        id_organism=None,
    ):
        """
            Get CorAcquisitionFrameworkActor from id_dataset, id_actor, and id_role or id_organism.
            if no object return None
        """
        try:
            if id_role is None:
                return (
                    DB.session.query(CorAcquisitionFrameworkActor).filter_by(
                        id_acquisition_framework=id_acquisition_framework,
                        id_organism=id_organism,
                        id_nomenclature_actor_role=id_nomenclature_actor_role,
                    ).one())
            elif id_organism is None:
                return (
                    DB.session.query(CorAcquisitionFrameworkActor).filter_by(
                        id_acquisition_framework=id_acquisition_framework,
                        id_role=id_role,
                        id_nomenclature_actor_role=id_nomenclature_actor_role,
                    ).one())
        except exc.NoResultFound:
            return None
Example #2
0
class TDatasets(DB.Model):
    __tablename__ = 't_datasets'
    __table_args__ = {'schema': 'gn_meta'}
    id_dataset = DB.Column(DB.Integer, primary_key=True)
    unique_dataset_id = DB.Column(UUID(as_uuid=True),
                                  default=select([func.uuid_generate_v4()]))
    id_acquisition_framework = DB.Column(
        DB.Integer,
        ForeignKey(
            'gn_meta.t_acquisition_frameworks.id_acquisition_framework'))
    dataset_name = DB.Column(DB.Unicode)
    dataset_shortname = DB.Column(DB.Unicode)
    dataset_desc = DB.Column(DB.Unicode)
    id_nomenclature_data_type = DB.Column(
        DB.Integer,
        default=TNomenclatures.get_default_nomenclature("DATA_TYP"))
    keywords = DB.Column(DB.Unicode)
    marine_domain = DB.Column(DB.Boolean)
    terrestrial_domain = DB.Column(DB.Boolean)
    id_nomenclature_dataset_objectif = DB.Column(
        DB.Integer,
        default=TNomenclatures.get_default_nomenclature("JDD_OBJECTIFS"))
    bbox_west = DB.Column(DB.Float)
    bbox_east = DB.Column(DB.Float)
    bbox_south = DB.Column(DB.Float)
    bbox_north = DB.Column(DB.Float)
    id_nomenclature_collecting_method = DB.Column(
        DB.Integer,
        default=TNomenclatures.get_default_nomenclature("METHO_RECUEIL"))
    id_nomenclature_data_origin = DB.Column(
        DB.Integer,
        default=TNomenclatures.get_default_nomenclature("DS_PUBLIQUE"))
    id_nomenclature_source_status = DB.Column(
        DB.Integer,
        default=TNomenclatures.get_default_nomenclature("STATUT_SOURCE"))
    id_nomenclature_resource_type = DB.Column(
        DB.Integer,
        default=TNomenclatures.get_default_nomenclature("RESOURCE_TYP"))
    default_validity = DB.Column(DB.Boolean)
    meta_create_date = DB.Column(DB.DateTime)
    meta_update_date = DB.Column(DB.DateTime)
    active = DB.Column(DB.Boolean, default=True)

    cor_dataset_actor = relationship(
        CorDatasetActor,
        lazy='select',
        cascade="save-update, delete, delete-orphan")

    @staticmethod
    def get_id(uuid_dataset):
        id_dataset = DB.session.query(TDatasets.id_dataset).filter(
            TDatasets.unique_dataset_id == uuid_dataset).first()
        if id_dataset:
            return id_dataset[0]
        return id_dataset

    @staticmethod
    def get_uuid(id_dataset):
        uuid_dataset = DB.session.query(TDatasets.unique_dataset_id).filter(
            TDatasets.id_dataset == id_dataset).first()
        if uuid_dataset:
            return uuid_dataset[0]
        return uuid_dataset

    @staticmethod
    def get_user_datasets(user):
        """get the dataset(s) where the user is actor (himself or with its organism)
            param: user from TRole model
            return: a list of id_dataset """
        q = DB.session.query(CorDatasetActor, CorDatasetActor.id_dataset)
        if user.id_organisme is None:
            q = q.filter(CorDatasetActor.id_role == user.id_role)
        else:
            q = q.filter(
                or_(CorDatasetActor.id_organism == user.id_organisme,
                    CorDatasetActor.id_role == user.id_role))
        return list(set([d.id_dataset for d in q.all()]))
Example #3
0
class TAcquisitionFramework(CruvedHelper):
    __tablename__ = "t_acquisition_frameworks"
    __table_args__ = {"schema": "gn_meta"}
    id_acquisition_framework = DB.Column(DB.Integer, primary_key=True)
    unique_acquisition_framework_id = DB.Column(UUID(as_uuid=True),
                                                default=select(
                                                    [func.uuid_generate_v4()]))
    acquisition_framework_name = DB.Column(DB.Unicode)
    acquisition_framework_desc = DB.Column(DB.Unicode)
    id_nomenclature_territorial_level = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature(
            "NIVEAU_TERRITORIAL"),
    )
    territory_desc = DB.Column(DB.Unicode)
    keywords = DB.Column(DB.Unicode)
    id_nomenclature_financing_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature(
            "TYPE_FINANCEMENT"),
    )
    target_description = DB.Column(DB.Unicode)
    ecologic_or_geologic_target = DB.Column(DB.Unicode)
    acquisition_framework_parent_id = DB.Column(DB.Integer)
    is_parent = DB.Column(DB.Boolean)
    opened = DB.Column(DB.Boolean, default=True)
    id_digitizer = DB.Column(DB.Integer,
                             ForeignKey("utilisateurs.t_roles.id_role"))

    acquisition_framework_start_date = DB.Column(DB.DateTime)
    acquisition_framework_end_date = DB.Column(DB.DateTime)

    meta_create_date = DB.Column(DB.DateTime)
    meta_update_date = DB.Column(DB.DateTime)
    initial_closing_date = DB.Column(DB.DateTime)

    creator = DB.relationship("User", lazy="select")
    cor_af_actor = relationship(
        CorAcquisitionFrameworkActor,
        lazy="select",
        cascade="save-update, merge, delete, delete-orphan",
    )

    cor_objectifs = DB.relationship(
        TNomenclatures,
        secondary=CorAcquisitionFrameworkObjectif.__table__,
        primaryjoin=(CorAcquisitionFrameworkObjectif.id_acquisition_framework
                     == id_acquisition_framework),
        secondaryjoin=(CorAcquisitionFrameworkObjectif.id_nomenclature_objectif
                       == TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorAcquisitionFrameworkObjectif.id_acquisition_framework,
            CorAcquisitionFrameworkObjectif.id_nomenclature_objectif,
        ],
        lazy="select",
    )

    cor_volets_sinp = DB.relationship(
        TNomenclatures,
        secondary=CorAcquisitionFrameworkVoletSINP.__table__,
        primaryjoin=(CorAcquisitionFrameworkVoletSINP.id_acquisition_framework
                     == id_acquisition_framework),
        secondaryjoin=(
            CorAcquisitionFrameworkVoletSINP.id_nomenclature_voletsinp ==
            TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorAcquisitionFrameworkVoletSINP.id_acquisition_framework,
            CorAcquisitionFrameworkVoletSINP.id_nomenclature_voletsinp,
        ],
        lazy="select",
    )

    @staticmethod
    def get_id(uuid_af):
        """
            return the acquisition framework's id
            from its UUID if exist or None
        """
        a_f = (DB.session.query(
            TAcquisitionFramework.id_acquisition_framework).filter(
                TAcquisitionFramework.unique_acquisition_framework_id ==
                uuid_af).first())
        if a_f:
            return a_f[0]
        return a_f

    @staticmethod
    def get_user_af(user, only_query=False, only_user=False):
        """get the af(s) where the user is actor (himself or with its organism - only himelsemf id only_use=True) or digitizer
            param: 
              - user from TRole model
              - only_query: boolean (return the query not the id_datasets allowed if true)
              - only_user: boolean: return only the dataset where user himself is actor (not with its organoism)

            return: a list of id_dataset or a query"""
        q = DB.session.query(
            TAcquisitionFramework.id_acquisition_framework).outerjoin(
                CorAcquisitionFrameworkActor,
                CorAcquisitionFrameworkActor.id_acquisition_framework ==
                TAcquisitionFramework.id_acquisition_framework,
            )
        if user.id_organisme is None or only_user:
            q = q.filter(
                or_(
                    CorAcquisitionFrameworkActor.id_role == user.id_role,
                    TAcquisitionFramework.id_digitizer == user.id_role,
                ))
        else:
            q = q.filter(
                or_(
                    CorAcquisitionFrameworkActor.id_organism ==
                    user.id_organisme,
                    CorAcquisitionFrameworkActor.id_role == user.id_role,
                    TAcquisitionFramework.id_digitizer == user.id_role,
                ))
        if only_query:
            return q
        data = q.all()
        return list(set([d.id_acquisition_framework for d in data]))
def add_nomenclature(module_code):
    path_nomenclature = CONFIG_PATH + '/' + module_code + '/nomenclature.json'

    if not os.path.exists(path_nomenclature):
        print("Il n'y a pas de nomenclature à insérer pour ce module")
        return

    nomenclature = json_from_file(path_nomenclature, None)
    if not nomenclature:
        print(
            'Il y a un problème avec le fichier {}'.format(path_nomenclature))
        return

    for data in nomenclature.get('types', []):
        nomenclature_type = None
        try:
            nomenclature_type = (
                DB.session.query(BibNomenclaturesTypes).filter(
                    data.get('mnemonique') ==
                    BibNomenclaturesTypes.mnemonique).one())

        except Exception:
            pass

        if nomenclature_type:
            print('no insert type', nomenclature_type)
            continue

        data['label_fr'] = data.get('label_fr') or data['label_default']
        data['definition_fr'] = data.get(
            'definition_fr') or data['definition_default']
        data['source'] = data.get('source') or 'monitoring'
        data['statut'] = data.get('statut') or 'Validation en cours'

        nomenclature_type = BibNomenclaturesTypes(**data)
        DB.session.add(nomenclature_type)
        DB.session.commit()

    for data in nomenclature['nomenclatures']:
        nomenclature = None
        try:
            nomenclature = (DB.session.query(TNomenclatures).join(
                BibNomenclaturesTypes, BibNomenclaturesTypes.id_type ==
                TNomenclatures.id_type).filter(
                    and_(
                        data.get('cd_nomenclature') ==
                        TNomenclatures.cd_nomenclature,
                        data.get('type') ==
                        BibNomenclaturesTypes.mnemonique)).one())

        except Exception as e:
            pass

        if nomenclature:
            # TODO make update
            print('nomenclature {} - {} already exist'.format(
                nomenclature.cd_nomenclature, nomenclature.label_default))
            continue

        id_type = None

        try:
            id_type = (DB.session.query(BibNomenclaturesTypes.id_type).filter(
                BibNomenclaturesTypes.mnemonique == data['type']).one())[0]
        except Exception:
            pass

        if not id_type:
            print(
                'probleme de type avec mnemonique="{}" pour la nomenclature {}'
                .format(data['type'], data))
            continue

        data['label_fr'] = data.get('label_fr') or data['label_default']
        data['definition_fr'] = data.get(
            'definition_fr') or data['definition_default']
        data['source'] = data.get('source') or 'monitoring'
        data['statut'] = data.get('statut') or 'Validation en cours'
        data['active'] = True
        data['id_type'] = id_type
        data.pop('type')

        nomenclature = TNomenclatures(**data)
        DB.session.add(nomenclature)
        DB.session.commit()
Example #5
0
class TDatasets(CruvedHelper):
    __tablename__ = "t_datasets"
    __table_args__ = {"schema": "gn_meta"}
    id_dataset = DB.Column(DB.Integer, primary_key=True)
    unique_dataset_id = DB.Column(UUID(as_uuid=True),
                                  default=select([func.uuid_generate_v4()]))
    id_acquisition_framework = DB.Column(
        DB.Integer,
        ForeignKey(
            "gn_meta.t_acquisition_frameworks.id_acquisition_framework"),
    )
    dataset_name = DB.Column(DB.Unicode)
    dataset_shortname = DB.Column(DB.Unicode)
    dataset_desc = DB.Column(DB.Unicode)
    id_nomenclature_data_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("DATA_TYP"),
    )
    keywords = DB.Column(DB.Unicode)
    marine_domain = DB.Column(DB.Boolean)
    terrestrial_domain = DB.Column(DB.Boolean)
    id_nomenclature_dataset_objectif = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("JDD_OBJECTIFS"
                                                                ),
    )
    bbox_west = DB.Column(DB.Float)
    bbox_east = DB.Column(DB.Float)
    bbox_south = DB.Column(DB.Float)
    bbox_north = DB.Column(DB.Float)
    id_nomenclature_collecting_method = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("METHO_RECUEIL"
                                                                ),
    )
    id_nomenclature_data_origin = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("DS_PUBLIQUE"),
    )
    id_nomenclature_source_status = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("STATUT_SOURCE"
                                                                ),
    )
    id_nomenclature_resource_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("RESOURCE_TYP"
                                                                ),
    )
    meta_create_date = DB.Column(DB.DateTime)
    meta_update_date = DB.Column(DB.DateTime)
    active = DB.Column(DB.Boolean, default=True)
    validable = DB.Column(DB.Boolean)
    id_digitizer = DB.Column(DB.Integer,
                             ForeignKey("utilisateurs.t_roles.id_role"))

    creator = DB.relationship("User", lazy="select")
    modules = DB.relationship("TModules",
                              secondary=cor_module_dataset,
                              lazy="select")

    # HACK: the relationship is not well defined for many to many relationship
    # because CorDatasetActor could be an User or an Organisme object...
    cor_dataset_actor = relationship(
        CorDatasetActor,
        lazy="select",
        cascade="save-update, merge, delete, delete-orphan",
    )

    @staticmethod
    def get_id(uuid_dataset):
        id_dataset = (DB.session.query(TDatasets.id_dataset).filter(
            TDatasets.unique_dataset_id == uuid_dataset).first())
        if id_dataset:
            return id_dataset[0]
        return id_dataset

    @staticmethod
    def get_uuid(id_dataset):
        uuid_dataset = (DB.session.query(TDatasets.unique_dataset_id).filter(
            TDatasets.id_dataset == id_dataset).first())
        if uuid_dataset:
            return uuid_dataset[0]
        return uuid_dataset

    @staticmethod
    def get_user_datasets(user, only_query=False, only_user=False):
        """get the dataset(s) where the user is actor (himself or with its organism - only himelsemf id only_use=True) or digitizer
            param: 
              - user from TRole model
              - only_query: boolean (return the query not the id_datasets allowed if true)
              - only_user: boolean: return only the dataset where user himself is actor (not with its organism)

            return: a list of id_dataset or a query"""
        q = DB.session.query(TDatasets).outerjoin(
            CorDatasetActor,
            CorDatasetActor.id_dataset == TDatasets.id_dataset)
        if user.id_organisme is None or only_user:
            q = q.filter(
                or_(
                    CorDatasetActor.id_role == user.id_role,
                    TDatasets.id_digitizer == user.id_role,
                ))
        else:
            q = q.filter(
                or_(
                    CorDatasetActor.id_organism == user.id_organisme,
                    CorDatasetActor.id_role == user.id_role,
                    TDatasets.id_digitizer == user.id_role,
                ))
        if only_query:
            return q
        return list(set([d.id_dataset for d in q.all()]))
Example #6
0
class TAcquisitionFramework(CruvedHelper):
    __tablename__ = "t_acquisition_frameworks"
    __table_args__ = {"schema": "gn_meta"}
    id_acquisition_framework = DB.Column(DB.Integer, primary_key=True)
    unique_acquisition_framework_id = DB.Column(
        UUID(as_uuid=True), default=select([func.uuid_generate_v4()])
    )
    acquisition_framework_name = DB.Column(DB.Unicode)
    acquisition_framework_desc = DB.Column(DB.Unicode)
    id_nomenclature_territorial_level = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("NIVEAU_TERRITORIAL"),
    )
    territory_desc = DB.Column(DB.Unicode)
    keywords = DB.Column(DB.Unicode)
    id_nomenclature_financing_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("TYPE_FINANCEMENT"),
    )
    target_description = DB.Column(DB.Unicode)
    ecologic_or_geologic_target = DB.Column(DB.Unicode)
    acquisition_framework_parent_id = DB.Column(DB.Integer)
    is_parent = DB.Column(DB.Boolean)
    opened = DB.Column(DB.Boolean, default=True)
    id_digitizer = DB.Column(DB.Integer, ForeignKey("utilisateurs.t_roles.id_role"))

    acquisition_framework_start_date = DB.Column(DB.Date)
    acquisition_framework_end_date = DB.Column(DB.Date)

    meta_create_date = DB.Column(DB.DateTime)
    meta_update_date = DB.Column(DB.DateTime)
    initial_closing_date = DB.Column(DB.DateTime)

    creator = DB.relationship("User", lazy="joined")
    nomenclature_territorial_level = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_territorial_level),
    )
    nomenclature_financing_type = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_financing_type),
    )
    cor_af_actor = relationship(
        CorAcquisitionFrameworkActor,
        lazy="joined",
        #cascade="save-update, merge, delete, delete-orphan",
        cascade="all,delete-orphan",
        uselist=True,
        backref=DB.backref("actor_af", lazy="select")
    )

    cor_objectifs = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorAcquisitionFrameworkObjectif.__table__,
        primaryjoin=(
            CorAcquisitionFrameworkObjectif.id_acquisition_framework == id_acquisition_framework
        ),
        secondaryjoin=(
            CorAcquisitionFrameworkObjectif.id_nomenclature_objectif
            == TNomenclatures.id_nomenclature
        ),
        foreign_keys=[
            CorAcquisitionFrameworkObjectif.id_acquisition_framework,
            CorAcquisitionFrameworkObjectif.id_nomenclature_objectif,
        ],
        backref=DB.backref("objectif_af", lazy="select")
    )

    cor_volets_sinp = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorAcquisitionFrameworkVoletSINP.__table__,
        primaryjoin=(CorAcquisitionFrameworkVoletSINP.id_acquisition_framework == id_acquisition_framework),
        secondaryjoin=(CorAcquisitionFrameworkVoletSINP.id_nomenclature_voletsinp == TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorAcquisitionFrameworkVoletSINP.id_acquisition_framework,
            CorAcquisitionFrameworkVoletSINP.id_nomenclature_voletsinp,
        ],
        backref=DB.backref("volet_sinp_af", lazy="select")
    )

    cor_territories = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorAcquisitionFrameworkTerritory.__table__,
        primaryjoin=(CorAcquisitionFrameworkTerritory.id_acquisition_framework == id_acquisition_framework),
        secondaryjoin=(CorAcquisitionFrameworkTerritory.id_nomenclature_territory == TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorAcquisitionFrameworkTerritory.id_acquisition_framework,
            CorAcquisitionFrameworkTerritory.id_nomenclature_territory,
        ],
        backref=DB.backref("territory_af", lazy="select")
    )

    bibliographical_references = DB.relationship(
        "TBibliographicReference",
        lazy="select",
        cascade="all,delete-orphan",
        uselist=True,
        backref=DB.backref("acquisition_framework", lazy="select"),
    )

    t_datasets = DB.relationship(
        "TDatasets",
        lazy="select",
        cascade="all,delete-orphan",
        uselist=True,
        backref=DB.backref("acquisition_framework", lazy="select"),
    )

    def get_object_cruved(
        self, info_role, user_cruved
    ):
        """
        Return the user's cruved for a Model instance.
        Use in the map-list interface to allow or not an action
        params:
            - user_cruved: object retourner by cruved_for_user_in_app(user) {'C': '2', 'R':'3' etc...}
            - id_object (int): id de l'objet sur lqurqul on veut vérifier le CRUVED (self.id_dataset/ self.id_ca)
            - id_role: identifiant de la personne qui demande la route
            - id_object_users_actor (list): identifiant des objects ou l'utilisateur est lui même acteur
            - id_object_organism_actor (list): identifiants des objects ou l'utilisateur ou son organisme sont acteurs

        Return: dict {'C': True, 'R': False ...}
        """
        return {
            action: self.user_is_allowed_to(self.cor_af_actor, info_role, level)
            for action, level in user_cruved.items()
        }

    @staticmethod
    def get_id(uuid_af):
        """
            return the acquisition framework's id
            from its UUID if exist or None
        """
        a_f = (
            DB.session.query(TAcquisitionFramework.id_acquisition_framework)
            .filter(TAcquisitionFramework.unique_acquisition_framework_id == uuid_af)
            .first()
        )
        if a_f:
            return a_f[0]
        return a_f

    @staticmethod
    def get_user_af(user, only_query=False, only_user=False):
        """get the af(s) where the user is actor (himself or with its organism - only himelsemf id only_use=True) or digitizer
            param: 
              - user from TRole model
              - only_query: boolean (return the query not the id_datasets allowed if true)
              - only_user: boolean: return only the dataset where user himself is actor (not with its organoism)

            return: a list of id_dataset or a query"""
        q = DB.session.query(TAcquisitionFramework.id_acquisition_framework).outerjoin(
            CorAcquisitionFrameworkActor,
            CorAcquisitionFrameworkActor.id_acquisition_framework
            == TAcquisitionFramework.id_acquisition_framework,
        )
        if user.id_organisme is None or only_user:
            q = q.filter(
                or_(
                    CorAcquisitionFrameworkActor.id_role == user.id_role,
                    TAcquisitionFramework.id_digitizer == user.id_role,
                )
            )
        else:
            q = q.filter(
                or_(
                    CorAcquisitionFrameworkActor.id_organism == user.id_organisme,
                    CorAcquisitionFrameworkActor.id_role == user.id_role,
                    TAcquisitionFramework.id_digitizer == user.id_role,
                )
            )
        if only_query:
            return q
        data = q.all()
        return list(set([d.id_acquisition_framework for d in data]))
Example #7
0
class TDatasets(CruvedHelper):
    __tablename__ = "t_datasets"
    __table_args__ = {"schema": "gn_meta"}
    id_dataset = DB.Column(DB.Integer, primary_key=True)
    unique_dataset_id = DB.Column(UUID(as_uuid=True), default=select([func.uuid_generate_v4()]))
    id_acquisition_framework = DB.Column(
        DB.Integer, ForeignKey("gn_meta.t_acquisition_frameworks.id_acquisition_framework"),
    )
    dataset_name = DB.Column(DB.Unicode)
    dataset_shortname = DB.Column(DB.Unicode)
    dataset_desc = DB.Column(DB.Unicode)
    id_nomenclature_data_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("DATA_TYP"),
    )
    keywords = DB.Column(DB.Unicode)
    marine_domain = DB.Column(DB.Boolean)
    terrestrial_domain = DB.Column(DB.Boolean)
    id_nomenclature_dataset_objectif = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("JDD_OBJECTIFS"),
    )
    bbox_west = DB.Column(DB.Float)
    bbox_east = DB.Column(DB.Float)
    bbox_south = DB.Column(DB.Float)
    bbox_north = DB.Column(DB.Float)
    id_nomenclature_collecting_method = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("METHO_RECUEIL"),
    )
    id_nomenclature_data_origin = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("DS_PUBLIQUE"),
    )
    id_nomenclature_source_status = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("STATUT_SOURCE"),
    )
    id_nomenclature_resource_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("RESOURCE_TYP"),
    )
    meta_create_date = DB.Column(DB.DateTime)
    meta_update_date = DB.Column(DB.DateTime)
    active = DB.Column(DB.Boolean, default=True)
    validable = DB.Column(DB.Boolean)
    id_digitizer = DB.Column(DB.Integer, ForeignKey("utilisateurs.t_roles.id_role"))
    id_taxa_list = DB.Column(DB.Integer)
    modules = DB.relationship("TModules", secondary=cor_module_dataset, lazy="select")

    creator = DB.relationship("User", lazy="joined")
    nomenclature_data_type = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_data_type),
    )
    nomenclature_dataset_objectif = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_dataset_objectif),
    )
    nomenclature_collecting_method = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(
            TNomenclatures.id_nomenclature == id_nomenclature_collecting_method
        ),
    )
    nomenclature_data_origin = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_data_origin),
    )
    nomenclature_source_status = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_source_status),
    )
    nomenclature_resource_type = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_resource_type),
    )

    cor_territories = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorDatasetTerritory.__table__,
        primaryjoin=(CorDatasetTerritory.id_dataset == id_dataset),
        secondaryjoin=(CorDatasetTerritory.id_nomenclature_territory == TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorDatasetTerritory.id_dataset,
            CorDatasetTerritory.id_nomenclature_territory,
        ],
        backref=DB.backref("territory_dataset", lazy="select")
    )

    # because CorDatasetActor could be an User or an Organisme object...
    cor_dataset_actor = relationship(
        CorDatasetActor,
        lazy="joined",
        cascade="save-update, merge, delete, delete-orphan",
        backref=DB.backref("actor_dataset", lazy="select")
    )

    def __str__(self):
        return self.dataset_name
        
    def get_object_cruved(
        self, info_role, user_cruved
    ):
        """
        Return the user's cruved for a Model instance.
        Use in the map-list interface to allow or not an action
        params:
            - user_cruved: object retourner by cruved_for_user_in_app(user) {'C': '2', 'R':'3' etc...}
            - id_object (int): id de l'objet sur lqurqul on veut vérifier le CRUVED (self.id_dataset/ self.id_ca)
            - id_role: identifiant de la personne qui demande la route
            - id_object_users_actor (list): identifiant des objects ou l'utilisateur est lui même acteur
            - id_object_organism_actor (list): identifiants des objects ou l'utilisateur ou son organisme sont acteurs

        Return: dict {'C': True, 'R': False ...}
        """
        return {
            action: self.user_is_allowed_to(self.cor_dataset_actor, info_role, level)
            for action, level in user_cruved.items()
        }

    @staticmethod
    def get_id(uuid_dataset):
        id_dataset = (
            DB.session.query(TDatasets.id_dataset)
            .filter(TDatasets.unique_dataset_id == uuid_dataset)
            .first()
        )
        if id_dataset:
            return id_dataset[0]
        return id_dataset

    @staticmethod
    def get_uuid(id_dataset):
        uuid_dataset = (
            DB.session.query(TDatasets.unique_dataset_id)
            .filter(TDatasets.id_dataset == id_dataset)
            .first()
        )
        if uuid_dataset:
            return uuid_dataset[0]
        return uuid_dataset

    @staticmethod
    def get_user_datasets(user, only_query=False, only_user=False):
        """get the dataset(s) where the user is actor (himself or with its organism - only himelsemf id only_use=True) or digitizer
            param: 
              - user from TRole model
              - only_query: boolean (return the query not the id_datasets allowed if true)
              - only_user: boolean: return only the dataset where user himself is actor (not with its organism)

            return: a list of id_dataset or a query"""
        q = DB.session.query(TDatasets).outerjoin(
            CorDatasetActor, CorDatasetActor.id_dataset == TDatasets.id_dataset
        )
        if user.id_organisme is None or only_user:
            q = q.filter(
                or_(
                    CorDatasetActor.id_role == user.id_role,
                    TDatasets.id_digitizer == user.id_role,
                )
            )
        else:
            q = q.filter(
                or_(
                    CorDatasetActor.id_organism == user.id_organisme,
                    CorDatasetActor.id_role == user.id_role,
                    TDatasets.id_digitizer == user.id_role,
                )
            )
        if only_query:
            return q
        return list(set([d.id_dataset for d in q.all()]))
Example #8
0
class TAcquisitionFramework(CruvedMixin, FilterMixin, db.Model):
    __tablename__ = "t_acquisition_frameworks"
    __table_args__ = {"schema": "gn_meta"}
    query_class = TAcquisitionFrameworkQuery

    id_acquisition_framework = DB.Column(DB.Integer, primary_key=True)
    unique_acquisition_framework_id = DB.Column(
        UUIDType(as_uuid=True), default=select([func.uuid_generate_v4()])
    )
    acquisition_framework_name = DB.Column(DB.Unicode(255))
    acquisition_framework_desc = DB.Column(DB.Unicode)
    id_nomenclature_territorial_level = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("NIVEAU_TERRITORIAL"),
    )
    territory_desc = DB.Column(DB.Unicode)
    keywords = DB.Column(DB.Unicode)
    id_nomenclature_financing_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("TYPE_FINANCEMENT"),
    )
    target_description = DB.Column(DB.Unicode)
    ecologic_or_geologic_target = DB.Column(DB.Unicode)
    acquisition_framework_parent_id = DB.Column(DB.Integer)
    is_parent = DB.Column(DB.Boolean)
    opened = DB.Column(DB.Boolean, default=True)
    id_digitizer = DB.Column(DB.Integer, ForeignKey(User.id_role))

    acquisition_framework_start_date = DB.Column(DB.Date, default=datetime.datetime.utcnow)
    acquisition_framework_end_date = DB.Column(DB.Date)

    meta_create_date = DB.Column(DB.DateTime)
    meta_update_date = DB.Column(DB.DateTime)
    initial_closing_date = DB.Column(DB.DateTime)

    creator = DB.relationship(User, lazy="joined")  # = digitizer
    nomenclature_territorial_level = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_territorial_level),
    )
    nomenclature_financing_type = DB.relationship(
        TNomenclatures,
        lazy="select",
        primaryjoin=(TNomenclatures.id_nomenclature == id_nomenclature_financing_type),
    )
    cor_af_actor = relationship(
        CorAcquisitionFrameworkActor,
        lazy="joined",
        #cascade="save-update, merge, delete, delete-orphan",
        cascade="all,delete-orphan",
        uselist=True,
        backref=DB.backref("actor_af", lazy="select")
    )

    cor_objectifs = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorAcquisitionFrameworkObjectif.__table__,
        primaryjoin=(
            CorAcquisitionFrameworkObjectif.id_acquisition_framework == id_acquisition_framework
        ),
        secondaryjoin=(
            CorAcquisitionFrameworkObjectif.id_nomenclature_objectif
            == TNomenclatures.id_nomenclature
        ),
        foreign_keys=[
            CorAcquisitionFrameworkObjectif.id_acquisition_framework,
            CorAcquisitionFrameworkObjectif.id_nomenclature_objectif,
        ],
        backref=DB.backref("objectif_af", lazy="select")
    )

    cor_volets_sinp = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorAcquisitionFrameworkVoletSINP.__table__,
        primaryjoin=(CorAcquisitionFrameworkVoletSINP.id_acquisition_framework == id_acquisition_framework),
        secondaryjoin=(CorAcquisitionFrameworkVoletSINP.id_nomenclature_voletsinp == TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorAcquisitionFrameworkVoletSINP.id_acquisition_framework,
            CorAcquisitionFrameworkVoletSINP.id_nomenclature_voletsinp,
        ],
        backref=DB.backref("volet_sinp_af", lazy="select")
    )

    cor_territories = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorAcquisitionFrameworkTerritory.__table__,
        primaryjoin=(CorAcquisitionFrameworkTerritory.id_acquisition_framework == id_acquisition_framework),
        secondaryjoin=(CorAcquisitionFrameworkTerritory.id_nomenclature_territory == TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorAcquisitionFrameworkTerritory.id_acquisition_framework,
            CorAcquisitionFrameworkTerritory.id_nomenclature_territory,
        ],
        backref=DB.backref("territory_af", lazy="select")
    )

    bibliographical_references = DB.relationship(
        "TBibliographicReference",
        lazy="select",
        cascade="all,delete-orphan",
        uselist=True,
        backref=DB.backref("acquisition_framework", lazy="select"),
    )

    t_datasets = DB.relationship(
        "TDatasets",
        lazy="joined",  # DS required for permissions checks
        cascade="all,delete-orphan",
        uselist=True,
    )
    datasets = synonym("t_datasets")

    @hybrid_property
    def user_actors(self):
        return [ actor.role for actor in self.cor_af_actor if actor.role is not None ]

    @hybrid_property
    def organism_actors(self):
        return [ actor.organism for actor in self.cor_af_actor if actor.organism is not None ]

    def is_deletable(self):
        return not db.session.query(
            TDatasets.query
            .filter_by(id_acquisition_framework=self.id_acquisition_framework)
            .exists()
        ).scalar()

    def has_instance_permission(self, scope, _through_ds=True):
        if scope == 0:
            return False
        elif scope in (1, 2):
            if g.current_user == self.creator or g.current_user in self.user_actors:
                return True
            if scope == 2 and g.current_user.organisme in self.organism_actors:
                return True
            # rights on DS give rights on AF!
            return _through_ds and any(map(lambda ds: ds.has_instance_permission(scope, _through_af=False), self.t_datasets))
        elif scope == 3:
            return True

    @staticmethod
    def get_id(uuid_af):
        """
            return the acquisition framework's id
            from its UUID if exist or None
        """
        a_f = (
            DB.session.query(TAcquisitionFramework.id_acquisition_framework)
            .filter(TAcquisitionFramework.unique_acquisition_framework_id == uuid_af)
            .first()
        )
        if a_f:
            return a_f[0]
        return a_f

    @staticmethod
    def get_user_af(user, only_query=False, only_user=False):
        """get the af(s) where the user is actor (himself or with its organism - only himelsemf id only_use=True) or digitizer
            param: 
              - user from TRole model
              - only_query: boolean (return the query not the id_datasets allowed if true)
              - only_user: boolean: return only the dataset where user himself is actor (not with its organoism)

            return: a list of id_dataset or a query"""
        q = DB.session.query(TAcquisitionFramework.id_acquisition_framework).outerjoin(
            CorAcquisitionFrameworkActor,
            CorAcquisitionFrameworkActor.id_acquisition_framework
            == TAcquisitionFramework.id_acquisition_framework,
        )
        if user.id_organisme is None or only_user:
            q = q.filter(
                or_(
                    CorAcquisitionFrameworkActor.id_role == user.id_role,
                    TAcquisitionFramework.id_digitizer == user.id_role,
                )
            )
        else:
            q = q.filter(
                or_(
                    CorAcquisitionFrameworkActor.id_organism == user.id_organisme,
                    CorAcquisitionFrameworkActor.id_role == user.id_role,
                    TAcquisitionFramework.id_digitizer == user.id_role,
                )
            )
        if only_query:
            return q
        data = q.all()
        return list(set([d.id_acquisition_framework for d in data]))

    @classmethod
    def compute_filter(cls, **kwargs):
        f = super().compute_filter(**kwargs)
        uuid = kwargs.get('uuid')
        if uuid is not None:
            try:
                uuid = UUID(uuid.strip())
            except TypeError:
                pass
            else:
                f &= TAcquisitionFramework.unique_acquisition_framework_id == uuid
        name = kwargs.get('name')
        if name is not None:
            f &= TAcquisitionFramework.acquisition_framework_name.ilike(f'%{name}%')
        return f
Example #9
0
class TDatasets(CruvedMixin, FilterMixin, db.Model):
    __tablename__ = "t_datasets"
    __table_args__ = {"schema": "gn_meta"}
    query_class = TDatasetsQuery

    id_dataset = DB.Column(DB.Integer, primary_key=True)
    unique_dataset_id = DB.Column(UUIDType(as_uuid=True), default=select([func.uuid_generate_v4()]))
    id_acquisition_framework = DB.Column(
        DB.Integer, ForeignKey("gn_meta.t_acquisition_frameworks.id_acquisition_framework"),
    )
    acquisition_framework = DB.relationship("TAcquisitionFramework", lazy="joined")  # join AF as required for permissions checks
    dataset_name = DB.Column(DB.Unicode)
    dataset_shortname = DB.Column(DB.Unicode)
    dataset_desc = DB.Column(DB.Unicode)
    id_nomenclature_data_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("DATA_TYP"),
    )
    keywords = DB.Column(DB.Unicode)
    marine_domain = DB.Column(DB.Boolean)
    terrestrial_domain = DB.Column(DB.Boolean)
    id_nomenclature_dataset_objectif = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("JDD_OBJECTIFS"),
    )
    bbox_west = DB.Column(DB.Float)
    bbox_east = DB.Column(DB.Float)
    bbox_south = DB.Column(DB.Float)
    bbox_north = DB.Column(DB.Float)
    id_nomenclature_collecting_method = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("METHO_RECUEIL"),
    )
    id_nomenclature_data_origin = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("DS_PUBLIQUE"),
    )
    id_nomenclature_source_status = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("STATUT_SOURCE"),
    )
    id_nomenclature_resource_type = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("RESOURCE_TYP"),
    )
    meta_create_date = DB.Column(DB.DateTime)
    meta_update_date = DB.Column(DB.DateTime)
    active = DB.Column(DB.Boolean, default=True)
    validable = DB.Column(DB.Boolean, server_default=FetchedValue())
    id_digitizer = DB.Column(DB.Integer, ForeignKey(User.id_role))
    digitizer = DB.relationship(User, lazy="joined")  # joined for permission check
    id_taxa_list = DB.Column(DB.Integer)
    modules = DB.relationship("TModules", secondary=cor_module_dataset, lazy="select")

    creator = DB.relationship(User, lazy="joined")  # = digitizer
    nomenclature_data_type = DB.relationship(
        TNomenclatures,
        lazy="select",
        foreign_keys=[id_nomenclature_data_type],
    )
    nomenclature_dataset_objectif = DB.relationship(
        TNomenclatures,
        lazy="select",
        foreign_keys=[id_nomenclature_dataset_objectif],
    )
    nomenclature_collecting_method = DB.relationship(
        TNomenclatures,
        lazy="select",
        foreign_keys=[id_nomenclature_collecting_method],
    )
    nomenclature_data_origin = DB.relationship(
        TNomenclatures,
        lazy="select",
        foreign_keys=[id_nomenclature_data_origin],
    )
    nomenclature_source_status = DB.relationship(
        TNomenclatures,
        lazy="select",
        foreign_keys=[id_nomenclature_source_status],
    )
    nomenclature_resource_type = DB.relationship(
        TNomenclatures,
        lazy="select",
        foreign_keys=[id_nomenclature_resource_type],
    )

    cor_territories = DB.relationship(
        TNomenclatures,
        lazy="select",
        secondary=CorDatasetTerritory.__table__,
        primaryjoin=(CorDatasetTerritory.id_dataset == id_dataset),
        secondaryjoin=(CorDatasetTerritory.id_nomenclature_territory == TNomenclatures.id_nomenclature),
        foreign_keys=[
            CorDatasetTerritory.id_dataset,
            CorDatasetTerritory.id_nomenclature_territory,
        ],
        backref=DB.backref("territory_dataset", lazy="select")
    )

    # because CorDatasetActor could be an User or an Organisme object...
    cor_dataset_actor = relationship(
        CorDatasetActor,
        lazy="joined",
        cascade="save-update, merge, delete, delete-orphan",
        backref=DB.backref("actor_dataset", lazy="select")
    )

    @hybrid_property
    def user_actors(self):
        return [ actor.role for actor in self.cor_dataset_actor if actor.role is not None ]

    @hybrid_property
    def organism_actors(self):
        return [ actor.organism for actor in self.cor_dataset_actor if actor.organism is not None ]

    def is_deletable(self):
        return not DB.session.query(self.synthese_records.exists()).scalar()

    def has_instance_permission(self, scope, _through_af=True):
        """
        _through_af prevent infinite recursion
        """
        if scope == 0:
            return False
        elif scope in (1, 2):
            if g.current_user == self.digitizer or g.current_user in self.user_actors:
                return True
            if scope == 2 and g.current_user.organisme in self.organism_actors:
                return True
            return _through_af and self.acquisition_framework.has_instance_permission(scope, _through_ds=False)
        elif scope == 3:
            return True

    def __str__(self):
        return self.dataset_name

    @staticmethod
    def get_id(uuid_dataset):
        id_dataset = (
            DB.session.query(TDatasets.id_dataset)
            .filter(TDatasets.unique_dataset_id == uuid_dataset)
            .first()
        )
        if id_dataset:
            return id_dataset[0]
        return id_dataset

    @staticmethod
    def get_uuid(id_dataset):
        uuid_dataset = (
            DB.session.query(TDatasets.unique_dataset_id)
            .filter(TDatasets.id_dataset == id_dataset)
            .first()
        )
        if uuid_dataset:
            return uuid_dataset[0]
        return uuid_dataset

    @classmethod
    def compute_filter(cls, **kwargs):
        f = super().compute_filter(**kwargs)
        uuid = kwargs.get('uuid')
        if uuid is not None:
            try:
                uuid = UUID(uuid.strip())
            except TypeError:
                pass
            else:
                f &= TDatasets.unique_dataset_id == uuid
        name = kwargs.get('name')
        if name is not None:
            f &= TDatasets.dataset_name.ilike(f'%{name}%')
        return f
Example #10
0
class CorDatasetActor(DB.Model):
    __tablename__ = "cor_dataset_actor"
    __table_args__ = {"schema": "gn_meta"}
    id_cda = DB.Column(DB.Integer, primary_key=True)
    id_dataset = DB.Column(DB.Integer, ForeignKey("gn_meta.t_datasets.id_dataset"))
    id_role = DB.Column(DB.Integer, ForeignKey(User.id_role))
    id_organism = DB.Column(DB.Integer, ForeignKey(Organisme.id_organisme))

    id_nomenclature_actor_role = DB.Column(
        DB.Integer,
        ForeignKey("ref_nomenclatures.t_nomenclatures.id_nomenclature"),
        default=lambda: TNomenclatures.get_default_nomenclature("ROLE_ACTEUR"),
    )
    nomenclature_actor_role = DB.relationship(
        TNomenclatures,
        lazy="joined",
        foreign_keys=[id_nomenclature_actor_role],
    )

    role = DB.relationship(User, lazy="joined")
    organism = relationship(Organisme, lazy="joined")

    @hybrid_property
    def actor(self):
        if self.role is not None:
            return self.role
        else:
            return self.organism

    @hybrid_property
    def display(self):
        if self.role:
            actor = self.role.nom_complet
        else:
            actor = self.organism.nom_organisme
        return '{} ({})'.format(actor, self.nomenclature_actor_role.label_default)

    @staticmethod
    def get_actor(id_dataset, id_nomenclature_actor_role, id_role=None, id_organism=None):
        """
            Get CorDatasetActor from id_dataset, id_actor, and id_role or id_organism.
            if no object return None
        """
        try:
            if id_role is None:
                return (
                    DB.session.query(CorDatasetActor)
                    .filter_by(
                        id_dataset=id_dataset,
                        id_organism=id_organism,
                        id_nomenclature_actor_role=id_nomenclature_actor_role,
                    )
                    .one()
                )
            elif id_organism is None:
                return (
                    DB.session.query(CorDatasetActor)
                    .filter_by(
                        id_dataset=id_dataset,
                        id_role=id_role,
                        id_nomenclature_actor_role=id_nomenclature_actor_role,
                    )
                    .one()
                )
        except exc.NoResultFound:
            return None