Example #1
0
def get_acquisition_frameworks_metadata(info_role):
    """
    Get all AF with cruved filter
    Use for metadata module. 
    Add the cruved permission for each row

    .. :quickref: Metadata;

    """
    params = request.args
    afs = get_af_cruved(info_role, params, as_model=True)
    id_afs_user = TAcquisitionFramework.get_user_af(info_role, only_user=True)
    id_afs_org = TAcquisitionFramework.get_user_af(info_role, only_user=False)
    user_cruved = cruved_scope_for_user_in_module(
        id_role=info_role.id_role,
        module_code="METADATA",
    )[0]
    afs_dict = []
    for af in afs:
        af_dict = af.as_dict()
        af_dict["cruved"] = af.get_object_cruved(
            user_cruved=user_cruved,
            id_object=af.id_acquisition_framework,
            ids_object_user=id_afs_user,
            ids_object_organism=id_afs_org,
        )
        afs_dict.append(af_dict)
    return afs_dict
Example #2
0
def post_acquisition_framework():
    data = dict(request.get_json())

    cor_af_actor = data.pop('cor_af_actor')
    cor_objectifs = data.pop('cor_objectifs')
    cor_volets_sinp = data.pop('cor_volets_sinp')

    af = TAcquisitionFramework(**data)

    for cor in cor_af_actor:
        af.cor_af_actor.append(CorAcquisitionFrameworkActor(**cor))

    if cor_objectifs is not None:
        objectif_nom = DB.session.query(TNomenclatures).filter(
            TNomenclatures.id_nomenclature.in_(cor_objectifs)).all()
        for obj in objectif_nom:
            af.cor_objectifs.append(obj)

    if cor_volets_sinp is not None:
        volet_nom = DB.session.query(TNomenclatures).filter(
            TNomenclatures.id_nomenclature.in_(cor_volets_sinp)).all()
        for volet in volet_nom:
            af.cor_volets_sinp.append(volet)
    if af.id_acquisition_framework:
        DB.session.merge(af)
    else:
        DB.session.add(af)
    DB.session.commit()
    return af.as_dict()
Example #3
0
def create_dataset_user(user):
    """
        After dataset validation, add a personnal AF and JDD so the user 
        can add new user.
    """
    af_desc_and_name = "Cadre d'acquisition personnel de {name} {surname}".format(
        name=user["nom_role"], surname=user["prenom_role"])

    #  actor = data productor
    af_productor = CorAcquisitionFrameworkActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "6"),
    )
    af_contact = CorAcquisitionFrameworkActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "1"),
    )

    new_af = TAcquisitionFramework(
        acquisition_framework_name=af_desc_and_name,
        acquisition_framework_desc=af_desc_and_name +
        " - auto-créé via la demande de création de compte",
        acquisition_framework_start_date=datetime.datetime.now(),
    )

    new_af.cor_af_actor = [af_productor, af_contact]

    DB.session.add(new_af)
    DB.session.commit()

    ds_desc_and_name = "Jeu de données personnel de {name} {surname}".format(
        name=user["nom_role"], surname=user["prenom_role"])
    ds_productor = CorDatasetActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "6"),
    )
    ds_contact = CorDatasetActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "1"),
    )
    # add new JDD: terrestrial and marine = True as default
    new_dataset = TDatasets(
        id_acquisition_framework=new_af.id_acquisition_framework,
        dataset_name=ds_desc_and_name,
        dataset_shortname=ds_desc_and_name +
        " - auto-créé via la demande de création de compte",
        dataset_desc=ds_desc_and_name,
        marine_domain=True,
        terrestrial_domain=True,
    )
    new_dataset.cor_dataset_actor = [ds_productor, ds_contact]
    DB.session.add(new_dataset)
    DB.session.commit()
