Ejemplo n.º 1
0
    def delete_by_action(cls, action, index_id, path):
        """
        Delete_by_action.

        :param action: action of the index.
        :param index_id: Identifier of the index.
        :param path: path of the index.
        :return: bool True: Delete success None: Delete failed
        """
        from weko_deposit.api import WekoDeposit
        if "move" == action:
            result = cls.delete(index_id, True)
            if result is not None:
                # move indexes all
                target = path.split('/')
                if len(target) >= 2:
                    target.pop(-2)
                    target = "/".join(target)
                else:
                    target = ""
                WekoDeposit.update_by_index_tree_id(path, target)
        else:
            result = cls.delete(index_id)
            if result is not None:
                # delete indexes all
                WekoDeposit.delete_by_index_tree_id(path)
        return result
Ejemplo n.º 2
0
def delete_records(index_tree_id):
    """Bulk delete records."""
    record_indexer = RecordIndexer()
    hits = get_tree_items(index_tree_id)
    for hit in hits:
        recid = hit.get('_id')
        record = Record.get_record(recid)
        if record is not None and record['path'] is not None:
            paths = record['path']
            if len(paths) > 0:
                # Remove the element which matches the index_tree_id
                removed_path = None
                for path in paths:
                    if path.endswith(str(index_tree_id)):
                        removed_path = path
                        paths.remove(path)
                        break

                # Do update the path on record
                record.update({'path': paths})
                record.commit()
                db.session.commit()

                # Indexing
                indexer = WekoIndexer()
                indexer.update_path(record, update_revision=False)

                if len(paths) == 0 and removed_path is not None:
                    from weko_deposit.api import WekoDeposit
                    WekoDeposit.delete_by_index_tree_id(removed_path)
                    Record.get_record(recid).delete()  # flag as deleted
                    db.session.commit()  # terminate the transaction
Ejemplo n.º 3
0
Archivo: views.py Proyecto: mhaya/weko
def cancel_action(activity_id='0', action_id=0):
    """Next action."""
    post_json = request.get_json()
    work_activity = WorkActivity()

    activity = dict(activity_id=activity_id,
                    action_id=action_id,
                    action_version=post_json.get('action_version'),
                    action_status=ActionStatusPolicy.ACTION_CANCELED,
                    commond=post_json.get('commond'))

    # clear deposit
    activity_detail = work_activity.get_activity_detail(activity_id)
    if activity_detail is not None:
        cancel_item_id = activity_detail.item_id
        if cancel_item_id is None:
            pid_value = post_json.get('pid_value')
            if pid_value is not None:
                pid = PersistentIdentifier.get('recid', pid_value)
                cancel_item_id = pid.object_uuid
        if cancel_item_id is not None:
            cancel_record = WekoDeposit.get_record(cancel_item_id)
            if cancel_record is not None:
                cancel_deposit = WekoDeposit(cancel_record,
                                             cancel_record.model)
                cancel_deposit.clear()
                # Remove draft child
                cancel_pid = PersistentIdentifier.get_by_object(
                    pid_type='recid',
                    object_type='rec',
                    object_uuid=cancel_item_id)
                cancel_pv = PIDVersioning(child=cancel_pid)
                if cancel_pv.exists:
                    previous_pid = cancel_pv.previous
                    if previous_pid is not None:
                        activity.update(dict(item_id=previous_pid.object_uuid))
                    cancel_pv.remove_child(cancel_pid)

    work_activity.upt_activity_action_status(
        activity_id=activity_id,
        action_id=action_id,
        action_status=ActionStatusPolicy.ACTION_CANCELED)

    rtn = work_activity.quit_activity(activity)

    if rtn is None:
        work_activity.upt_activity_action_status(
            activity_id=activity_id,
            action_id=action_id,
            action_status=ActionStatusPolicy.ACTION_DOING)
        return jsonify(code=-1, msg=_('Error! Cannot process quit activity!'))

    return jsonify(code=0,
                   msg=_('success'),
                   data={
                       'redirect':
                       url_for('weko_workflow.display_activity',
                               activity_id=activity_id)
                   })
Ejemplo n.º 4
0
def register_item_metadata(item):
    """Upload file content.

    :argument
        list_record    -- {list} list item import.
        file_path      -- {str} file path.
    """
    item_id = str(item.get('id'))
    try:
        pid = PersistentIdentifier.query.filter_by(
            pid_type='recid',
            pid_value=item_id
        ).first()

        record = WekoDeposit.get_record(pid.object_uuid)

        _deposit_data = record.dumps().get("_deposit")
        deposit = WekoDeposit(record, record.model)
        new_data = dict(
            **item.get('metadata'),
            **_deposit_data,
            **{
                '$schema': item.get('$schema'),
                'title': handle_get_title(item.get('Title')),
            }
        )
        item_status = {
            'index': new_data['path'],
            'actions': 'publish',
        }
        if not new_data.get('pid'):
            new_data = dict(**new_data, **{
                'pid': {
                    'revision_id': 0,
                    'type': 'recid',
                    'value': item_id
                }
            })
        deposit.update(item_status, new_data)
        deposit.commit()
        deposit.publish()
        with current_app.test_request_context():
            first_ver = deposit.newversion(pid)
            if first_ver:
                first_ver.publish()
        db.session.commit()

    except Exception as ex:
        db.session.rollback()
        current_app.logger.error('item id: %s update error.' % item_id)
        current_app.logger.error(ex)
        return {
            'success': False,
            'error': str(ex)
        }
    return {
        'success': True
    }
Ejemplo n.º 5
0
def process_item(record, resync, counter):
    """Process item."""
    event_counter('processed_items', counter)
    event = ItemEvents.INIT
    xml = etree.tostring(record, encoding='utf-8').decode()
    mapper = JPCOARMapper(xml)

    resyncid = PersistentIdentifier.query.filter_by(
        pid_type='syncid',
        pid_value=gen_resync_pid_value(resync, mapper.identifier())).first()
    if resyncid:
        r = RecordMetadata.query.filter_by(id=resyncid.object_uuid).first()
        recid = PersistentIdentifier.query.filter_by(
            pid_type='recid', object_uuid=resyncid.object_uuid).first()
        recid.status = PIDStatus.REGISTERED
        pubdate = dateutil.parser.parse(
            r.json['pubdate']['attribute_value']).date()
        dep = WekoDeposit(r.json, r)
        indexes = dep['path'].copy()
        event = ItemEvents.UPDATE
    elif mapper.is_deleted():
        return
    else:
        dep = WekoDeposit.create({})
        PersistentIdentifier.create(pid_type='syncid',
                                    pid_value=gen_resync_pid_value(
                                        resync, mapper.identifier()),
                                    status=PIDStatus.REGISTERED,
                                    object_type=dep.pid.object_type,
                                    object_uuid=dep.pid.object_uuid)
        indexes = []
        event = ItemEvents.CREATE
    indexes.append(str(resync.index_id)) if str(
        resync.index_id) not in indexes else None

    if mapper.is_deleted():
        soft_delete(recid.pid_value)
        event = ItemEvents.DELETE
    else:
        json = mapper.map()
        json['$schema'] = '/items/jsonschema/' + str(mapper.itemtype.id)
        dep['_deposit']['status'] = 'draft'
        dep.update({'actions': 'publish', 'index': indexes}, json)
        dep.commit()
        dep.publish()
        # add item versioning
        pid = PersistentIdentifier.query.filter_by(
            pid_type='recid', pid_value=dep.pid.pid_value).first()
        with current_app.test_request_context() as ctx:
            first_ver = dep.newversion(pid)
            first_ver.publish()
    db.session.commit()
    if event == ItemEvents.CREATE:
        event_counter('created_items', counter)
    elif event == ItemEvents.UPDATE:
        event_counter('updated_items', counter)
    elif event == ItemEvents.DELETE:
        event_counter('deleted_items', counter)
