コード例 #1
0
def resolve_copo_datafile_id_data(data, elem):
    resolved_data = dict()

    da_object = DAComponent(component="datafile")

    if data:
        datafile = da_object.get_record(data)
        resolved_data["recordLabel"] = datafile.get("name", str())
        resolved_data["recordID"] = data

    return resolved_data
コード例 #2
0
def generate_copo_form(component=str(), target_id=str(), component_dict=dict(), message_dict=dict(), profile_id=str(),
                       **kwargs):
    # message_dict templates are defined in the lookup dictionary: "MESSAGES_LKUPS"

    label_dict = get_labels()

    da_object = DAComponent(component=component, profile_id=profile_id)

    if component in da_dict:
        da_object = da_dict[component](profile_id)

    form_value = component_dict

    # get record, if in edit mode
    if target_id:
        form_value = da_object.get_record(target_id)

    form_schema = list()

    # get schema fields
    for f in da_object.get_component_schema(**kwargs):
        if f.get("show_in_form", True):

            # if required, resolve data source for select-type controls,
            # i.e., if a callback is defined on the 'option_values' field
            if "option_values" in f or f.get("control", "text") in ["copo-lookup", "copo-lookup2"]:
                f['data'] = form_value.get(f["id"].split(".")[-1], str())
                f["option_values"] = get_control_options(f)

            # resolve values for unique items...
            # if a list of unique items is provided with the schema, use it, else dynamically
            # generate unique items based on the component records
            if "unique" in f and not f.get("unique_items", list()):
                f["unique_items"] = generate_unique_items(component=component, profile_id=profile_id,
                                                          elem_id=f["id"].split(".")[-1], record_id=target_id, **kwargs)

            # filter based on sample type
            if component == "sample" and not filter_sample_type(form_value, f):
                continue

            form_schema.append(f)

    if form_value:
        form_value["_id"] = str(target_id)
    else:
        form_value = str()

    return dict(component_name=component,
                form_label=label_dict.get(component, dict()).get("label", str()),
                form_value=form_value,
                target_id=target_id,
                form_schema=form_schema,
                form_message=message_dict,
                )
コード例 #3
0
ファイル: html_tags.py プロジェクト: ISA-tools/COPO
def generate_copo_form(component=str(), target_id=str(), component_dict=dict(), message_dict=dict(), profile_id=str()):
    # message_dict templates are defined in the lookup dictionary, "MESSAGES_LKUPS"

    label_dict = dict(publication=dict(label="Publication", clonable=False),
                      person=dict(label="Person", clonable=False),
                      sample=dict(label="Sample", clonable=False),
                      source=dict(label="Source", clonable=True),
                      profile=dict(label="Profile", clonable=False),
                      annotation=dict(label="Annotation", clonable=False),
                      )

    da_object = DAComponent(component=component, profile_id=profile_id)

    form_value = component_dict

    # get record, if in edit mode
    if target_id:
        form_value = da_object.get_record(target_id)

    form_schema = list()

    # get schema fields
    for f in da_object.get_schema().get("schema_dict"):
        if f.get("show_in_form", True):

            # if required, resolve data source for select-type controls,
            # i.e., if a callback is defined on the 'option_values' field

            if "option_values" in f:
                f["option_values"] = get_control_options(f)

            # filter based on sample type
            if component == "sample" and not filter_sample_type(form_value, f):
                continue

            form_schema.append(f)

    # get all records: used in the UI for 'cloning' and other purposes
    component_records = generate_component_records(component, profile_id)
    # if label_dict.get(component, dict()).get("clonable", False):
    #     component_records = generate_component_records(component, profile_id)

    return dict(component_name=component,
                form_label=label_dict.get(component, dict()).get("label", str()),
                form_value=form_value,
                target_id=target_id,
                form_schema=form_schema,
                form_message=message_dict,
                component_records=component_records,
                clonable=label_dict.get(component, dict()).get("clonable", False),
                )