Example #4
0
def post_acquisition_framework(info_role):
    """
    Post a dataset
    .. :quickref: Metadata;
    """
    if info_role.value_filter == "0":
        raise InsufficientRightsError(
            ('User "{}" cannot "{}" a dataset').format(
                info_role.id_role, info_role.code_action
            ),
            403,
        )
    data = dict(request.get_json())

    cor_af_actor = data.pop("cor_af_actor")
    cor_objectifs = data.pop("cor_objectifs")
    cor_volets_sinp = data.pop("cor_volets_sinp")

    af = TAcquisitionFramework(**data)

    for cor in cor_af_actor:
        # remove id_cda if None otherwise merge no working well
        if "id_cafa" in cor and cor["id_cafa"] is None:
            cor.pop("id_cafa")
        af.cor_af_actor.append(CorAcquisitionFrameworkActor(**cor))

    if cor_objectifs is not None:
        objectif_nom = (
            DB.session.query(TNomenclatures)
            .filter(TNomenclatures.id_nomenclature.in_(cor_objectifs))
            .all()
        )
        for obj in objectif_nom:
            af.cor_objectifs.append(obj)

    if cor_volets_sinp is not None:
        volet_nom = (
            DB.session.query(TNomenclatures)
            .filter(TNomenclatures.id_nomenclature.in_(cor_volets_sinp))
            .all()
        )
        for volet in volet_nom:
            af.cor_volets_sinp.append(volet)
    if af.id_acquisition_framework:
        DB.session.merge(af)
    else:
        af.id_digitizer = info_role.id_role
        DB.session.add(af)
    DB.session.commit()
    return af.as_dict()
Example #5
0
def post_acquisition_framework(uuid=None, id_user=None, id_organism=None):
    """ 
        Post an acquisition framwork from MTD XML
        Params:
            uuid (str): uuid of the acquisition framework
            id_user (int): the id of the user connected via CAS
            id_organism (int): the id of the organism user via CAS
    
    """
    xml_af = None
    xml_af = get_acquisition_framework(uuid)

    if xml_af:
        acquisition_framwork = parse_acquisition_framwork_xml(xml_af)
        actors = acquisition_framwork.pop("actors")
        new_af = TAcquisitionFramework(**acquisition_framwork)
        id_acquisition_framework = TAcquisitionFramework.get_id(uuid)
        # if the CA already exist in the DB
        if id_acquisition_framework:
            # delete cor_af_actor
            new_af.id_acquisition_framework = id_acquisition_framework

            delete_q = CorAcquisitionFrameworkActor.__table__.delete().where(
                CorAcquisitionFrameworkActor.id_acquisition_framework ==
                id_acquisition_framework)
            DB.session.execute(delete_q)
            DB.session.commit()
            create_cor_object_actors(actors, new_af)
            DB.session.merge(new_af)

        # its a new AF
        else:
            create_cor_object_actors(actors, new_af)
            # Add the new CA
            DB.session.add(new_af)
        # try to commit
        try:
            DB.session.commit()
        # TODO catch db error ?
        except SQLAlchemyError as e:
            DB.session.flush()
            DB.session.rollback()
            error_msg = "Error posting an aquisition framework\nTrace:\n{} \n\n ".format(
                e)
            log.error(error_msg)

        return new_af.as_dict()

    return {"message": "Not found"}, 404
Example #6
0
def post_acquisition_framework(info_role):
    if info_role.value_filter == "0":
        raise InsufficientRightsError(
            ('User "{}" cannot "{}" a dataser').format(
                info_role.id_role, info_role.code_action
            ),
            403,
        )
    data = dict(request.get_json())

    cor_af_actor = data.pop("cor_af_actor")
    cor_objectifs = data.pop("cor_objectifs")
    cor_volets_sinp = data.pop("cor_volets_sinp")

    af = TAcquisitionFramework(**data)

    for cor in cor_af_actor:
        # remove id_cda if None otherwise merge no working well
        if "id_cafa" in cor and cor["id_cafa"] is None:
            cor.pop("id_cafa")
        af.cor_af_actor.append(CorAcquisitionFrameworkActor(**cor))

    if cor_objectifs is not None:
        objectif_nom = (
            DB.session.query(TNomenclatures)
            .filter(TNomenclatures.id_nomenclature.in_(cor_objectifs))
            .all()
        )
        for obj in objectif_nom:
            af.cor_objectifs.append(obj)

    if cor_volets_sinp is not None:
        volet_nom = (
            DB.session.query(TNomenclatures)
            .filter(TNomenclatures.id_nomenclature.in_(cor_volets_sinp))
            .all()
        )
        for volet in volet_nom:
            af.cor_volets_sinp.append(volet)
    if af.id_acquisition_framework:
        DB.session.merge(af)
    else:
        DB.session.add(af)
    DB.session.commit()
    return af.as_dict()