Ejemplo n.º 6
0
def serialize_related_identifiers(pid):
    """Serialize PID Versioning relations as related_identifiers metadata."""
    pv = PIDVersioning(child=pid)
    related_identifiers = []
    if pv.exists:

        rec = WekoDeposit.get_record(pid.get_assigned_object())
        # External DOI records don't have Concept DOI
        if 'conceptdoi' in rec:
            ri = {
                'scheme': 'doi',
                'relation': 'isVersionOf',
                'identifier': rec['conceptdoi']
            }
            related_identifiers.append(ri)

        # TODO: We do not serialize previous/next versions to
        # related identifiers because of the semantic-versioning cases
        # (e.g. GitHub releases of minor versions)
        #
        # children = pv.children.all()
        # idx = children.index(pid)
        # left = children[:idx]
        # right = children[idx + 1:]
        # for p in left:
        #     rec = ZenodoRecord.get_record(p.get_assigned_object())
        #     ri = {
        #         'scheme': 'doi',
        #         'relation': 'isNewVersionOf',
        #         'identifier': rec['doi']
        #     }
        #     related_identifiers.append(ri)
        # for p in right:
        #     rec = ZenodoRecord.get_record(p.get_assigned_object())
        #     ri = {
        #         'scheme': 'doi',
        #         'relation': 'isPreviousVersionOf',
        #         'identifier': rec['doi']
        #     }
        #     related_identifiers.append(ri)
    pv = PIDVersioning(parent=pid)
    if pv.exists:
        for p in pv.children:
            rec = WekoDeposit.get_record(p.get_assigned_object())
            if 'doi' in rec:
                relation_info = {
                    'scheme': 'doi',
                    'relation': 'hasVersion',
                    'identifier': rec['doi']
                }
                related_identifiers.append(relation_info)
    return related_identifiers
Ejemplo n.º 7
0
def restore(recid):
    """Restore item."""
    try:
        pid = PersistentIdentifier.query.filter_by(pid_type='recid',
                                                   pid_value=recid).first()
        if not pid:
            pid = PersistentIdentifier.query.filter_by(
                pid_type='recid', object_uuid=recid).first()
        if pid.status != PIDStatus.DELETED:
            return
        pid.status = PIDStatus.REGISTERED
        depid = PersistentIdentifier.query.filter_by(
            pid_type='depid', object_uuid=pid.object_uuid).first()
        if depid:
            depid.status = PIDStatus.REGISTERED
            rec = RecordMetadata.query.filter_by(id=pid.object_uuid).first()
            dep = WekoDeposit(rec.json, rec)
            dep.indexer.update_path(dep, update_revision=False)
        pids = PersistentIdentifier.query.filter_by(
            object_uuid=pid.object_uuid)
        for p in pids:
            p.status = PIDStatus.REGISTERED
        db.session.commit()
    except Exception as ex:
        db.session.rollback()
        raise ex
Ejemplo n.º 8
0
def create_deposit(item_id):
    """Create deposit.

    :argument
        item           -- {dict} item import.
        item_exist     -- {dict} item in system.

    """
    try:
        if item_id is not None:
            dep = WekoDeposit.create({}, recid=int(item_id))
            db.session.commit()
        else:
            dep = WekoDeposit.create({})
            db.session.commit()
        return dep['recid']
    except Exception:
        db.session.rollback()
Ejemplo n.º 9
0
 def delete_by_action(cls, action, index_id, path):
     from weko_deposit.api import WekoDeposit
     if "move" == action:
         result = cls.delete(index_id, True)
         if result is not None:
             # move indexes all
             target = path.split('/')
             if len(target) >= 2:
                 target.pop(-2)
                 target = "/".join(target)
             else:
                 target = ""
             WekoDeposit.update_by_index_tree_id(path, target)
     else:
         result = cls.delete(index_id)
         if result is not None:
             # delete indexes all
             WekoDeposit.delete_by_index_tree_id(path)
     return result
