def restore_itemtype(self, item_type_id=0): """Restore logically deleted item types.""" if item_type_id > 0: record = ItemTypes.get_record(id_=item_type_id, with_deleted=True) if record is not None and record.model.is_deleted: # Get all versions all_records = ItemTypes.get_records_by_name_id( name_id=record.model.name_id, with_deleted=True) # Get item type name item_type_name = ItemTypeNames.get_record( id_=record.model.name_id, with_deleted=True) if all_records and item_type_name: try: # Restore item type name ItemTypeNames.restore(item_type_name) # Restore item typea for k in all_records: k.restore() db.session.commit() except BaseException: db.session.rollback() current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return jsonify(code=-1, msg=_('Failed to restore Item type.')) current_app.logger.debug( 'Itemtype restore: {}'.format(item_type_id)) return jsonify(code=0, msg=_('Restored Item type successfully.')) return jsonify(code=-1, msg=_('An error has occurred.'))
def index(item_type_id=0): """Renders an item register view. :param item_type_id: Item type ID. (Default: 0) :return: The rendered template. """ try: lists = ItemTypes.get_latest() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMS_UI_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return redirect( url_for('.index', item_type_id=lists[0].item_type[0].id)) json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) need_file = False if 'filename' in json.dumps(item_type.schema): need_file = True return render_template( current_app.config['WEKO_ITEMS_UI_FORM_TEMPLATE'], render_widgets=True, need_file=need_file, record={}, jsonschema=json_schema, schemaform=schema_form, lists=lists, id=item_type_id, files=[]) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def index(self, item_type_id=0): """Renders an item type register view. :param item_type_id: Item type i. Default 0. """ lists = ItemTypes.get_latest(True) # Check that item type is already registered to an item or not for item in lists: # Get all versions all_records = ItemTypes.get_records_by_name_id(name_id=item.id) item.belonging_item_flg = False for item in all_records: metaDataRecords = ItemsMetadata.get_by_item_type_id( item_type_id=item.id) item.belonging_item_flg = len(metaDataRecords) > 0 if item.belonging_item_flg: break is_sys_admin = has_system_admin_access() return self.render( current_app.config['WEKO_ITEMTYPES_UI_ADMIN_REGISTER_TEMPLATE'], lists=lists, id=item_type_id, is_sys_admin=is_sys_admin, lang_code=session.get('selected_language', 'en') # Set default )
def delete_itemtype(self, item_type_id=0): """Soft-delete an item type.""" if item_type_id > 0: record = ItemTypes.get_record(id_=item_type_id) if record is not None: # Check harvesting_type if record.model.harvesting_type: flash(_('Cannot delete Item type for Harvesting.'), 'error') return jsonify(code=-1) # Get all versions all_records = ItemTypes.get_records_by_name_id( name_id=record.model.name_id) # Check that item type is already registered to an item or not for item in all_records: metaDataRecords = ItemsMetadata.get_by_item_type_id( item_type_id=item.id) if len(metaDataRecords) > 0: flash( _( 'Cannot delete due to child' ' existing item types.'), 'error') return jsonify(code=-1) # Get item type name item_type_name = ItemTypeNames.get_record( id_=record.model.name_id) if all_records and item_type_name: try: # Delete item type name ItemTypeNames.delete(item_type_name) # Delete item typea for k in all_records: k.delete() db.session.commit() except BaseException: db.session.rollback() current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) flash(_('Failed to delete Item type.'), 'error') return jsonify(code=-1) current_app.logger.debug( 'Itemtype delete: {}'.format(item_type_id)) flash(_('Deleted Item type successfully.')) return jsonify(code=0) flash(_('An error has occurred.'), 'error') return jsonify(code=-1)
def site_license(): """Site license setting page.""" current_app.logger.info('site-license setting page') if 'POST' in request.method: jfy = {} try: # update item types and site license info SiteLicense.update(request.get_json()) jfy['status'] = 201 jfy['message'] = 'Site license was successfully updated.' except: jfy['status'] = 500 jfy['message'] = 'Failed to update site license.' return make_response(jsonify(jfy), jfy['status']) try: # site license list result_list = SiteLicense.get_records() # item types list n_lst = ItemTypes.get_latest() result = get_response_json(result_list, n_lst) return render_template( current_app.config['WEKO_ADMIN_SITE_LICENSE_TEMPLATE'], result=json.dumps(result)) except: abort(500)
def weko_view_method(pid, record, template=None, **kwargs): r"""Display Weko view. Sends record_viewed signal and renders template. :param pid: PID object. :param record: Record object. :param template: Template to render. :returns: The rendered template. """ flst = FilesMetadata.get_records(pid.pid_value) frecord = [] if len(flst) > 0: for fj in flst: frecord.append(fj.dumps()) item_type = ItemTypes.get_by_id(id_=record['item_type_id']) item_type_info = "{}({})".format(item_type.item_type_name.name, item_type.tag) return render_template(template, pid=pid, record=record, files=frecord, item_type_info=item_type_info)
def index(item_type_id=0): """Renders an item type register view.""" lists = ItemTypes.get_latest() return render_template( current_app.config['WEKO_ITEMTYPES_UI_REGISTER_TEMPLATE'], lists=lists, id=item_type_id)
def site_license_check(): # site license permission check obj = ItemTypes.get_by_id(record.get('item_type_id')) if obj.item_type_name.has_site_license: return check_site_license_permission( ) | check_user_group_permission(fjson.get('groups')) return False
def index(self): """Site License settings view.""" if 'POST' in request.method: jfy = {} try: # update item types and site license info SiteLicense.update(request.get_json()) jfy['status'] = 201 jfy['message'] = 'Site license was successfully updated.' except BaseException: jfy['status'] = 500 jfy['message'] = 'Failed to update site license.' return make_response(jsonify(jfy), jfy['status']) try: # site license list result_list = SiteLicense.get_records() # item types list n_lst = ItemTypes.get_latest() result = get_response_json(result_list, n_lst) return self.render( current_app.config['WEKO_ADMIN_SITE_LICENSE_TEMPLATE'], result=json.dumps(result)) except BaseException as e: current_app.logger.error('Could not save site license settings', e) abort(500)
def create_work_flow(item_type_id): """Handle create work flow. :argument item_type_id -- {str} item_type_id. :return """ flow_define = FlowDefine.query.filter_by( flow_name='Registration Flow').first() it = ItemTypes.get_by_id(item_type_id) if flow_define and it: try: data = WorkFlow() data.flows_id = uuid.uuid4() data.flows_name = it.item_type_name.name data.itemtype_id = it.id data.flow_id = flow_define.id db.session.add(data) db.session.commit() except Exception as ex: db.session.rollback() current_app.logger.error("create work flow error") current_app.logger.error(ex)
def init_workflow(): """Init WorkFlow Table.""" db_workflow = list() flow_list = FlowDefine.query.order_by(asc(FlowDefine.id)).all() itemtypesname_list = ItemTypes.get_latest() db_workflow.append( dict(flows_id=uuid.uuid4(), flows_name='Registration WorkFlow', itemtype_id=itemtypesname_list[0].item_type[0].id, flow_id=flow_list[0].id)) return db_workflow
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
def get_schema_form(item_type_id=0): """Get schema form. :param item_type_id: Item type ID. (Default: 0) :return: The json object. """ try: cur_lang = current_i18n.language result = None if item_type_id > 0: result = ItemTypes.get_by_id(item_type_id) if result is None: return '["*"]' schema_form = result.form filemeta_form = schema_form[0] if 'filemeta' == filemeta_form.get('key'): group_list = Group.get_group_list() filemeta_form_group = filemeta_form.get('items')[-1] filemeta_form_group['type'] = 'select' filemeta_form_group['titleMap'] = group_list if 'default' != cur_lang: for elem in schema_form: if 'title_i18n' in elem and cur_lang in elem['title_i18n']\ and len(elem['title_i18n'][cur_lang]) > 0: elem['title'] = elem['title_i18n'][cur_lang] if 'items' in elem: for sub_elem in elem['items']: if 'title_i18n' in sub_elem and cur_lang in \ sub_elem['title_i18n'] and len( sub_elem['title_i18n'][cur_lang]) > 0: sub_elem['title'] = sub_elem['title_i18n'][ cur_lang] if sub_elem.get('title') == 'Group/Price': for sub_item in sub_elem['items']: if sub_item['title'] == "価格" and \ 'validationMessage_i18n' in sub_item and \ cur_lang in sub_item[ 'validationMessage_i18n'] and\ len(sub_item['validationMessage_i18n'] [cur_lang]) > 0: sub_item['validationMessage'] = sub_item[ 'validationMessage_i18n'][cur_lang] if 'items' in sub_elem: for sub_item in sub_elem['items']: if 'title_i18n' in sub_item and cur_lang in \ sub_item['title_i18n'] and len( sub_item['title_i18n'][cur_lang]) > 0: sub_item['title'] = sub_item['title_i18n'][ cur_lang] return jsonify(schema_form) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def mapping_index(ItemTypeID=0): """Renders an item type mapping view. :param ItemTypeID: Item type ID. (Default: 0) :return: The rendered template. """ lists = ItemTypes.get_all() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMTYPES_UI_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(ItemTypeID) if item_type is None: return redirect(url_for('.mapping_index', ItemTypeID=lists[0].id)) item_type_mapping = Mapping.get_record(ItemTypeID) mapping = json.dumps(item_type_mapping, indent=4, ensure_ascii=False) current_app.logger.debug(mapping) return render_template( current_app.config['WEKO_ITEMTYPES_UI_MAPPING_TEMPLATE'], lists=lists, mapping=mapping, id=ItemTypeID)
def is_billing_item(item_type_id): """Checks if item is a billing item based on its meta data schema.""" item_type = ItemTypes.get_by_id(id_=item_type_id) if item_type: properties = item_type.schema['properties'] for meta_key in properties: if properties[meta_key]['type'] == 'object' and \ 'groupsprice' in properties[meta_key]['properties'] or \ properties[meta_key]['type'] == 'array' and 'groupsprice' in \ properties[meta_key]['items']['properties']: return True return False
def get_json_schema(item_type_id=0): """Get json schema. :param item_type_id: Item type ID. (Default: 0) :return: The json object. """ try: result = None json_schema = None cur_lang = current_i18n.language if item_type_id > 0: if item_type_id == 20: result = ItemTypes.get_by_id(item_type_id) if result is None: return '{}' json_schema = result.schema properties = json_schema.get('properties') for key, value in properties.items(): if 'validationMessage_i18n' in value: value['validationMessage'] =\ value['validationMessage_i18n'][cur_lang] else: result = ItemTypes.get_record(item_type_id) if 'filemeta' in json.dumps(result): group_list = Group.get_group_list() group_enum = list(group_list.keys()) filemeta_group = result.get('properties').get( 'filemeta').get('items').get('properties').get( 'groups') filemeta_group['enum'] = group_enum json_schema = result if result is None: return '{}' return jsonify(json_schema) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def default_view_method(pid, record, template=None): """Default view method. Sends ``record_viewed`` signal and renders template. """ record_viewed.send( current_app._get_current_object(), pid=pid, record=record, ) item_type_id = record.get('item_type_id') lists = ItemTypes.get_latest() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMS_UI_ERROR_TEMPLATE'] ) item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return redirect( url_for('.index', item_type_id=lists[0].item_type[0].id)) json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) need_file = False # if 'filemeta' in json.dumps(item_type.schema): if 'filename' in json.dumps(item_type.schema): need_file = True return render_template( template, need_file=need_file, record=record.item_metadata, jsonschema=json_schema, schemaform=schema_form, lists=lists, links=to_links_js(pid), id=item_type_id, files=to_files_js(record), pid=pid )
def index(item_type_id=0): """Renders an item register view. :param item_type_id: Item type ID. (Default: 0) :return: The rendered template. """ try: from weko_theme.utils import get_design_layout # Get the design for widget rendering page, render_widgets = get_design_layout( current_app.config['WEKO_THEME_DEFAULT_COMMUNITY']) lists = ItemTypes.get_latest() if lists is None or len(lists) == 0: return render_template( current_app.config['WEKO_ITEMS_UI_ERROR_TEMPLATE']) item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return redirect( url_for('.index', item_type_id=lists[0].item_type[0].id)) json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) need_file, need_billing_file = is_schema_include_key(item_type.schema) return render_template( current_app.config['WEKO_ITEMS_UI_FORM_TEMPLATE'], page=page, render_widgets=render_widgets, need_file=need_file, need_billing_file=need_billing_file, record={}, jsonschema=json_schema, schemaform=schema_form, lists=lists, id=item_type_id, files=[]) except BaseException: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def __get_item_types(ids: list) -> dict: """Get item types base on list of item type id. Args: ids (list): Item Type identifier list. Returns: dict: Item types. """ item_types = ItemTypes.get_records(ids) item_type_dict = {} for item_type in item_types: item_type_dict[str(item_type.model.id)] = item_type return item_type_dict
def render(item_type_id=0): result = None if item_type_id > 0: result = ItemTypes.get_by_id(id_=item_type_id) if result is None: result = { 'table_row': [], 'table_row_map': {}, 'meta_list': {}, 'schemaeditor': { 'schema': {} } } return jsonify(result.render)
def iframe_index(item_type_id=0): """Renders an item register view. :param item_type_id: Item type ID. (Default: 0) :return: The rendered template. """ try: item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: return render_template('weko_items_ui/iframe/error.html', error_type='no_itemtype') json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) 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')))) record = {} files = [] endpoints = {} activity_session = session['activity_info'] activity_id = activity_session.get('activity_id', None) if activity_id and sessionstore.redis.exists( 'activity_item_'+activity_id): item_str = sessionstore.get('activity_item_'+activity_id) item_json = json.loads(item_str) if 'metainfo' in item_json: record = item_json.get('metainfo') if 'files' in item_json: files = item_json.get('files') if 'endpoints' in item_json: endpoints = item_json.get('endpoints') need_file = False if 'filename' in json.dumps(item_type.schema): need_file = True return render_template( 'weko_items_ui/iframe/item_edit.html', need_file=need_file, record=record, jsonschema=json_schema, schemaform=schema_form, id=item_type_id, item_save_uri=url_for('.iframe_save_model'), files=files, endpoints=endpoints ) except: current_app.logger.error('Unexpected error: ', sys.exc_info()[0]) return abort(400)
def workflow_detail(self, workflow_id='0'): """Get workflow info. :return: """ if WEKO_WORKFLOW_SHOW_HARVESTING_ITEMS: itemtype_list = ItemTypes.get_latest() else: itemtype_list = ItemTypes.get_latest_custorm_harvesting() flow_api = Flow() flow_list = flow_api.get_flow_list() if '0' == workflow_id: """Create new workflow""" return self.render('weko_workflow/admin/workflow_detail.html', workflow=None, itemtype_list=itemtype_list, flow_list=flow_list) """Update the workflow info""" workflow = WorkFlow() workflows = workflow.get_workflow_detail(workflow_id) return self.render('weko_workflow/admin/workflow_detail.html', workflow=workflows, itemtype_list=itemtype_list, flow_list=flow_list)
def render_itemtype(self, item_type_id=0): """Renderer.""" result = None if item_type_id > 0: result = ItemTypes.get_by_id(id_=item_type_id) if result is None: result = { 'table_row': [], 'table_row_map': {}, 'meta_list': {}, 'schemaeditor': { 'schema': {} } } else: result = result.render return jsonify(result)
def index(self): """Site License settings view.""" if 'POST' in request.method: jfy = {} try: # update item types and site license info data = request.get_json() if data and data.get('site_license'): for license in data['site_license']: err_addr = False if not license.get('addresses'): err_addr = True else: for addresses in license['addresses']: for item in addresses.values(): if not item or '' in item: err_addr = True # break for item addresses break if err_addr: # break for addresses break if err_addr: raise ValueError('IP Address is incorrect') SiteLicense.update(data) jfy['status'] = 201 jfy['message'] = 'Site license was successfully updated.' except BaseException: jfy['status'] = 500 jfy['message'] = 'Failed to update site license.' return make_response(jsonify(jfy), jfy['status']) try: # site license list result_list = SiteLicense.get_records() # item types list n_lst = ItemTypes.get_latest() result = get_response_json(result_list, n_lst) return self.render( current_app.config['WEKO_ADMIN_SITE_LICENSE_TEMPLATE'], result=json.dumps(result)) except BaseException as e: current_app.logger.error('Could not save site license settings', e) abort(500)
def item_login(item_type_id=0): """Return information that item register need. :param item_type_id: Item type ID. (Default: 0) """ template_url = 'weko_items_ui/iframe/item_edit.html' need_file = False record = {} json_schema = '' schema_form = '' item_save_uri = url_for('weko_items_ui.iframe_save_model') files = [] endpoints = {} try: item_type = ItemTypes.get_by_id(item_type_id) if item_type is None: template_url = 'weko_items_ui/iframe/error.html' json_schema = '/items/jsonschema/{}'.format(item_type_id) schema_form = '/items/schemaform/{}'.format(item_type_id) 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')))) activity_session = session['activity_info'] activity_id = activity_session.get('activity_id', None) if activity_id and sessionstore.redis.exists( 'activity_item_' + activity_id): item_str = sessionstore.get('activity_item_' + activity_id) item_json = json.loads(item_str) if 'metainfo' in item_json: record = item_json.get('metainfo') if 'files' in item_json: files = item_json.get('files') if 'endpoints' in item_json: endpoints = item_json.get('endpoints') if 'filename' in json.dumps(item_type.schema): need_file = True except Exception as e: template_url = 'weko_items_ui/iframe/error.html' current_app.logger.debug(str(e)) return template_url, need_file, record, json_schema, \ schema_form, item_save_uri, files, endpoints
def register(self, item_type_id=0): """Register an item type.""" if request.headers['Content-Type'] != 'application/json': current_app.logger.debug(request.headers['Content-Type']) return jsonify(msg=_('Header Error')) data = request.get_json() try: table_row_map = data.get('table_row_map') json_schema = fix_json_schema( table_row_map.get( 'schema')) if not json_schema: raise ValueError('Schema is in wrong format.') record = ItemTypes.update(id_=item_type_id, name=table_row_map.get( 'name'), schema=json_schema, form=table_row_map.get( 'form'), render=data) # Just update Mapping when create new record if record.model.id != item_type_id: Mapping.create(item_type_id=record.model.id, mapping=table_row_map. get('mapping')) ItemTypeEditHistory.create_or_update( item_type_id=record.model.id, user_id=current_user.get_id(), notes=data.get('edit_notes', {}) ) db.session.commit() except BaseException: raise db.session.rollback() return jsonify(msg=_('Failed to register Item type.')) current_app.logger.debug('itemtype register: {}'.format(item_type_id)) flash(_('Successfuly registered Item type.')) redirect_url = url_for('.index', item_type_id=record.model.id) return jsonify(msg=_('Successfuly registered Item type.'), redirect_url=redirect_url)
def workflow_detail(self, workflow_id='0'): """ Get workflow info :return: """ itemtype_list = ItemTypes.get_latest() flow_api = Flow() flow_list = flow_api.get_flow_list() if '0' == workflow_id: """Create new workflow""" return self.render('weko_workflow/admin/workflow_detail.html', workflow=None, itemtype_list=itemtype_list, flow_list=flow_list) """Update the workflow info""" workflow = WorkFlow() workflows = workflow.get_workflow_detail(workflow_id) return self.render('weko_workflow/admin/workflow_detail.html', workflow=workflows, itemtype_list=itemtype_list, flow_list=flow_list)
def get_item_type(item_type_id=0) -> dict: """Get item type. :param item_type_id: Item type ID. (Default: 0). :return: The json object. """ result = None if item_type_id > 0: itemtype = ItemTypes.get_by_id(item_type_id) if itemtype and itemtype.schema \ and itemtype.item_type_name.name and item_type_id: result = { 'schema': itemtype.schema, 'name': itemtype.item_type_name.name, 'item_type_id': item_type_id } if result is None: return {} return result
def get_cinii_record_data(naid, item_type_id): """Get record data base on CiNii API. :param naid: The CiNii ID :param item_type_id: The item type ID :return: """ result = list() api_response = CiNiiURL(naid).get_data() if api_response["error"] \ or not isinstance(api_response['response'], dict): return result api_data = get_cinii_data_by_key(api_response, 'all') items = ItemTypes.get_by_id(item_type_id) if items is None: return result elif items.form is not None: autofill_key_tree = get_autofill_key_tree( items.form, get_cinii_autofill_item(item_type_id)) result = build_record_model(autofill_key_tree, api_data) return result
def render_itemtype(self, item_type_id=0): """Renderer.""" result = None if item_type_id > 0: result = ItemTypes.get_by_id(id_=item_type_id, with_deleted=True) if result is None: result = { 'table_row': [], 'table_row_map': {}, 'meta_list': {}, 'schemaeditor': { 'schema': {} }, 'edit_notes': {} } else: edit_notes = result.latest_edit_history result = result.render result['edit_notes'] = edit_notes return jsonify(result)