Example #7
0
def create_acquisition_framework(info_role):
    """
    Post one AcquisitionFramework data
    .. :quickref: Metadata;
    """

    # create new acquisition_framework
    return AcquisitionFrameworkSchema().dump(
        acquisitionFrameworkHandler(request=request, acquisition_framework=TAcquisitionFramework(), info_role=info_role)
    )
Example #8
0
 def create_af(creator=None):
     with db.session.begin_nested():
         af = TAcquisitionFramework(acquisition_framework_name='test',
                                    acquisition_framework_desc='test',
                                    creator=creator)
         db.session.add(af)
         if creator and creator.organisme:
             actor = CorAcquisitionFrameworkActor(
                 organism=creator.organisme,
                 nomenclature_actor_role=principal_actor_role)
             af.cor_af_actor.append(actor)
     return af
Example #9
0
def post_acquisition_framework(uuid=None, id_user=None, id_organism=None):
    """ Post an acquisition framwork from MTD XML"""
    xml_af = None
    xml_af = get_acquisition_framework(uuid)


    if xml_af:
        acquisition_framwork = parse_acquisition_framwork_xml(xml_af)
        new_af = TAcquisitionFramework(**acquisition_framwork)
        actor = CorAcquisitionFrameworkActor(
            id_role=id_user,
            id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1')
        )
        new_af.cor_af_actor.append(actor)
        if id_organism:
            organism = CorAcquisitionFrameworkActor(
                id_organism=id_organism,
                id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1')
            )
            new_af.cor_af_actor.append(organism)
        # check if exist
        id_acquisition_framework = TAcquisitionFramework.get_id(uuid)
        try:
            if id_acquisition_framework:
                new_af.id_acquisition_framework = id_acquisition_framework[0]
                DB.session.merge(new_af)
            else:
                DB.session.add(new_af)
                DB.session.commit()
        # TODO catch db error ?
        except SQLAlchemyError as e:
            DB.session.rollback()
            error_msg = """
                Error posting an aquisition framework {} \n\n Trace: \n {}
                """.format(uuid, e)
            log.error(error_msg)

        return new_af.as_dict()

    return {'message': 'Not found'}, 404