Ejemplo n.º 10
0
def display_activity(activity_id=0):
    """Display activity."""
    activity = WorkActivity()
    activity_detail = activity.get_activity_detail(activity_id)
    item = None
    if activity_detail and activity_detail.item_id:
        try:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        except NoResultFound as ex:
            current_app.logger.exception(str(ex))
            item = None

    steps = activity.get_activity_steps(activity_id)
    history = WorkActivityHistory()
    histories = history.get_activity_history_list(activity_id)
    workflow = WorkFlow()
    workflow_detail = workflow.get_workflow_by_id(activity_detail.workflow_id)

    if activity_detail.activity_status == \
        ActivityStatusPolicy.ACTIVITY_FINALLY \
        or activity_detail.activity_status == \
            ActivityStatusPolicy.ACTIVITY_CANCEL:
        activity_detail.activity_status_str = _('End')
    else:
        activity_detail.activity_status_str = \
            request.args.get('status', 'ToDo')
    cur_action = activity_detail.action
    action_endpoint = cur_action.action_endpoint
    action_id = cur_action.id
    temporary_comment = activity.get_activity_action_comment(
        activity_id=activity_id, action_id=action_id)

    # display_activity of Identifier grant
    identifier_setting = None
    if action_endpoint == 'identifier_grant' and item:
        community_id = request.args.get('community', None)
        if not community_id:
            community_id = 'Root Index'
        identifier_setting = get_identifier_setting(community_id)

        # valid date pidstore_identifier data
        if identifier_setting:
            text_empty = '<Empty>'
            if not identifier_setting.jalc_doi:
                identifier_setting.jalc_doi = text_empty
            if not identifier_setting.jalc_crossref_doi:
                identifier_setting.jalc_crossref_doi = text_empty
            if not identifier_setting.jalc_datacite_doi:
                identifier_setting.jalc_datacite_doi = text_empty
            if not identifier_setting.ndl_jalc_doi:
                identifier_setting.ndl_jalc_doi = text_empty

    temporary_identifier_select = 0
    temporary_identifier_inputs = []
    last_identifier_setting = activity.get_action_identifier_grant(
        activity_id=activity_id, action_id=action_id)
    if last_identifier_setting:
        temporary_identifier_select = last_identifier_setting.get(
            'action_identifier_select')
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_jalc_doi'))
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_jalc_cr_doi'))
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_jalc_dc_doi'))
        temporary_identifier_inputs.append(
            last_identifier_setting.get('action_identifier_ndl_jalc_doi'))

    temporary_journal = activity.get_action_journal(activity_id=activity_id,
                                                    action_id=action_id)
    if temporary_journal:
        temporary_journal = temporary_journal.action_journal

    cur_step = action_endpoint
    step_item_login_url = None
    approval_record = []
    pid = None
    record = {}
    need_file = False
    need_billing_file = False
    json_schema = ''
    schema_form = ''
    item_save_uri = ''
    files = []
    endpoints = {}
    links = None
    need_thumbnail = False
    files_thumbnail = []
    allow_multi_thumbnail = False
    show_autofill_metadata = True
    is_hidden_pubdate_value = False
    item_type_name = get_item_type_name(workflow_detail.itemtype_id)

    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        activity_session = dict(activity_id=activity_id,
                                action_id=activity_detail.action_id,
                                action_version=cur_action.action_version,
                                action_status=ActionStatusPolicy.ACTION_DOING,
                                commond='')
        show_autofill_metadata = is_show_autofill_metadata(item_type_name)
        is_hidden_pubdate_value = is_hidden_pubdate(item_type_name)
        session['activity_info'] = activity_session
        # get item edit page info.
        step_item_login_url, need_file, need_billing_file, \
            record, json_schema, schema_form,\
            item_save_uri, files, endpoints, need_thumbnail, files_thumbnail, \
            allow_multi_thumbnail \
            = item_login(item_type_id=workflow_detail.itemtype_id)
        if item:
            # Remove the unused local variable
            # _pid_identifier = PersistentIdentifier.get_by_object(
            #     pid_type='depid', object_type='rec', object_uuid=item.id)
            record = item

        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if sessionstore.redis.exists(
            'updated_json_schema_{}'.format(activity_id)) \
            and sessionstore.get(
                'updated_json_schema_{}'.format(activity_id)):
            json_schema = (json_schema + "/{}").format(activity_id)

    # if 'approval' == action_endpoint:
    if item:
        # get record data for the first time access to editing item screen
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        pid, approval_record = resolver.resolve(pid_identifier.pid_value)

        files = to_files_js(approval_record)

        # get files data after click Save btn
        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if sessionstore.redis.exists('activity_item_' + str(activity_id)):
            item_str = sessionstore.get('activity_item_' + str(activity_id))
            item_json = json.loads(item_str.decode('utf-8'))
            if 'files' in item_json:
                files = item_json.get('files')
        if not files:
            deposit = WekoDeposit.get_record(item.id)
            if deposit:
                files = to_files_js(deposit)

        if files and not files_thumbnail:
            files_thumbnail = [
                i for i in files
                if 'is_thumbnail' in i.keys() and i['is_thumbnail']
            ]

        from weko_deposit.links import base_factory
        links = base_factory(pid)

    res_check = check_authority_action(str(activity_id), str(action_id))

    getargs = request.args
    ctx = {'community': None}
    community_id = ""
    if 'community' in getargs:
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        ctx = {'community': comm}
        community_id = comm.id
    # be use for index tree and comment page.
    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        session['itemlogin_id'] = activity_id
        session['itemlogin_activity'] = activity_detail
        session['itemlogin_item'] = item
        session['itemlogin_steps'] = steps
        session['itemlogin_action_id'] = action_id
        session['itemlogin_cur_step'] = cur_step
        session['itemlogin_record'] = approval_record
        session['itemlogin_histories'] = histories
        session['itemlogin_res_check'] = res_check
        session['itemlogin_pid'] = pid
        session['itemlogin_community_id'] = community_id

    from weko_theme.utils import get_design_layout
    # Get the design for widget rendering
    page, render_widgets = get_design_layout(
        community_id or current_app.config['WEKO_THEME_DEFAULT_COMMUNITY'])
    list_license = get_list_licence()

    if item and item.get('pid'):
        pid_without_ver = item['pid']['value'].split('.')[0]
        item_link = ItemLink.get_item_link_info(pid_without_ver)
        ctx['item_link'] = item_link

    return render_template(
        'weko_workflow/activity_detail.html',
        page=page,
        render_widgets=render_widgets,
        activity=activity_detail,
        item=item,
        steps=steps,
        action_id=action_id,
        cur_step=cur_step,
        temporary_comment=temporary_comment,
        temporary_journal=temporary_journal,
        temporary_idf_grant=temporary_identifier_select,
        temporary_idf_grant_suffix=temporary_identifier_inputs,
        idf_grant_data=identifier_setting,
        idf_grant_input=IDENTIFIER_GRANT_LIST,
        idf_grant_method=IDENTIFIER_GRANT_SUFFIX_METHOD,
        record=approval_record,
        records=record,
        step_item_login_url=step_item_login_url,
        need_file=need_file,
        need_billing_file=need_billing_file,
        jsonschema=json_schema,
        schemaform=schema_form,
        id=workflow_detail.itemtype_id,
        item_save_uri=item_save_uri,
        files=files,
        endpoints=endpoints,
        error_type='item_login_error',
        links=links,
        histories=histories,
        res_check=res_check,
        pid=pid,
        community_id=community_id,
        need_thumbnail=need_thumbnail,
        files_thumbnail=files_thumbnail,
        allow_multi_thumbnail=allow_multi_thumbnail,
        enable_feedback_maillist=current_app.
        config['WEKO_WORKFLOW_ENABLE_FEEDBACK_MAIL'],
        enable_contributor=current_app.
        config['WEKO_WORKFLOW_ENABLE_CONTRIBUTOR'],
        show_automatic_metadata_input=show_autofill_metadata,
        is_hidden_pubdate=is_hidden_pubdate_value,
        list_license=list_license,
        **ctx)
Ejemplo n.º 11
0
    def move(cls, index_id, **data):
        """Move."""
        def _update_index(parent=None):
            with db.session.begin_nested():
                index = Index.query.filter_by(id=index_id).one()
                index.position = position_max
                index.owner_user_id = user_id
                flag_modified(index, 'position')
                flag_modified(index, 'owner_user_id')
                if parent:
                    index.parent = parent
                    flag_modified(index, 'parent')
                db.session.merge(index)
            db.session.commit()

        is_ok = True
        user_id = current_user.get_id()
        position_max = 0

        if isinstance(data, dict):
            pre_parent = data.get('pre_parent')
            parent = data.get('parent')
            if not pre_parent or not parent:
                return False

            try:
                # move index on the same hierarchy
                if str(pre_parent) == str(parent):
                    if int(pre_parent) == 0:
                        parent_info = cls.get_root_index_count()
                    else:
                        parent_info = cls.get_index(pre_parent,
                                                    with_count=True)
                    position = int(data.get('position'))
                    pmax = parent_info.position_max \
                        if parent_info.position_max is not None else 0

                    if position >= pmax:
                        position_max = pmax + 1
                        try:
                            _update_index()
                        except IntegrityError as ie:
                            if 'uix_position' in ''.join(ie.args):
                                try:
                                    position_max += 1
                                    _update_index()
                                except SQLAlchemyError as ex:
                                    is_ok = False
                                    current_app.logger.debug(ex)
                            else:
                                is_ok = False
                                current_app.logger.debug(ie)
                        except Exception as ex:
                            is_ok = False
                            current_app.logger.debug(ex)
                        finally:
                            if not is_ok:
                                db.session.rollback()
                    else:
                        position_max = position
                        try:
                            with db.session.begin_nested():
                                nlst = Index.query.filter_by(parent=parent). \
                                    order_by(
                                    Index.position).with_for_update().all()
                                n = t = -1

                                for i in range(len(nlst)):
                                    db.session.delete(nlst[i])
                                    if nlst[i].id == index_id:
                                        n = i
                                    if position == nlst[i].position:
                                        t = i
                                # if the index has been deleted.
                                if n < 0:
                                    raise Exception()

                                pre_index = nlst.pop(n)
                                if n < t:
                                    t -= 1
                                if t < 0:
                                    t = position - 1

                                nlst.insert(t + 1, pre_index)
                                db.session.flush()
                                for i in range(len(nlst)):
                                    nid = Index()
                                    for k in dict(nid).keys():
                                        setattr(nid, k, getattr(nlst[i], k))
                                    nid.position = i
                                    nid.owner_user_id = user_id
                                    db.session.add(nid)
                            db.session.commit()
                        except Exception as ex:
                            is_ok = False
                            current_app.logger.debug(ex)
                        finally:
                            if not is_ok:
                                db.session.rollback()
                else:
                    slf_path = cls.get_self_path(index_id)
                    if int(parent) == 0:
                        parent_info = cls.get_root_index_count()
                    else:
                        parent_info = cls.get_index(parent, with_count=True)
                    position_max = parent_info.position_max + 1 \
                        if parent_info.position_max is not None else 0
                    try:
                        _update_index(parent)
                    except IntegrityError as ie:
                        if 'uix_position' in ''.join(ie.args):
                            try:
                                if int(parent) == 0:
                                    parent_info = cls.get_root_index_count()
                                else:
                                    parent_info = \
                                        cls.get_index(parent, with_count=True)
                                position_max = parent_info.position_max + 1 \
                                    if parent_info.position_max is not None \
                                    else 0
                                _update_index()
                            except SQLAlchemyError as ex:
                                is_ok = False
                                current_app.logger.debug(ex)
                        else:
                            is_ok = False
                            current_app.logger.debug(ie)
                    except Exception as ex:
                        is_ok = False
                        current_app.logger.debug(ex)
                    finally:
                        if not is_ok:
                            db.session.rollback()

                    # move items
                    target = cls.get_self_path(index_id)
                    from weko_deposit.api import WekoDeposit
                    WekoDeposit.update_by_index_tree_id(
                        slf_path.path, target.path)
            except Exception as ex:
                current_app.logger.debug(ex)
                is_ok = False
        return is_ok
