class PreconditionSimpleController(RestController): def _before(self, *args, **kw): tmpl_context.sidebar_section = "preconditions" @expose() def get_all(self, workspace, **kw): tg.redirect('/precondition', params=dict(workspace=workspace)) @expose('ksweb.templates.precondition.simple.new') @validate({'workspace': WorkspaceExistValidator(required=True)}) def new(self, workspace, **kw): return dict(page='precondition-new', workspace=workspace, qa_value=kw.get('qa_value'), precondition={ 'question_content': kw.get('question_content', None), 'question_title': kw.get('question_title', None) }) @decode_params('json') @expose('json') @validate( { 'title': StringLengthValidator(min=2), 'workspace': WorkspaceExistValidator(required=True), 'question': QAExistValidator(required=True), 'answer_type': OneOfValidator(values=[u'have_response', u'what_response']), }, error_handler=validation_errors_response) def post(self, title, workspace, question, answer_type, interested_response=[], **kw): user = request.identity['user'] qa = Qa.query.get(_id=ObjectId(question)) _type = Precondition.TYPES.SIMPLE if qa.is_text: _condition = [qa._id, ''] else: if answer_type == 'have_response': interested_response = qa.answers answers_len = len(interested_response) if answers_len < 1: response.status_code = 412 return dict(errors={ 'interested_response': _('Please select at least one answer') }) if answers_len == 1: _condition = [qa._id, interested_response[0]] else: advanced_condition = [] for answer in interested_response: ___ = Precondition(_owner=user._id, _workspace=ObjectId(workspace), title="%s_%s" % (qa.title.upper(), answer.upper()), type=_type, condition=[qa._id, answer], public=True, visible=False) advanced_condition.append(___._id) advanced_condition.append('or') del advanced_condition[-1] _condition = advanced_condition _type = Precondition.TYPES.ADVANCED new_filter = Precondition(_owner=user._id, _workspace=ObjectId(workspace), title=title, type=_type, condition=_condition) return dict(precondition_id=str(new_filter._id), errors=None) @decode_params('json') @expose('json') @validate( { '_id': PreconditionExistValidator(required=True), 'title': StringLengthValidator(min=2), 'workspace': WorkspaceExistValidator(required=True), 'question': QAExistValidator(required=True), }, error_handler=validation_errors_response) @require( CanManageEntityOwner( msg=l_(u'You are not allowed to edit this filter.'), field='_id', entity_model=Precondition)) def put(self, _id, title, workspace, question, interested_response, **kw): check = self.get_related_entities(_id) if check.get("entities"): entity = dict(_id=_id, title=title, condition=[question, interested_response], _workspace=workspace, auto_generated=False, entity='precondition/simple') session[ 'entity'] = entity # overwrite always same key for avoiding conflicts session.save() return dict(redirect_url=tg.url('/resolve', params=dict(workspace=workspace))) precondition = Precondition.query.get(_id=ObjectId(_id)) precondition.title = title precondition.condition = [ObjectId(question), interested_response] precondition.auto_generated = False precondition.status = Precondition.STATUS.UNREAD precondition._workspace = workspace return dict(errors=None, redirect_url=None) @decode_params('json') @expose('json') def get_related_entities(self, _id): return get_related_entities_for_filters(_id) @expose('ksweb.templates.precondition.simple.new') @validate( { '_id': PreconditionExistValidator(), 'workspace': WorkspaceExistValidator() }, error_handler=validation_errors_response) @require( CanManageEntityOwner( msg=l_(u'You are not allowed to edit this filter.'), field='_id', entity_model=Precondition)) def edit(self, _id, workspace): precondition = Precondition.query.find({ '_id': ObjectId(_id), '_workspace': ObjectId(workspace) }).first() return dict(precondition=precondition, workspace=workspace, errors=None) @expose('json') @decode_params('json') @validate({ '_id': PreconditionExistValidator(required=True), }, error_handler=validation_errors_response) def human_readable_details(self, _id): return dict(precondition=Precondition.query.get(ObjectId(_id)))
class QaController(RestController): def _before(self, *args, **kw): tmpl_context.sidebar_section = "qas" allow_only = predicates.not_anonymous(msg=l_('Only for admin or lawyer')) @expose('ksweb.templates.qa.index') @paginate('entities', items_per_page=int(tg.config.get('pagination.items_per_page'))) @validate({ 'workspace': WorkspaceExistValidator(required=True), }, error_handler=validation_errors_response) def get_all(self, workspace, **kw): return dict(page='qa-index', fields={ 'columns_name': [_('Label'), _('Question'), _('Filter'), _('Id')], 'fields_name': 'title question parent_precondition hash'.split() }, entities=Qa.available_for_user( request.identity['user']._id, workspace), actions=False, workspace=workspace) @expose('json') @validate({ 'id': QAExistValidator(required=True), }, error_handler=validation_errors_response) def get_one(self, id, **kw): id = hash_to_id(id, Qa) return dict(qa=Qa.by_id(id)) @expose('json') @validate({'workspace': WorkspaceExistValidator(required=True)}) def valid_options(self, workspace): questions = Qa.available_for_user(request.identity['user']._id, workspace) return dict(questions=[{ '_id': qa._id, 'title': qa.title } for qa in questions]) @expose('json') @expose('ksweb.templates.qa.new') @validate({ 'workspace': WorkspaceExistValidator(required=True), }) def new(self, workspace, **kw): return dict(errors=None, workspace=workspace, referrer=kw.get('referrer'), qa={ 'question': kw.get('question_content', None), 'title': kw.get('question_title', None), '_parent_precondition': kw.get('precondition_id', None) }) @decode_params('json') @expose('json') @validate( { 'title': StringLengthValidator(min=2), 'workspace': WorkspaceExistValidator(required=True), 'question': StringLengthValidator(min=2), 'tooltip': StringLengthValidator(min=0, max=100), 'link': StringLengthValidator(min=0, max=100), 'answer_type': OneOfValidator(values=Qa.QA_TYPE, required=True), 'precondition': PreconditionExistValidator(required=False), }, error_handler=validation_errors_response) def post(self, title, workspace, question, tooltip, link, answer_type, precondition=None, answers=None, **kw): if not self._are_answers_valid(answer_type, answers): response.status_code = 412 return dict( errors={'answers': _('Please add at least one more answer')}) user = request.identity['user'] qa = Qa(_owner=user._id, _workspace=ObjectId(workspace), _parent_precondition=to_object_id(precondition), title=title, question=question, tooltip=tooltip, link=link, type=answer_type, answers=answers, auto_generated=False, public=True, visible=True) DBSession.flush(qa) qa.generate_output_from() return dict(errors=None, _id=ObjectId(qa._id)) @decode_params('json') @expose('json') @validate( { '_id': QAExistValidator(required=True), 'title': StringLengthValidator(min=2), 'workspace': WorkspaceExistValidator(required=True), 'question': StringLengthValidator(min=2), 'tooltip': StringLengthValidator(min=0, max=100), 'link': StringLengthValidator(min=0, max=100), 'answer_type': OneOfValidator(values=Qa.QA_TYPE, required=True), 'precondition': PreconditionExistValidator(required=False), }, error_handler=validation_errors_response) def put(self, _id, title, workspace, question, tooltip, link, answer_type, precondition=None, answers=None, **kw): if not self._are_answers_valid(answer_type, answers): response.status_code = 412 return dict( errors={'answers': _('Please add at least one more answer')}) check = self.get_related_entities(_id) if check.get("entities"): entity = dict(_id=_id, _workspace=workspace, title=title, entity='qa', question=question, tooltip=tooltip, link=link, auto_generated=False, type=answer_type, _parent_precondition=precondition, answers=answers) session.data_serializer = 'pickle' session[ 'entity'] = entity # overwrite always same key for avoiding conflicts session.save() return dict(redirect_url=tg.url('/resolve', params=dict(workspace=workspace))) qa = Qa.upsert({'_id': ObjectId(_id)}, dict(_workspace=ObjectId(workspace), _parent_precondition=to_object_id(precondition), title=title, question=question, auto_generated=False, tooltip=tooltip, link=link, type=answer_type, answers=answers)) DBSession.flush(qa) qa.generate_output_from() return dict(errors=None) @expose('ksweb.templates.qa.new') @validate({'_id': QAExistValidator(model=True)}, error_handler=validation_errors_response) @require( CanManageEntityOwner(msg=l_(u'You can not edit this Q/A'), field='_id', entity_model=Qa)) def edit(self, _id, workspace=None, **kw): ws = Workspace.query.find({'_id': ObjectId(workspace)}).first() if not ws: return tg.abort(404) qa = Qa.query.find({'_id': ObjectId(_id)}).first() return dict(qa=qa, workspace=ws._id, errors=None) @expose('json') @decode_params('json') @validate({ '_id': QAExistValidator(required=True), }, error_handler=validation_errors_response) def human_readable_details(self, _id, **kw): qa = Qa.query.find({'_id': ObjectId(_id)}).first() return dict(qa=qa) @decode_params('json') @expose('json') def get_related_entities(self, _id): """ This method return ALL entities (Precondition simple) that have inside the given _id :param _id: :return: """ entities = Precondition.query.find({ 'type': Precondition.TYPES.SIMPLE, 'condition': ObjectId(_id) }).all() return {'entities': entities, 'len': len(entities)} def _are_answers_valid(self, answer_type, answers): if (answer_type == Qa.TYPES.SINGLE and len(answers) < 2) or\ (answer_type == Qa.TYPES.MULTI and len(answers) < 1): return False return True @expose('json') @validate({'workspace': WorkspaceExistValidator(required=True)}) def mark_as_read(self, workspace): Qa.mark_as_read(request.identity['user']._id, workspace)
class PreconditionController(BaseController): allow_only = predicates.has_any_permission('manage', 'lawyer', msg=l_('Only for admin or lawyer')) def _before(self, *args, **kw): tmpl_context.sidebar_section = "preconditions" simple = PreconditionSimpleController() advanced = PreconditionAdvancedController() @expose('ksweb.templates.precondition.index') @paginate('entities', items_per_page=int(tg.config.get('pagination.items_per_page'))) @validate({'workspace': CategoryExistValidator(required=True)}) def index(self, workspace, **kw): return dict( page='precondition-index', fields={ 'columns_name': [l_('Label'), l_('Type'), l_('Owner')], 'fields_name': ['title', 'type', 'owner'] }, entities=model.Precondition.precondition_available_for_user(request.identity['user']._id, workspace=workspace), actions_content=[l_('New Output'),l_('New Q/A')], workspace=workspace ) @expose('json') def sidebar_precondition(self, workspace): #pragma: no cover res = list(model.Precondition.query.aggregate([ { '$match': { '_owner': request.identity['user']._id, # 'visible': True '_category': ObjectId(workspace) } }, { '$group': { '_id': '$_category', 'precondition': {'$push': "$$ROOT",} } } ])) # Insert category name into res for e in res: e['category_name'] = model.Category.query.get(_id=ObjectId(e['_id'])).name return dict(precond=res) @expose('json') def available_preconditions(self, workspace=None): preconditions = Precondition.query.find({'_owner': request.identity['user']._id, 'visible': True, '_category': ObjectId(workspace)}).sort('title').all() return dict(preconditions=preconditions) @expose('json') @decode_params('json') @validate({ 'id': PreconditionExistValidator(required=True), }, error_handler=validation_errors_response) def qa_precondition(self, id, **kw): print(ObjectId(id)) precondition = model.Precondition.query.get(_id=ObjectId(id)) print(precondition.response_interested) return dict(qas=precondition.response_interested)
class OutputController(RestController): def _validate_precondition_with_qa(self, precondition, content): if not precondition: return dict(errors={'content': _('Filter not found')}) # Check content precondition element precond = model.Precondition.query.find({ '_id': ObjectId(precondition) }).first() related_qa = precond.response_interested # Check elem['content'] contain the obj id of the related for elem in content: if elem['type'] == 'qa_response': if elem['content'] not in related_qa.keys(): response.status_code = 412 return dict( errors={ 'content': _('The question %s is not related to the filter') % elem['title'] }) return dict() def _before(self, *args, **kw): tmpl_context.sidebar_section = "outputs" tmpl_context.id_obj = kw.get('_id') allow_only = predicates.has_any_permission( 'manage', 'lawyer', msg=l_('Only for admin or lawyer')) @expose('ksweb.templates.output.index') @paginate('entities', items_per_page=int(tg.config.get('pagination.items_per_page'))) @validate({'workspace': CategoryExistValidator(required=True)}) def get_all(self, workspace, **kw): return dict(page='output-index', fields={ 'columns_name': [_('Label'), _('Filter'), _('Content')], 'fields_name': ['title', 'precondition', 'content'] }, entities=model.Output.output_available_for_user( request.identity['user']._id, workspace), actions=False, workspace=workspace) @expose('json') @expose('ksweb.templates.output.new') @validate({'workspace': CategoryExistValidator(required=True)}) def new(self, workspace, **kw): tmpl_context.sidebar_output = "output-new" return dict(output={'_precondition': kw.get('precondition_id', None)}, workspace=workspace, errors=None) @decode_params('json') @expose('json') @validate( { 'title': StringLengthValidator(min=2), 'content': OutputContentValidator(), 'ks_editor': StringLengthValidator(min=2), 'category': CategoryExistValidator(required=True), 'precondition': PreconditionExistValidator(), }, error_handler=validation_errors_response) def post(self, title, content, category, precondition, **kw): content = content or [] # Check content precondition element error = self._validate_precondition_with_qa(precondition, content) if error: return error user = request.identity['user'] model.Output(_owner=user._id, _category=ObjectId(category), _precondition=ObjectId(precondition), title=title, content=content, public=True, visible=True, html=kw['ks_editor']) return dict(errors=None) @expose('json') @decode_params('json') @validate( { '_id': OutputExistValidator(required=True), 'title': StringLengthValidator(min=2), 'content': OutputContentValidator(), 'category': CategoryExistValidator(required=True), 'precondition': PreconditionExistValidator(), }, error_handler=validation_errors_response) @require( CanManageEntityOwner( msg=l_(u'You are not allowed to edit this output.'), field='_id', entity_model=model.Output)) def put(self, _id, title, content, category, precondition, **kw): content = content or [] # Check content precondition element error = self._validate_precondition_with_qa(precondition, content) if error: return error check = self.get_related_entities(_id) if check.get("entities"): entity = dict(_id=_id, title=title, content=content, _category=category, _precondition=precondition, entity='output', html=kw['ks_editor']) session[ 'entity'] = entity # overwrite always same key for avoiding conflicts session.save() return dict(redirect_url=tg.url('/resolve', params=dict(workspace=category))) output = model.Output.query.find({'_id': ObjectId(_id)}).first() output.title = title output._category = ObjectId(category) output._precondition = ObjectId(precondition) output.content = content output.html = kw['ks_editor'] return dict(errors=None, redirect_url=None) @expose('ksweb.templates.output.new') @validate( { '_id': OutputExistValidator(required=True), 'workspace': CategoryExistValidator(required=True), }, error_handler=validation_errors_response) @require( CanManageEntityOwner( msg=l_(u'You are not allowed to edit this output.'), field='_id', entity_model=model.Output)) def edit(self, _id, workspace, **kw): output = model.Output.query.find({ '_id': ObjectId(_id), '_category': ObjectId(workspace) }).first() tmpl_context.sidebar_output = "output-edit" return dict(output=output, workspace=workspace, errors=None) @expose('json') def sidebar_output(self, _id=None, workspace=None): #pragma: no cover res = list( model.Output.query.aggregate([{ '$match': { '_owner': request.identity['user']._id, '_id': { '$ne': ObjectId(_id) }, 'visible': True, '_category': ObjectId(workspace) } }, { '$group': { '_id': '$_category', 'output': { '$push': "$$ROOT", } } }])) # Insert category name into res for e in res: e['category_name'] = model.Category.query.get( _id=ObjectId(e['_id'])).name return dict(outputs=res) @expose('json') @decode_params('json') @validate({ '_id': OutputExistValidator(required=True), }, error_handler=validation_errors_response) def human_readable_details(self, _id, **kw): output = model.Output.query.get(_id=ObjectId(_id)) return dict( output={ '_id': output._id, 'title': output.title, 'content': output.human_readbale_content, 'human_readbale_content': output.human_readbale_content, '_owner': output._owner, 'owner': output.owner.display_name, '_precondition': output._precondition, 'precondition': output.precondition.title, '_category': output._category, 'category': output.category.name, 'public': output.public, 'visible': output.visible, 'created_at': output.created_at }) @decode_params('json') @expose('json') def get_related_entities(self, _id): """ This method return ALL entities (Output, Document) that have inside a `content.content` the given _id :param _id: :return: """ output_related = model.Output.query.find({ "content.type": "output", "content.content": _id }).all() documents_related = model.Document.query.find({ "content.type": "output", "content.content": _id }).all() entities = list(output_related + documents_related) return dict(entities=entities, len=len(entities))
class PreconditionController(BaseController): allow_only = predicates.has_any_permission('manage', 'lawyer', msg=l_('Only for admin or lawyer')) def _before(self, *args, **kw): tmpl_context.sidebar_section = "preconditions" simple = PreconditionSimpleController() advanced = PreconditionAdvancedController() @expose('ksweb.templates.precondition.index') @paginate('entities', items_per_page=int(tg.config.get('pagination.items_per_page'))) @validate({'workspace': WorkspaceExistValidator(required=True)}) def index(self, workspace, **kw): return dict( page='precondition-index', fields={ 'columns_name': [l_('Label'), l_('Type'), l_('Owner'), l_('Id')], 'fields_name': 'title type owner hash'.split() }, entities=Precondition.available_for_user(request.identity['user']._id, workspace=workspace), actions_content=[l_('New Output'),l_('New QA')], workspace=workspace ) @expose('json') def sidebar_precondition(self, workspace): # pragma: no cover res = list(Precondition.query.aggregate([ { '$match': { '_owner': request.identity['user']._id, '_workspace': ObjectId(workspace) } }, { '$group': { '_id': '$_workspace', 'precondition': {'$push': "$$ROOT", } } } ])) # Insert workspace name into res for e in res: e['workspace_name'] = Workspace.query.get(_id=ObjectId(e['_id'])).name return dict(precond=res) @expose('json') def available_preconditions(self, workspace=None): preconditions = Precondition.available_for_user(request.identity['user']._id, workspace=workspace).all() return dict(preconditions=preconditions) @expose('json') @decode_params('json') @validate({ 'id': PreconditionExistValidator(required=True), }, error_handler=validation_errors_response) def qa_precondition(self, id, **kw): precondition = Precondition.query.get(_id=ObjectId(id)) return dict(qas=precondition.response_interested) @expose('json') @validate({'workspace': WorkspaceExistValidator(required=True)}) def mark_as_read(self, workspace): Precondition.mark_as_read(request.identity['user']._id, workspace) @expose('json') def open(self, _id): if not _id: tg.flash('The precondition you are looking for, does not exist') redirect() p = Precondition.query.get(_id=ObjectId(_id)) redirect('/%s/edit' % (p.entity), params=dict(_id=p._id, workspace=p._workspace))