Example #10
0
def get_af_and_ds_metadata(info_role):
    """
    Get all AF with their datasets 
    The Cruved in only apply on dataset in order to see all the AF
    where the user have rights with its dataset
    Use in maplist
    Add the CRUVED permission for each row (Dataset and AD)
    
    .. :quickref: Metadata;

    :param info_role: add with kwargs
    :type info_role: TRole
    :returns:  `dict{'data':list<AF with Datasets>, 'with_erros': <boolean>}`
    """
    with_mtd_error = False
    if current_app.config["CAS_PUBLIC"]["CAS_AUTHENTIFICATION"]:
        # synchronise the CA and JDD from the MTD WS
        try:
            mtd_utils.post_jdd_from_user(id_user=info_role.id_role,
                                         id_organism=info_role.id_organisme)
        except Exception as e:
            gunicorn_error_logger.info(e)
            log.error(e)
            with_mtd_error = True
    params = request.args.to_dict()
    params["orderby"] = "dataset_name"
    datasets = get_datasets_cruved(info_role, params, as_model=True)
    ids_dataset_user = TDatasets.get_user_datasets(info_role, only_user=True)
    ids_dataset_organisms = TDatasets.get_user_datasets(info_role,
                                                        only_user=False)
    ids_afs_user = TAcquisitionFramework.get_user_af(info_role, only_user=True)
    ids_afs_org = TAcquisitionFramework.get_user_af(info_role, only_user=False)
    user_cruved = cruved_scope_for_user_in_module(
        id_role=info_role.id_role,
        module_code="METADATA",
    )[0]

    #  get all af from the JDD filtered with cruved or af where users has rights
    ids_afs_cruved = [
        d.id_acquisition_framework
        for d in get_af_cruved(info_role, as_model=True)
    ]
    list_id_af = [d.id_acquisition_framework
                  for d in datasets] + ids_afs_cruved
    afs = (DB.session.query(TAcquisitionFramework).filter(
        TAcquisitionFramework.id_acquisition_framework.in_(
            list_id_af)).order_by(
                TAcquisitionFramework.acquisition_framework_name).all())

    afs_dict = []
    #  get cruved for each AF and prepare dataset
    for af in afs:
        af_dict = af.as_dict()
        af_dict["cruved"] = af.get_object_cruved(
            user_cruved=user_cruved,
            id_object=af.id_acquisition_framework,
            ids_object_user=ids_afs_user,
            ids_object_organism=ids_afs_org,
        )
        af_dict["datasets"] = []
        afs_dict.append(af_dict)

    #  get cruved for each ds and push them in the af
    for d in datasets:
        dataset_dict = d.as_dict()
        dataset_dict["cruved"] = d.get_object_cruved(
            user_cruved=user_cruved,
            id_object=d.id_dataset,
            ids_object_user=ids_dataset_user,
            ids_object_organism=ids_dataset_organisms,
        )
        af_of_dataset = get_af_from_id(d.id_acquisition_framework, afs_dict)
        af_of_dataset["datasets"].append(dataset_dict)

    afs_resp = {"data": afs_dict}
    if with_mtd_error:
        afs_resp["with_mtd_errors"] = True
    if not datasets:
        return afs_resp, 404
    return afs_resp
Example #11
0
def get_acquisition_framework_details(info_role, id_acquisition_framework):
    """
    Get one AF

    .. :quickref: Metadata;

    :param id_acquisition_framework: the id_acquisition_framework
    :param type: int
    """
    af = DB.session.query(TAcquisitionFrameworkDetails).get(id_acquisition_framework)
    if not af:
        return None
    acquisition_framework = af.as_dict(True)

    datasets = acquisition_framework["datasets"] if "datasets" in acquisition_framework else []
    dataset_ids = [d["id_dataset"] for d in datasets]
    geojsonData = (
        DB.session.query(func.ST_AsGeoJSON(func.ST_Extent(Synthese.the_geom_4326)))
        .filter(Synthese.id_dataset.in_(dataset_ids))
        .first()[0]
    )
    if geojsonData:
        acquisition_framework["bbox"] = json.loads(geojsonData)
    nb_data = len(dataset_ids)
    nb_taxons = (
        DB.session.query(Synthese.cd_nom)
        .filter(Synthese.id_dataset.in_(dataset_ids))
        .distinct()
        .count()
    )
    nb_observations = (
        DB.session.query(Synthese.cd_nom).filter(Synthese.id_dataset.in_(dataset_ids)).count()
    )
    nb_habitat = 0

    # Check if pr_occhab exist
    check_schema_query = exists(
        select([text("schema_name")])
        .select_from(text("information_schema.schemata"))
        .where(text("schema_name = 'pr_occhab'"))
    )

    if DB.session.query(check_schema_query).scalar() and nb_data > 0:
        query = (
            "SELECT count(*) FROM pr_occhab.t_stations s, pr_occhab.t_habitats h WHERE s.id_station = h.id_station AND s.id_dataset in \
        ("
            + str(dataset_ids).strip("[]")
            + ")"
        )

        nb_habitat = DB.engine.execute(text(query)).first()[0]

    acquisition_framework["stats"] = {
        "nb_data": nb_data,
        "nb_taxons": nb_taxons,
        "nb_observations": nb_observations,
        "nb_habitats": nb_habitat,
    }
    ids_afs_user = TAcquisitionFramework.get_user_af(info_role, only_user=True)
    ids_afs_org = TAcquisitionFramework.get_user_af(info_role, only_user=False)
    user_cruved = cruved_scope_for_user_in_module(
        id_role=info_role.id_role, module_code="METADATA",
    )[0]
    acquisition_framework["cruved"] = af.get_object_cruved(
        user_cruved=user_cruved,
        id_object=af.id_acquisition_framework,
        ids_object_user=ids_afs_user,
        ids_object_organism=ids_afs_org,
    )

    return acquisition_framework