Ejemplo n.º 12
0
Archivo: views.py Proyecto: mhaya/weko
def next_action(activity_id='0', action_id=0):
    """Next action."""
    post_json = request.get_json()
    activity = dict(activity_id=activity_id,
                    action_id=action_id,
                    action_version=post_json.get('action_version'),
                    action_status=ActionStatusPolicy.ACTION_DONE,
                    commond=post_json.get('commond'))

    work_activity = WorkActivity()

    history = WorkActivityHistory()
    action = Action().get_action_detail(action_id)
    action_endpoint = action.action_endpoint

    if (1 == post_json.get('temporary_save')
            and action_endpoint != 'identifier_grant'):
        if 'journal' in post_json:
            work_activity.create_or_update_action_journal(
                activity_id=activity_id,
                action_id=action_id,
                journal=post_json.get('journal'))
        else:
            work_activity.upt_activity_action_comment(
                activity_id=activity_id,
                action_id=action_id,
                comment=post_json.get('commond'))
        return jsonify(code=0, msg=_('success'))
    elif post_json.get('journal'):
        work_activity.create_or_update_action_journal(
            activity_id=activity_id,
            action_id=action_id,
            journal=post_json.get('journal'))

    if 'begin_action' == action_endpoint:
        return jsonify(code=0, msg=_('success'))

    if 'end_action' == action_endpoint:
        work_activity.end_activity(activity)
        return jsonify(code=0, msg=_('success'))

    if 'approval' == action_endpoint:
        activity_obj = WorkActivity()
        activity_detail = activity_obj.get_activity_detail(activity_id)
        item = None
        if activity_detail is not None and activity_detail.item_id is not None:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
            pid_identifier = PersistentIdentifier.get_by_object(
                pid_type='depid', object_type='rec', object_uuid=item.id)
            record_class = import_string('weko_deposit.api:WekoRecord')
            resolver = Resolver(pid_type='recid',
                                object_type='rec',
                                getter=record_class.get_record)
            pid, approval_record = resolver.resolve(pid_identifier.pid_value)

            # TODO: Make private as default.
            # UpdateItem.publish(pid, approval_record)

    if 'item_link' == action_endpoint:
        relation_data = post_json.get('link_data'),
        activity_obj = WorkActivity()
        activity_detail = activity_obj.get_activity_detail(activity_id)
        item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        pid, item_record = resolver.resolve(pid_identifier.pid_value)
        updated_item = UpdateItem()
        updated_item.set_item_relation(relation_data, item_record)

    # save pidstore_identifier to ItemsMetadata
    idf_grant = post_json.get('identifier_grant')
    if 'identifier_grant' == action_endpoint and idf_grant is not None:
        idf_grant_jalc_doi_manual = post_json.get(
            'identifier_grant_jalc_doi_suffix')
        idf_grant_jalc_cr_doi_manual = post_json.get(
            'identifier_grant_jalc_cr_doi_suffix')
        idf_grant_jalc_dc_doi_manual = post_json.get(
            'identifier_grant_jalc_dc_doi_suffix')

        # If is action identifier_grant, then save to to database
        identifier_grant = {
            'action_identifier_select': idf_grant,
            'action_identifier_jalc_doi': idf_grant_jalc_doi_manual,
            'action_identifier_jalc_cr_doi': idf_grant_jalc_cr_doi_manual,
            'action_identifier_jalc_dc_doi': idf_grant_jalc_dc_doi_manual
        }

        work_activity.create_or_update_action_identifier(
            activity_id=activity_id,
            action_id=action_id,
            identifier=identifier_grant)
        if post_json.get('temporary_save') != 1:
            pidstore_identifier_mapping(post_json, int(idf_grant), activity_id)
        else:
            return jsonify(code=0, msg=_('success'))

    rtn = history.create_activity_history(activity)
    if rtn is None:
        return jsonify(code=-1, msg=_('error'))
    # next action
    activity_detail = work_activity.get_activity_detail(activity_id)
    work_activity.upt_activity_action_status(
        activity_id=activity_id,
        action_id=action_id,
        action_status=ActionStatusPolicy.ACTION_DONE)
    work_activity.upt_activity_action_comment(activity_id=activity_id,
                                              action_id=action_id,
                                              comment='')
    flow = Flow()
    next_flow_action = flow.get_next_flow_action(
        activity_detail.flow_define.flow_id, action_id)
    if next_flow_action and len(next_flow_action) > 0:
        next_action_endpoint = next_flow_action[0].action.action_endpoint
        if 'end_action' == next_action_endpoint:
            if activity_detail is not None and \
                    activity_detail.item_id is not None:
                record = WekoDeposit.get_record(activity_detail.item_id)
                if record is not None:
                    deposit = WekoDeposit(record, record.model)
                    deposit.publish()
                    # For current item: Make status Public as default
                    updated_item = UpdateItem()
                    updated_item.publish(record)
                    # For previous item: Update status to Private
                    current_pid = PersistentIdentifier.get_by_object(
                        pid_type='recid',
                        object_type='rec',
                        object_uuid=activity_detail.item_id)
                    current_pv = PIDVersioning(child=current_pid)
                    if current_pv.exists and current_pv.previous is not None:
                        prev_record = WekoDeposit.get_record(
                            current_pv.previous.object_uuid)
                        if prev_record is not None:
                            updated_item.update_status(prev_record)
            activity.update(
                action_id=next_flow_action[0].action_id,
                action_version=next_flow_action[0].action_version,
            )
            work_activity.end_activity(activity)
        else:
            next_action_id = next_flow_action[0].action_id
            work_activity.upt_activity_action(
                activity_id=activity_id,
                action_id=next_action_id,
                action_status=ActionStatusPolicy.ACTION_DOING)
    return jsonify(code=0, msg=_('success'))