コード例 #4
0
class BrokerDA:
    def __init__(self, **kwargs):
        self.param_dict = kwargs
        self.context = self.param_dict.get("context", dict())
        self.component = self.param_dict.get("component", str())
        self.visualize = self.param_dict.get("visualize", str())
        self.profile_id = self.param_dict.get("profile_id", str())
        self.auto_fields = self.param_dict.get("auto_fields", dict())

        if self.auto_fields and isinstance(self.auto_fields, str):
            self.auto_fields = json.loads(self.auto_fields)

        self.broker_visuals = BrokerVisuals(**kwargs)
        self.da_object = DAComponent(self.profile_id, self.component)

        da_dict = dict(publication=Publication,
                       person=Person,
                       sample=Sample,
                       source=Source,
                       profile=Profile,
                       datafile=DataFile,
                       submission=Submission,
                       annotation=Annotation,
                       cgcore=CGCore,
                       metadata_template=MetadataTemplate)

        if self.component in da_dict:
            self.da_object = da_dict[self.component](self.profile_id)

    def set_extra_params(self, extra_param):
        for k, v in extra_param.items():
            self.param_dict[k] = v

    def do_form_control_schemas(self):
        """
        function returns object type control schemas used in building form controls
        :return:
        """

        copo_schemas = dict()
        for k, v in d_utils.object_type_control_map().items():
            copo_schemas[k] = d_utils.get_copo_schema(v)

        self.context["copo_schemas"] = copo_schemas
        return self.context

    def do_save_edit(self):
        kwargs = dict()
        kwargs["target_id"] = self.param_dict.get("target_id", str())

        # set report parameter
        status = "success"  # 'success', 'warning', 'info', 'danger' - modelled after bootstrap alert classes
        action_type = "add"

        report_metadata = dict()

        if self.param_dict.get("target_id", str()):
            action_type = "edit"

        record_object = self.da_object.save_record(self.auto_fields, **kwargs)

        if not record_object:
            status = "danger"

        if action_type == "add":
            report_metadata[
                "message"] = "New " + self.component + " record created!"
            if status != "success":
                report_metadata[
                    "message"] = "There was a problem creating the " + self.component + " record!"
        elif action_type == "edit":
            report_metadata["message"] = "Record updated!"
            if status != "success":
                report_metadata[
                    "message"] = "There was a problem updating the " + self.component + " record!"

        report_metadata["status"] = status
        self.context["action_feedback"] = report_metadata

        # process visualisation context,

        # set extra parameters which will be passed along to the visualize object
        self.broker_visuals.set_extra_params(
            dict(record_object=record_object,
                 data_source=self.param_dict.get("data_source", str())))

        # build dictionary of executable tasks/functions
        visualize_dict = dict(
            profiles_counts=self.broker_visuals.do_profiles_counts,
            created_component_json=self.broker_visuals.
            get_created_component_json,
            last_record=self.broker_visuals.get_last_record,
            get_profile_count=self.broker_visuals.get_profile_count)

        if self.visualize in visualize_dict:
            self.context = visualize_dict[self.visualize]()
        elif self.param_dict.get("target_id", str()):
            self.context = self.broker_visuals.do_table_data()
        else:
            self.context = self.broker_visuals.do_row_data()

        return self.context

    def do_delete(self):
        target_ids = [ObjectId(i) for i in self.param_dict.get("target_ids")]

        # if ever it was needed to re-implement 'soft' delete uncomment the following lines and
        # comment out the 'hard' delete query

        # soft delete
        # self.da_object.get_collection_handle().update_many(
        #     {"_id": {"$in": target_ids}}, {"$set": {"deleted": d_utils.get_deleted_flag()}}
        # )

        # hard delete
        self.da_object.get_collection_handle().remove(
            {'_id': {
                '$in': target_ids
            }})

        self.context = self.broker_visuals.do_table_data()
        return self.context

    def do_form(self):
        target_id = self.param_dict.get("target_id")
        component_dict = self.param_dict.get("component_dict", dict())
        message_dict = self.param_dict.get("message_dict", dict())

        kwargs = dict()
        kwargs["referenced_field"] = self.param_dict.get(
            "referenced_field", str())
        kwargs["referenced_type"] = self.param_dict.get(
            "referenced_type", str())

        self.context["form"] = htags.generate_copo_form(
            self.component, target_id, component_dict, message_dict,
            self.profile_id, **kwargs)
        self.context["form"]["visualize"] = self.param_dict.get("visualize")
        return self.context

    def do_form_and_component_records(self):
        # generates form, and in addition returns records of the form component, this could, for instance, be
        # used for cloning of a record

        kwargs = dict()
        kwargs["referenced_field"] = self.param_dict.get(
            "referenced_field", str())
        kwargs["referenced_type"] = self.param_dict.get(
            "referenced_type", str())

        self.context = self.do_form()
        self.context["component_records"] = htags.generate_component_records(
            self.component, self.profile_id, **kwargs)

        return self.context

    def do_doi(self):
        id_handle = self.param_dict.get("id_handle")
        id_type = self.param_dict.get("id_type")

        doi_resolve = DOI2Metadata(id_handle,
                                   id_type).get_resolve(self.component)

        self.set_extra_params(
            dict(target_id=str(),
                 component_dict=doi_resolve.get("component_dict", dict()),
                 message_dict=doi_resolve.get("message_dict", dict())))

        return self.do_form()

    def do_initiate_submission(self):
        kwarg = dict(datafile_ids=self.param_dict.get("datafile_ids", list()))
        self.context["submission_token"] = str(
            self.da_object.save_record(dict(), **kwarg).get("_id", str()))
        return self.context

    def do_user_email(self):
        user_id = self.param_dict.get("user_id", str())
        user_email = self.param_dict.get("user_email", str())
        user = User.objects.get(pk=int(user_id))
        user.email = user_email
        user.save()

        return self.context

    def do_component_record(self):
        self.context["component_record"] = self.da_object.get_record(
            self.param_dict.get("target_id"))

        return self.context

    def component_form_record(self):
        target_id = self.param_dict.get("target_id")
        component_dict = self.param_dict.get("component_dict", dict())
        message_dict = self.param_dict.get("message_dict", dict())

        kwargs = dict()
        kwargs["referenced_field"] = self.param_dict.get(
            "referenced_field", str())
        kwargs["referenced_type"] = self.param_dict.get(
            "referenced_type", str())
        kwargs["action_type"] = self.param_dict.get("action_type", str())

        form_value = htags.generate_copo_form(self.component, target_id,
                                              component_dict, message_dict,
                                              self.profile_id, **kwargs)

        self.context["component_record"] = form_value["form_value"]
        self.context["component_schema"] = form_value["form_schema"]
        return self.context

    def do_sanitise_submissions(self):

        records = self.da_object.get_all_records()

        for submission in records:
            if "bundle_meta" not in submission:
                bundle_meta = list()

                for file_id in submission.get("bundle", list()):
                    datafile = DataFile().get_record(file_id)
                    if datafile:
                        upload_status = False

                        if str(submission.get("complete",
                                              False)).lower() == 'true':
                            upload_status = True
                        bundle_meta.append(
                            dict(file_id=file_id,
                                 file_path=datafile.get(
                                     "file_location", str()),
                                 upload_status=upload_status))
                submission["bundle_meta"] = bundle_meta
                submission['target_id'] = str(submission.pop('_id'))
                self.da_object.save_record(dict(), **submission)

        self.context["sanitise_status"] = True

        return self.context

    def do_clone_description_bundle(self):
        """
        function creates a new description by cloning an existing (specified) bundle
        :return:
        """

        target_id = self.param_dict.get("target_id", str())
        bundle_name = self.param_dict.get("bundle_name", str())

        result = dict(status="success", message="")

        if Description().get_description_handle().find({
                "name": {
                    '$regex': "^" + bundle_name + "$",
                    "$options": 'i'
                }
        }).count() >= 1:
            result["status"] = "error"
            result["message"] = "Bundle name must be unique"

            self.context["result"] = result
            return self.context

        # retrieve clone target
        description = Description().GET(target_id)

        # new bundle being created
        try:
            bundle = Description().create_description(
                profile_id=self.profile_id,
                component=self.component,
                name=bundle_name,
                stages=description.get('stages', list()),
                attributes=description.get('attributes', dict()),
                meta=description.get('meta', dict()))

            result["data"] = dict(id=str(bundle["_id"]), name=bundle["name"])
        except Exception as e:
            message = "Couldn't create bundle: " + bundle_name + " " + str(e)
            result["status"] = "error"
            result["message"] = message

        self.context["result"] = result
        return self.context

    def create_rename_description_bundle(self):
        """
        function creates a new description bundle or renames an existing one
        :return:
        """

        target_id = self.param_dict.get("target_id", str())
        bundle_name = self.param_dict.get("bundle_name", str())

        result = dict(status="success", message="")

        if Description().get_description_handle().find({
                "name": {
                    '$regex': "^" + bundle_name + "$",
                    "$options": 'i'
                }
        }).count() >= 1:
            result["status"] = "error"
            result["message"] = "Bundle name must be unique"
        elif target_id:
            # updating existing bundle
            Description().edit_description(target_id, {"name": bundle_name})

            try:
                Description().edit_description(target_id,
                                               {"name": bundle_name})
            except Exception as e:
                message = "Couldn't update bundle: " + bundle_name + " " + str(
                    e)
                result["status"] = "error"
                result["message"] = message
        else:
            # new bundle being created
            try:
                bundle = Description().create_description(
                    profile_id=self.profile_id,
                    component=self.component,
                    name=bundle_name)
                result["data"] = dict(id=str(bundle["_id"]),
                                      name=bundle["name"])
            except Exception as e:
                message = "Couldn't create bundle: " + bundle_name + " " + str(
                    e)
                result["status"] = "error"
                result["message"] = message

        self.context["result"] = result
        return self.context