Example #12
0
def get_af_and_ds_metadata(info_role):
    """
    Get all AF with their datasets 
    The Cruved in only apply on dataset in order to see all the AF
    where the user have rights with its dataset
    Use in maplist
    Add the CRUVED permission for each row (Dataset and AD)
    
    .. :quickref: Metadata;

    :param info_role: add with kwargs
    :type info_role: TRole
    :returns:  `dict{'data':list<AF with Datasets>, 'with_erros': <boolean>}`
    """
    with_mtd_error = False
    if current_app.config["CAS_PUBLIC"]["CAS_AUTHENTIFICATION"]:
        # synchronise the CA and JDD from the MTD WS
        try:
            mtd_utils.post_jdd_from_user(
                id_user=info_role.id_role, id_organism=info_role.id_organisme
            )
        except Exception as e:
            gunicorn_error_logger.info(e)
            log.error(e)
            with_mtd_error = True
    params = request.args.to_dict()
    params["orderby"] = "dataset_name"
    if "selector" not in params:
        params["selector"] = None
    datasets = filtered_ds_query(info_role, params).distinct().all()
    if len(datasets) == 0:
        return {"data": []}
    ids_dataset_user = TDatasets.get_user_datasets(info_role, only_user=True)

    ids_dataset_organisms = TDatasets.get_user_datasets(info_role, only_user=False)
    ids_afs_user = TAcquisitionFramework.get_user_af(info_role, only_user=True)
    ids_afs_org = TAcquisitionFramework.get_user_af(info_role, only_user=False)
    user_cruved = cruved_scope_for_user_in_module(
        id_role=info_role.id_role, module_code="METADATA",
    )[0]


    #  get all af from the JDD filtered with cruved or af where users has rights
    ids_afs_cruved = (
        [d.id_acquisition_framework for d in get_af_cruved(info_role, as_model=True)]
        if not params["selector"]
        else []
    )
    list_id_af = [d.id_acquisition_framework for d in datasets] + ids_afs_cruved
    afs = (
        filtered_af_query(request.args)
        .filter(TAcquisitionFramework.id_acquisition_framework.in_(list_id_af))
        .order_by(TAcquisitionFramework.acquisition_framework_name)
        .all()
    )
    list_id_af = [af.id_acquisition_framework for af in afs]

    afs_dict = []
    #  get cruved for each AF and prepare dataset
    for af in afs:
        af_dict = af.as_dict(
            True,
            relationships=[
                "creator",
                "cor_af_actor",
                "nomenclature_actor_role",
                "organism",
                "role",
            ],
        )
        af_dict["cruved"] = af.get_object_cruved(
            user_cruved=user_cruved,
            id_object=af.id_acquisition_framework,
            ids_object_user=ids_afs_user,
            ids_object_organism=ids_afs_org,
        )
        af_dict["datasets"] = []
        af_dict["deletable"] = is_af_deletable(af.id_acquisition_framework)
        afs_dict.append(af_dict)

    #  get cruved for each ds and push them in the af
    for d in datasets:
        dataset_dict = d.as_dict(
            recursif=True,
            relationships=[
                "creator",
                "cor_dataset_actor",
                "nomenclature_actor_role",
                "organism",
                "role",
            ],
        )
        if d.id_acquisition_framework not in list_id_af:
            continue
        dataset_dict["cruved"] = d.get_object_cruved(
            user_cruved=user_cruved,
            id_object=d.id_dataset,
            ids_object_user=ids_dataset_user,
            ids_object_organism=ids_dataset_organisms,
        )
        # dataset_dict["observation_count"] = (
        #     DB.session.query(Synthese.cd_nom).filter(Synthese.id_dataset == d.id_dataset).count()
        # )
        dataset_dict["deletable"] = is_dataset_deletable(d.id_dataset)
        af_of_dataset = get_af_from_id(d.id_acquisition_framework, afs_dict)
        af_of_dataset["datasets"].append(dataset_dict)

    afs_resp = {"data": afs_dict}
    if with_mtd_error:
        afs_resp["with_mtd_errors"] = True
    if not datasets:
        return afs_resp, 404
    return afs_resp