Ejemplo n.º 13
0
Archivo: views.py Proyecto: mhaya/weko
def prepare_edit_item():
    """Prepare_edit_item.

    Host the api which provide 2 service:
        Create new activity for editing flow
        Check permission: check if user is owner/admin/shared user
    request:
        header: Content type must be json
        data:
            pid_value: pid_value
    return: The result json:
        code: status code,
        msg: meassage result,
        data: url redirect
    """
    if request.headers['Content-Type'] != 'application/json':
        """Check header of request"""
        return jsonify(code=-1, msg=_('Header Error'))
    post_activity = request.get_json()
    pid_value = post_activity.get('pid_value')
    if pid_value:
        try:
            record = WekoRecord.get_record_by_pid(pid_value)
            owner = str(record.get('owner'))
            shared_id = str(record.get('weko_shared_id'))
            user_id = str(get_current_user())
            is_admin = get_user_roles()
            activity = WorkActivity()
            pid_object = PersistentIdentifier.get('recid', pid_value)

            # check item is being editied
            item_id = pid_object.object_uuid
            workflow_action_stt = \
                activity.get_workflow_activity_status_by_item_id(
                    item_id=item_id)
            # show error when has stt is Begin or Doing
            if workflow_action_stt is not None and \
                (workflow_action_stt == ActionStatusPolicy.ACTION_BEGIN
                 or workflow_action_stt == ActionStatusPolicy.ACTION_DOING):
                return jsonify(code=-13,
                               msg=_('The workflow is being edited. '))

            if user_id != owner and not is_admin[0] and user_id != shared_id:
                return jsonify(code=-1,
                               msg=_('You are not allowed to edit this item.'))
            lists = ItemTypes.get_latest()
            if not lists:
                return jsonify(code=-1,
                               msg=_('You do not even have an itemtype.'))
            item_type_id = record.get('item_type_id')
            item_type = ItemTypes.get_by_id(item_type_id)
            if item_type is None:
                return jsonify(code=-1, msg=_('This itemtype not found.'))

            upt_current_activity = activity.upt_activity_detail(
                item_id=pid_object.object_uuid)

            if upt_current_activity is not None:
                post_activity['workflow_id'] = upt_current_activity.workflow_id
                post_activity['flow_id'] = upt_current_activity.flow_id
                post_activity['itemtype_id'] = item_type_id
                getargs = request.args
                community = getargs.get('community', None)

                # Create a new version of a record.
                record = WekoDeposit.get_record(item_id)
                if record is None:
                    return jsonify(code=-1, msg=_('Record does not exist.'))
                deposit = WekoDeposit(record, record.model)
                new_record = deposit.newversion(pid_object)
                if new_record is None:
                    return jsonify(code=-1, msg=_('An error has occurred.'))
                rtn = activity.init_activity(post_activity, community,
                                             new_record.model.id)
                if rtn:
                    # GOTO: TEMPORARY EDIT MODE FOR IDENTIFIER
                    identifier_actionid = get_actionid('identifier_grant')
                    identifier = activity.get_action_identifier_grant(
                        upt_current_activity.activity_id, identifier_actionid)
                    if identifier:
                        if identifier.get('action_identifier_select') > \
                                IDENTIFIER_GRANT_DOI:
                            identifier['action_identifier_select'] = \
                                IDENTIFIER_GRANT_CAN_WITHDRAW
                        elif identifier.get('action_identifier_select') == \
                                IDENTIFIER_GRANT_IS_WITHDRAWING:
                            identifier['action_identifier_select'] = \
                                IDENTIFIER_GRANT_WITHDRAWN
                        activity.create_or_update_action_identifier(
                            rtn.activity_id, identifier_actionid, identifier)

                    if community:
                        comm = GetCommunity.get_community_by_id(community)
                        url_redirect = url_for(
                            'weko_workflow.display_activity',
                            activity_id=rtn.activity_id,
                            community=comm.id)
                    else:
                        url_redirect = url_for(
                            'weko_workflow.display_activity',
                            activity_id=rtn.activity_id)
                    return jsonify(code=0,
                                   msg='success',
                                   data={'redirect': url_redirect})
        except Exception as e:
            current_app.logger.error('Unexpected error: ', str(e))
    return jsonify(code=-1, msg=_('An error has occurred.'))
Ejemplo n.º 14
0
def process_item(record, harvesting, counter):
    """Process item."""
    event_counter('processed_items', counter)
    event = ItemEvents.INIT
    xml = etree.tostring(record, encoding='utf-8').decode()
    if harvesting.metadata_prefix == 'oai_dc':
        mapper = DCMapper(xml)
    elif harvesting.metadata_prefix == 'jpcoar' or \
            harvesting.metadata_prefix == 'jpcoar_1.0':
        mapper = JPCOARMapper(xml)
    elif harvesting.metadata_prefix == 'oai_ddi25' or \
            harvesting.metadata_prefix == 'ddi':
        mapper = DDIMapper(xml)
    else:
        return
    hvstid = PersistentIdentifier.query.filter_by(
        pid_type='hvstid', pid_value=mapper.identifier()).first()
    if hvstid:
        r = RecordMetadata.query.filter_by(id=hvstid.object_uuid).first()
        recid = PersistentIdentifier.query.filter_by(
            pid_type='recid', object_uuid=hvstid.object_uuid).first()
        recid.status = PIDStatus.REGISTERED
        pubdate = dateutil.parser.parse(
            r.json['pubdate']['attribute_value']).date()
        dep = WekoDeposit(r.json, r)
        indexes = dep['path'].copy()
        event = ItemEvents.UPDATE
    elif mapper.is_deleted():
        return
    else:
        dep = WekoDeposit.create({})
        PersistentIdentifier.create(pid_type='hvstid',
                                    pid_value=mapper.identifier(),
                                    object_type=dep.pid.object_type,
                                    object_uuid=dep.pid.object_uuid)
        indexes = []
        event = ItemEvents.CREATE
    if int(harvesting.auto_distribution):
        for i in map_indexes(mapper.specs(), harvesting.index_id):
            indexes.append(str(i)) if i not in indexes else None
    else:
        indexes.append(str(harvesting.index_id)) if str(
            harvesting.index_id) not in indexes else None

    if hvstid and pubdate >= mapper.datestamp() and \
       indexes == dep['path'] and harvesting.update_style == '1':
        return

    if mapper.is_deleted():
        soft_delete(recid.pid_value)
        event = ItemEvents.DELETE
    else:
        json = mapper.map()
        json['$schema'] = '/items/jsonschema/' + str(mapper.itemtype.id)
        dep['_deposit']['status'] = 'draft'
        dep.update({'actions': 'publish', 'index': indexes}, json)
        dep.commit()
        dep.publish()
        # add item versioning
        pid = PersistentIdentifier.query.filter_by(
            pid_type='recid', pid_value=dep.pid.pid_value).first()

        idt_list = mapper.identifiers
        from weko_workflow.utils import IdentifierHandle

        idt = IdentifierHandle(pid.object_uuid)
        for it in idt_list:
            if not it.get('type'):
                continue
            pid_type = it['type'].lower()
            pid_obj = idt.get_pidstore(pid_type)
            if not pid_obj:
                idt.register_pidstore(pid_type, it['identifier'])

        with current_app.test_request_context() as ctx:
            first_ver = dep.newversion(pid)
            first_ver.publish()

    harvesting.item_processed = harvesting.item_processed + 1
    db.session.commit()

    if event == ItemEvents.CREATE:
        event_counter('created_items', counter)
    elif event == ItemEvents.UPDATE:
        event_counter('updated_items', counter)
    elif event == ItemEvents.DELETE:
        event_counter('deleted_items', counter)
Ejemplo n.º 15
0
def next_action(activity_id='0', action_id=0):
    """Next action."""
    work_activity = WorkActivity()
    history = WorkActivityHistory()

    post_json = request.get_json()
    activity = dict(activity_id=activity_id,
                    action_id=action_id,
                    action_version=post_json.get('action_version'),
                    action_status=ActionStatusPolicy.ACTION_DONE,
                    commond=post_json.get('commond'))

    action = Action().get_action_detail(action_id)
    action_endpoint = action.action_endpoint

    if action_endpoint == 'begin_action':
        return jsonify(code=0, msg=_('success'))

    if action_endpoint == 'end_action':
        work_activity.end_activity(activity)
        return jsonify(code=0, msg=_('success'))

    if action_endpoint == 'item_login':
        register_hdl(activity_id)

    activity_detail = work_activity.get_activity_detail(activity_id)
    item_id = None
    recid = None
    record = None
    pid_without_ver = None
    if activity_detail and activity_detail.item_id:
        item_id = activity_detail.item_id
        current_pid = PersistentIdentifier.get_by_object(pid_type='recid',
                                                         object_type='rec',
                                                         object_uuid=item_id)
        recid = get_record_identifier(current_pid.pid_value)
        record = WekoDeposit.get_record(item_id)
        if record:
            pid_without_ver = get_record_without_version(current_pid)
            deposit = WekoDeposit(record, record.model)

    if post_json.get('temporary_save') == 1 \
            and action_endpoint != 'identifier_grant':
        if 'journal' in post_json:
            work_activity.create_or_update_action_journal(
                activity_id=activity_id,
                action_id=action_id,
                journal=post_json.get('journal'))
        else:
            work_activity.upt_activity_action_comment(
                activity_id=activity_id,
                action_id=action_id,
                comment=post_json.get('commond'))
        return jsonify(code=0, msg=_('success'))
    elif post_json.get('journal'):
        work_activity.create_or_update_action_journal(
            activity_id=activity_id,
            action_id=action_id,
            journal=post_json.get('journal'))

    if action_endpoint == 'approval' and item_id:
        item = ItemsMetadata.get_record(id_=item_id)
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        _pid, _approval_record = resolver.resolve(pid_identifier.pid_value)

        action_feedbackmail = work_activity.get_action_feedbackmail(
            activity_id=activity_id, action_id=ITEM_REGISTRATION_ACTION_ID)
        if action_feedbackmail:
            FeedbackMailList.update(
                item_id=item_id,
                feedback_maillist=action_feedbackmail.feedback_maillist)
            if not recid and pid_without_ver:
                FeedbackMailList.update(
                    item_id=pid_without_ver.object_uuid,
                    feedback_maillist=action_feedbackmail.feedback_maillist)

        if record:
            deposit.update_feedback_mail()
            deposit.update_jpcoar_identifier()
        # TODO: Make private as default.
        # UpdateItem.publish(pid, approval_record)

    if action_endpoint == 'item_link' and record:
        current_pid = PersistentIdentifier.get_by_object(pid_type='recid',
                                                         object_type='rec',
                                                         object_uuid=item_id)

        if not pid_without_ver:
            pid_without_ver = get_record_without_version(current_pid)

        item_link = ItemLink(pid_without_ver.pid_value)
        relation_data = post_json.get('link_data')
        if relation_data:
            errors = item_link.update(relation_data)
            if errors:
                return jsonify(code=-1, msg=_(errors))

    # save pidstore_identifier to ItemsMetadata
    identifier_select = post_json.get('identifier_grant')
    if 'identifier_grant' == action_endpoint and identifier_select:
        idf_grant_jalc_doi_manual = post_json.get(
            'identifier_grant_jalc_doi_suffix')
        idf_grant_jalc_cr_doi_manual = post_json.get(
            'identifier_grant_jalc_cr_doi_suffix')
        idf_grant_jalc_dc_doi_manual = post_json.get(
            'identifier_grant_jalc_dc_doi_suffix')
        idf_grant_ndl_jalc_doi_manual = post_json.get(
            'identifier_grant_ndl_jalc_doi_suffix')

        # If is action identifier_grant, then save to to database
        identifier_grant = {
            'action_identifier_select': identifier_select,
            'action_identifier_jalc_doi': idf_grant_jalc_doi_manual,
            'action_identifier_jalc_cr_doi': idf_grant_jalc_cr_doi_manual,
            'action_identifier_jalc_dc_doi': idf_grant_jalc_dc_doi_manual,
            'action_identifier_ndl_jalc_doi': idf_grant_ndl_jalc_doi_manual
        }

        work_activity.create_or_update_action_identifier(
            activity_id=activity_id,
            action_id=action_id,
            identifier=identifier_grant)

        error_list = item_metadata_validation(item_id, identifier_select)

        if post_json.get('temporary_save') == 1:
            return jsonify(code=0, msg=_('success'))

        if isinstance(error_list, str):
            return jsonify(code=-1, msg=_(error_list))

        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if error_list:
            sessionstore.put('updated_json_schema_{}'.format(activity_id),
                             json.dumps(error_list).encode('utf-8'),
                             ttl_secs=300)
            return previous_action(activity_id=activity_id,
                                   action_id=action_id,
                                   req=-1)
        else:
            if sessionstore.redis.exists(
                    'updated_json_schema_{}'.format(activity_id)):
                sessionstore.delete(
                    'updated_json_schema_{}'.format(activity_id))

        if identifier_select != IDENTIFIER_GRANT_SELECT_DICT['NotGrant'] \
                and item_id is not None:
            record_without_version = item_id
            if record and pid_without_ver and not recid:
                record_without_version = pid_without_ver.object_uuid
            saving_doi_pidstore(item_id, record_without_version, post_json,
                                int(identifier_select))

    rtn = history.create_activity_history(activity)
    if not rtn:
        return jsonify(code=-1, msg=_('error'))
    # next action
    work_activity.upt_activity_action_status(
        activity_id=activity_id,
        action_id=action_id,
        action_status=ActionStatusPolicy.ACTION_DONE)
    work_activity.upt_activity_action_comment(activity_id=activity_id,
                                              action_id=action_id,
                                              comment='')
    flow = Flow()
    next_flow_action = flow.get_next_flow_action(
        activity_detail.flow_define.flow_id, action_id)
    if next_flow_action and len(next_flow_action) > 0:
        next_action_endpoint = next_flow_action[0].action.action_endpoint
        if 'end_action' == next_action_endpoint:
            new_activity_id = None
            if record:
                deposit.publish()
                updated_item = UpdateItem()
                # publish record without version ID when registering newly
                if recid:
                    # new record attached version ID
                    ver_attaching_record = deposit.newversion(current_pid)
                    new_activity_id = ver_attaching_record.model.id
                    ver_attaching_deposit = WekoDeposit(
                        ver_attaching_record, ver_attaching_record.model)
                    ver_attaching_deposit.publish()
                    record_bucket_id = merge_buckets_by_records(
                        current_pid.object_uuid,
                        ver_attaching_record.model.id,
                        sub_bucket_delete=True)
                    if not record_bucket_id:
                        return jsonify(code=-1, msg=_('error'))
                    # Record without version: Make status Public as default
                    updated_item.publish(record)
                else:
                    # update to record without version ID when editing
                    new_activity_id = record.model.id
                    if pid_without_ver:
                        record_without_ver = WekoDeposit.get_record(
                            pid_without_ver.object_uuid)
                        deposit_without_ver = WekoDeposit(
                            record_without_ver, record_without_ver.model)
                        deposit_without_ver['path'] = deposit.get('path', [])
                        parent_record = deposit_without_ver.\
                            merge_data_to_record_without_version(current_pid)
                        deposit_without_ver.publish()

                        set_bucket_default_size(new_activity_id)
                        merge_buckets_by_records(new_activity_id,
                                                 pid_without_ver.object_uuid)
                        updated_item.publish(parent_record)
                delete_unregister_buckets(new_activity_id)
            activity.update(
                action_id=next_flow_action[0].action_id,
                action_version=next_flow_action[0].action_version,
                item_id=new_activity_id,
            )
            work_activity.end_activity(activity)
        else:
            next_action_id = next_flow_action[0].action_id
            work_activity.upt_activity_action(
                activity_id=activity_id,
                action_id=next_action_id,
                action_status=ActionStatusPolicy.ACTION_DOING)
    # delete session value
    if session.get('itemlogin_id'):
        del session['itemlogin_id']
        del session['itemlogin_activity']
        del session['itemlogin_item']
        del session['itemlogin_steps']
        del session['itemlogin_action_id']
        del session['itemlogin_cur_step']
        del session['itemlogin_record']
        del session['itemlogin_res_check']
        del session['itemlogin_pid']
        del session['itemlogin_community_id']
    return jsonify(code=0, msg=_('success'))