Example #13
0
def create_dataset_user(user):
    """
        After dataset validation, add a personnal AF and JDD so the user
        can add new user.
    """
    af_desc_and_name = "Cadre d'acquisition personnel de {name} {surname}".format(
        name=user["nom_role"], surname=user["prenom_role"])

    #  actor = data productor
    af_productor = CorAcquisitionFrameworkActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "6"),
    )
    af_contact = CorAcquisitionFrameworkActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "1"),
    )

    new_af = TAcquisitionFramework(
        acquisition_framework_name=af_desc_and_name,
        acquisition_framework_desc=af_desc_and_name +
        " - auto-créé via la demande de création de compte",
        acquisition_framework_start_date=datetime.datetime.now(),
    )

    new_af.cor_af_actor = [af_productor, af_contact]

    db.session.add(new_af)

    ds_desc_and_name = "Jeu de données personnel de {name} {surname}".format(
        name=user["nom_role"], surname=user["prenom_role"])
    ds_productor = CorDatasetActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "6"),
    )
    ds_contact = CorDatasetActor(
        id_role=user["id_role"],
        id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature(
            "ROLE_ACTEUR", "1"),
    )
    # add new JDD: terrestrial and marine = True as default
    new_dataset = TDatasets(
        acquisition_framework=new_af,
        dataset_name=ds_desc_and_name,
        dataset_shortname=ds_desc_and_name +
        " - auto-créé via la demande de création de compte",
        dataset_desc=ds_desc_and_name,
        marine_domain=True,
        terrestrial_domain=True,
    )
    new_dataset.cor_dataset_actor = [ds_productor, ds_contact]
    db.session.add(new_dataset)

    for module_code in current_app.config['ACCOUNT_MANAGEMENT'][
            'DATASET_MODULES_ASSOCIATION']:
        module = TModules.query.filter_by(
            module_code=module_code).one_or_none()
        if module is None:
            warn("Module code '{}' does not exist, can not associate dataset.".
                 format(module_code))
            continue
        new_dataset.modules.append(module)

    db.session.commit()
Example #14
0
def post_acquisition_framework(uuid=None, id_user=None, id_organism=None):
    """ 
        Post an acquisition framwork from MTD XML
        Params:
            uuid (str): uuid of the acquisition framework
            id_user (int): the id of the user connected via CAS
            id_organism (int): the id of the organism user via CAS
    
    """
    xml_af = None
    xml_af = get_acquisition_framework(uuid)

    if xml_af:
        acquisition_framwork = parse_acquisition_framwork_xml(xml_af)
        new_af = TAcquisitionFramework(**acquisition_framwork)
        id_acquisition_framework = TAcquisitionFramework.get_id(uuid)
        # if the CA already exist in the DB
        if id_acquisition_framework:
            # check if actor role not already exist for this CA
            actor_role = CorAcquisitionFrameworkActor.get_actor(
                id_acquisition_framework=id_acquisition_framework,
                id_nomenclature_actor_role=func.ref_nomenclatures.
                get_id_nomenclature('ROLE_ACTEUR', '1'),
                id_role=id_user)

            # if no actor push it
            if actor_role is None:
                actor = CorAcquisitionFrameworkActor(
                    id_role=id_user,
                    id_nomenclature_actor_role=func.ref_nomenclatures.
                    get_id_nomenclature('ROLE_ACTEUR', '1'))
                new_af.cor_af_actor.append(actor)

            # # check if actor role not already exist for this CA
            actor_organism = None
            if id_organism:
                actor_organism = CorAcquisitionFrameworkActor.get_actor(
                    id_acquisition_framework=id_acquisition_framework,
                    id_nomenclature_actor_role=func.ref_nomenclatures.
                    get_id_nomenclature('ROLE_ACTEUR', '1'),
                    id_organism=id_organism)
            if actor_organism is None:
                organism = CorAcquisitionFrameworkActor(
                    id_organism=id_organism,
                    id_nomenclature_actor_role=func.ref_nomenclatures.
                    get_id_nomenclature('ROLE_ACTEUR', '1'))
                new_af.cor_af_actor.append(organism)

            # finnaly merge the CA
            new_af.id_acquisition_framework = id_acquisition_framework
            DB.session.merge(new_af)

        #its a new AF
        else:
            actor = CorAcquisitionFrameworkActor(
                id_role=id_user,
                id_nomenclature_actor_role=func.ref_nomenclatures.
                get_id_nomenclature('ROLE_ACTEUR', '1'))
            new_af.cor_af_actor.append(actor)
            if id_organism:
                organism = CorAcquisitionFrameworkActor(
                    id_organism=id_organism,
                    id_nomenclature_actor_role=func.ref_nomenclatures.
                    get_id_nomenclature('ROLE_ACTEUR', '1'))
                new_af.cor_af_actor.append(organism)

            # Add the new CA
            DB.session.add(new_af)
        # try to commit
        try:
            DB.session.commit()
        # TODO catch db error ?
        except SQLAlchemyError as e:
            DB.session.flush()
            DB.session.rollback()
            error_msg = """
                Error posting an aquisition framework {} \n\n Trace: \n {}
                """.format(uuid, e)
            log.error(error_msg)

        return new_af.as_dict()

    return {'message': 'Not found'}, 404