Ejemplo n.º 16
0
def prepare_edit_item():
    """Prepare_edit_item.

    Host the api which provide 2 service:
        Create new activity for editing flow
        Check permission: check if user is owner/admin/shared user
    request:
        header: Content type must be json
        data:
            pid_value: pid_value
    return: The result json:
        code: status code,
        msg: meassage result,
        data: url redirect
    """
    def _get_workflow_by_item_type_id(item_type_name_id, item_type_id):
        """Get workflow settings by item type id."""
        workflow = WorkFlow.query.filter_by(itemtype_id=item_type_id).first()
        if not workflow:
            item_type_list = ItemTypes.get_by_name_id(item_type_name_id)
            id_list = [x.id for x in item_type_list]
            workflow = (WorkFlow.query.filter(
                WorkFlow.itemtype_id.in_(id_list)).order_by(
                    WorkFlow.itemtype_id.desc()).order_by(
                        WorkFlow.flow_id.asc()).first())
        return workflow

    if request.headers['Content-Type'] != 'application/json':
        """Check header of request"""
        return jsonify(code=-1, msg=_('Header Error'))
    post_activity = request.get_json()
    pid_value = post_activity.get('pid_value')

    if pid_value:
        try:
            record = WekoRecord.get_record_by_pid(pid_value)
            owner = str(record.get('owner'))
            shared_id = str(record.get('weko_shared_id'))
            user_id = str(get_current_user())
            is_admin = get_user_roles()
            activity = WorkActivity()

            pid_object = PersistentIdentifier.get('recid', pid_value)

            latest_pid = PIDVersioning(child=pid_object).last_child

            # check user's permission
            if user_id != owner and not is_admin[0] and user_id != shared_id:
                return jsonify(
                    code=-1, msg=_(r"You are not allowed to edit this item."))
            lists = ItemTypes.get_latest()
            if not lists:
                return jsonify(code=-1,
                               msg=_(r"You do not even have an Itemtype."))
            item_type_id = record.get('item_type_id')
            item_type = ItemTypes.get_by_id(item_type_id)
            if not item_type:
                return jsonify(code=-1, msg=_(r"This itemtype isn't found."))

            # check item is being editied
            item_id = latest_pid.object_uuid
            workflow_activity = activity.get_workflow_activity_by_item_id(
                item_id)
            if not workflow_activity:
                # get workflow of first record attached version ID: x.1
                workflow_activity = activity.get_workflow_activity_by_item_id(
                    pid_object.object_uuid)
                # if workflow of the item is not found
                # use default settings of item type to which the item belongs
            else:
                # show error when has stt is Begin or Doing
                if workflow_activity.action_status == \
                    ActionStatusPolicy.ACTION_BEGIN \
                    or workflow_activity.action_status == \
                        ActionStatusPolicy.ACTION_DOING:
                    return jsonify(code=-1,
                                   msg=_(r"The workflow is being edited."))

            # prepare params for new workflow activity
            if workflow_activity:
                post_activity['workflow_id'] = workflow_activity.workflow_id
                post_activity['flow_id'] = workflow_activity.flow_id
            else:
                workflow = _get_workflow_by_item_type_id(
                    item_type.name_id, item_type_id)
                if not workflow:
                    return jsonify(code=-1,
                                   msg=_('Workflow setting does not exist.'))
                post_activity['workflow_id'] = workflow.id
                post_activity['flow_id'] = workflow.flow_id
            post_activity['itemtype_id'] = item_type_id
            getargs = request.args
            community = getargs.get('community', None)

            # Create a new version of a record.
            record = WekoDeposit.get_record(item_id)
            if not record:
                return jsonify(code=-1, msg=_('Record does not exist.'))

            deposit = WekoDeposit(record, record.model)
            draft_record = deposit.newversion(pid_object)

            if not draft_record:
                return jsonify(code=-1, msg=_('An error has occurred.'))

            # Create snapshot bucket for draft record
            from invenio_records_files.models import RecordsBuckets
            try:
                with db.session.begin_nested():
                    from weko_workflow.utils import delete_bucket
                    draft_deposit = WekoDeposit(draft_record,
                                                draft_record.model)
                    snapshot = record.files.bucket.snapshot(lock=False)
                    snapshot.locked = False
                    draft_deposit['_buckets'] = {'deposit': str(snapshot.id)}
                    draft_record_bucket = RecordsBuckets.create(
                        record=draft_record.model, bucket=snapshot)

                    # Remove duplicated buckets
                    draft_record_buckets = RecordsBuckets.query.filter_by(
                        record_id=draft_record.model.id).all()
                    for record_bucket in draft_record_buckets:
                        if record_bucket != draft_record_bucket:
                            delete_bucket_id = record_bucket.bucket_id
                            RecordsBuckets.query.filter_by(
                                bucket_id=delete_bucket_id).delete()
                            delete_bucket(delete_bucket_id)
                    draft_deposit.commit()
            except Exception as ex:
                db.session.rollback()
                current_app.logger.exception(str(ex))
                return jsonify(code=-1, msg=_('An error has occurred.'))

            # Create a new workflow activity.
            rtn = activity.init_activity(post_activity, community,
                                         draft_record.model.id)

            if rtn:
                # GOTO: TEMPORARY EDIT MODE FOR IDENTIFIER
                identifier_actionid = get_actionid('identifier_grant')
                if workflow_activity:
                    identifier = activity.get_action_identifier_grant(
                        workflow_activity.activity_id, identifier_actionid)
                else:
                    identifier = activity.get_action_identifier_grant(
                        '', identifier_actionid)

                if identifier:
                    if identifier.get('action_identifier_select') > \
                            IDENTIFIER_GRANT_DOI:
                        identifier['action_identifier_select'] = \
                            IDENTIFIER_GRANT_CAN_WITHDRAW
                    elif identifier.get('action_identifier_select') == \
                            IDENTIFIER_GRANT_IS_WITHDRAWING:
                        identifier['action_identifier_select'] = \
                            IDENTIFIER_GRANT_WITHDRAWN
                    activity.create_or_update_action_identifier(
                        rtn.activity_id, identifier_actionid, identifier)

                mail_list = FeedbackMailList.get_mail_list_by_item_id(
                    item_id=pid_object.object_uuid)
                if mail_list:
                    activity.create_or_update_action_feedbackmail(
                        activity_id=rtn.activity_id,
                        action_id=ITEM_REGISTRATION_ACTION_ID,
                        feedback_maillist=mail_list)

                if community:
                    comm = GetCommunity.get_community_by_id(community)
                    url_redirect = url_for('weko_workflow.display_activity',
                                           activity_id=rtn.activity_id,
                                           community=comm.id)
                else:
                    url_redirect = url_for('weko_workflow.display_activity',
                                           activity_id=rtn.activity_id)
                return jsonify(code=0,
                               msg='success',
                               data={'redirect': url_redirect})

        except Exception as e:
            current_app.logger.error('Unexpected error: ', str(e))
    return jsonify(code=-1, msg=_('An error has occurred.'))
Ejemplo n.º 17
0
Archivo: views.py Proyecto: mhaya/weko
def display_activity(activity_id=0):
    """Display activity."""
    activity = WorkActivity()
    activity_detail = activity.get_activity_detail(activity_id)
    item = None
    if activity_detail is not None and activity_detail.item_id is not None:
        try:
            item = ItemsMetadata.get_record(id_=activity_detail.item_id)
        except NoResultFound as ex:
            current_app.logger.exception(str(ex))
            item = None

    steps = activity.get_activity_steps(activity_id)
    history = WorkActivityHistory()
    histories = history.get_activity_history_list(activity_id)
    workflow = WorkFlow()
    workflow_detail = workflow.get_workflow_by_id(activity_detail.workflow_id)
    if activity_detail.activity_status == \
        ActivityStatusPolicy.ACTIVITY_FINALLY \
        or activity_detail.activity_status == \
            ActivityStatusPolicy.ACTIVITY_CANCEL:
        activity_detail.activity_status_str = _('End')
    else:
        activity_detail.activity_status_str = \
            request.args.get('status', 'ToDo')
    cur_action = activity_detail.action
    action_endpoint = cur_action.action_endpoint
    action_id = cur_action.id
    temporary_comment = activity.get_activity_action_comment(
        activity_id=activity_id, action_id=action_id)

    # display_activity of Identifier grant
    idf_grant_data = None
    if 'identifier_grant' == action_endpoint and item:
        path = WekoRecord.get_record(item.id).get('path')
        if len(path) > 1:
            community_id = 'Root Index'
        else:
            index_address = path.pop(-1).split('/')
            index_id = Index.query.filter_by(id=index_address.pop()).one()
            community_id = get_community_id_by_index(
                index_id.index_name_english)
        idf_grant_data = Identifier.query.filter_by(
            repository=community_id).one_or_none()

        # valid date pidstore_identifier data
        if idf_grant_data is not None:
            if not idf_grant_data.jalc_doi:
                idf_grant_data.jalc_doi = '<Empty>'
            if not idf_grant_data.jalc_crossref_doi:
                idf_grant_data.jalc_crossref_doi = '<Empty>'
            if not idf_grant_data.jalc_datacite_doi:
                idf_grant_data.jalc_datacite_doi = '<Empty>'
            if not idf_grant_data.cnri:
                idf_grant_data.cnri = '<Empty>'
            if not idf_grant_data.suffix:
                idf_grant_data.suffix = '<Empty>'

    temporary_idf_grant = 0
    temporary_idf_grant_suffix = []
    temporary_identifier = activity.get_action_identifier_grant(
        activity_id=activity_id, action_id=action_id)
    if temporary_identifier:
        temporary_idf_grant = temporary_identifier.get(
            'action_identifier_select')
        temporary_idf_grant_suffix.append(
            temporary_identifier.get('action_identifier_jalc_doi'))
        temporary_idf_grant_suffix.append(
            temporary_identifier.get('action_identifier_jalc_cr_doi'))
        temporary_idf_grant_suffix.append(
            temporary_identifier.get('action_identifier_jalc_dc_doi'))

    temporary_journal = activity.get_action_journal(activity_id=activity_id,
                                                    action_id=action_id)
    if temporary_journal:
        temporary_journal = temporary_journal.action_journal

    cur_step = action_endpoint
    step_item_login_url = None
    approval_record = []
    pid = None
    record = {}
    need_file = False
    json_schema = ''
    schema_form = ''
    item_save_uri = ''
    files = []
    endpoints = {}
    links = None
    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        activity_session = dict(activity_id=activity_id,
                                action_id=activity_detail.action_id,
                                action_version=cur_action.action_version,
                                action_status=ActionStatusPolicy.ACTION_DOING,
                                commond='')
        session['activity_info'] = activity_session
        # get item edit page info.
        step_item_login_url, need_file, record, json_schema, \
            schema_form, item_save_uri, files, endpoints = item_login(
                item_type_id=workflow_detail.itemtype_id)
        if item:
            pid_identifier = PersistentIdentifier.get_by_object(
                pid_type='depid', object_type='rec', object_uuid=item.id)
            record = item
    # if 'approval' == action_endpoint:
    if item:
        # get record data for the first time access to editing item screen
        pid_identifier = PersistentIdentifier.get_by_object(
            pid_type='depid', object_type='rec', object_uuid=item.id)
        record_class = import_string('weko_deposit.api:WekoRecord')
        resolver = Resolver(pid_type='recid',
                            object_type='rec',
                            getter=record_class.get_record)
        pid, approval_record = resolver.resolve(pid_identifier.pid_value)

        files = to_files_js(approval_record)

        # get files data after click Save btn
        sessionstore = RedisStore(
            redis.StrictRedis.from_url('redis://{host}:{port}/1'.format(
                host=os.getenv('INVENIO_REDIS_HOST', 'localhost'),
                port=os.getenv('INVENIO_REDIS_PORT', '6379'))))
        if sessionstore.redis.exists('activity_item_' + str(activity_id)):
            item_str = sessionstore.get('activity_item_' + str(activity_id))
            item_json = json.loads(item_str.decode('utf-8'))
            if 'files' in item_json:
                files = item_json.get('files')
        if not files:
            deposit = WekoDeposit.get_record(item.id)
            if deposit is not None:
                files = to_files_js(deposit)

        from weko_deposit.links import base_factory
        links = base_factory(pid)

    res_check = check_authority_action(activity_id, action_id)

    getargs = request.args
    ctx = {'community': None}
    community_id = ""
    if 'community' in getargs:
        comm = GetCommunity.get_community_by_id(request.args.get('community'))
        community_id = request.args.get('community')
        ctx = {'community': comm}
        community_id = comm.id
    # be use for index tree and comment page.
    if 'item_login' == action_endpoint or 'file_upload' == action_endpoint:
        session['itemlogin_id'] = activity_id
        session['itemlogin_activity'] = activity_detail
        session['itemlogin_item'] = item
        session['itemlogin_steps'] = steps
        session['itemlogin_action_id'] = action_id
        session['itemlogin_cur_step'] = cur_step
        session['itemlogin_record'] = approval_record
        session['itemlogin_histories'] = histories
        session['itemlogin_res_check'] = res_check
        session['itemlogin_pid'] = pid
        session['itemlogin_community_id'] = community_id

    return render_template(
        'weko_workflow/activity_detail.html',
        render_widgets=True,
        activity=activity_detail,
        item=item,
        steps=steps,
        action_id=action_id,
        cur_step=cur_step,
        temporary_comment=temporary_comment,
        temporary_journal=temporary_journal,
        temporary_idf_grant=temporary_idf_grant,
        temporary_idf_grant_suffix=temporary_idf_grant_suffix,
        idf_grant_data=idf_grant_data,
        idf_grant_input=IDENTIFIER_GRANT_LIST,
        idf_grant_method=IDENTIFIER_GRANT_SUFFIX_METHOD,
        record=approval_record,
        records=record,
        step_item_login_url=step_item_login_url,
        need_file=need_file,
        jsonschema=json_schema,
        schemaform=schema_form,
        id=workflow_detail.itemtype_id,
        item_save_uri=item_save_uri,
        files=files,
        endpoints=endpoints,
        error_type='item_login_error',
        links=links,
        histories=histories,
        res_check=res_check,
        pid=pid,
        community_id=community_id,
        **ctx)