Example #15
0
def post_acquisition_framework(uuid=None, id_user=None, id_organism=None):
    """ 
        Post an acquisition framwork from MTD XML
        Params:
            uuid (str): uuid of the acquisition framework
            id_user (int): the id of the user connected via CAS
            id_organism (int): the id of the organism user via CAS
    
    """
    xml_af = None
    xml_af = get_acquisition_framework(uuid)

    if xml_af:
        acquisition_framwork = parse_acquisition_framwork_xml(xml_af)
        new_af = TAcquisitionFramework(**acquisition_framwork)
        id_acquisition_framework = TAcquisitionFramework.get_id(uuid)
        # if the CA already exist in the DB
        if id_acquisition_framework:
            # check if actor role not already exist for this CA
            actor_role = CorAcquisitionFrameworkActor.get_actor(
                id_acquisition_framework=id_acquisition_framework,
                id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1'),
                id_role=id_user
            )

            # if no actor push it
            if actor_role is None:
                actor = CorAcquisitionFrameworkActor(
                    id_role=id_user,
                    id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1')
                )
                new_af.cor_af_actor.append(actor)

            # # check if actor role not already exist for this CA
            actor_organism = None
            if id_organism:
                actor_organism = CorAcquisitionFrameworkActor.get_actor(
                    id_acquisition_framework=id_acquisition_framework,
                    id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1'),
                    id_organism=id_organism
                )
            if actor_organism is None:
                organism = CorAcquisitionFrameworkActor(
                    id_organism=id_organism,
                    id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1')
                )
                new_af.cor_af_actor.append(organism)

            # finnaly merge the CA
            new_af.id_acquisition_framework = id_acquisition_framework
            DB.session.merge(new_af)

        #its a new AF
        else:
            actor = CorAcquisitionFrameworkActor(
                id_role=id_user,
                id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1')
            )
            new_af.cor_af_actor.append(actor)
            if id_organism:
                organism = CorAcquisitionFrameworkActor(
                    id_organism=id_organism,
                    id_nomenclature_actor_role=func.ref_nomenclatures.get_id_nomenclature('ROLE_ACTEUR', '1')
                )
                new_af.cor_af_actor.append(organism)

            # Add the new CA
            DB.session.add(new_af)
        # try to commit
        try:
            DB.session.commit()
        # TODO catch db error ?
        except SQLAlchemyError as e:
            DB.session.flush()
            DB.session.rollback()
            error_msg = """
                Error posting an aquisition framework {} \n\n Trace: \n {}
                """.format(uuid, e)
            log.error(error_msg)

        return new_af.as_dict()

    return {'message': 'Not found'}, 404