Exemple #1
0
    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))
Exemple #2
0
 def _create_category(self, name, visible=True):
     c = model.Category(
         name=name,
         visible=visible,
     )
     DBSession.flush(c)
     return c
Exemple #3
0
 def _create_workspace(self, name, visible=True):
     c = model.Workspace(
         name=name,
         visible=visible,
     )
     DBSession.flush(c)
     return c
Exemple #4
0
    def previous_question(self, _id=None, **kwargs):
        questionary = model.Questionary.query.get(_id=ObjectId(_id))
        previous_response = {}

        if questionary.qa_values:
            last_order_number = max([
                questionary.qa_values[qa_val]["order_number"]
                for qa_val in questionary.qa_values
            ])
            last_question_answered = [
                qa_val for qa_val in questionary.qa_values
                if questionary.qa_values[qa_val]["order_number"] ==
                last_order_number
            ][0]
            previous_response = questionary.qa_values[last_question_answered][
                "qa_response"]
            questionary.qa_values.pop(last_question_answered, None)
            DBSession.flush_all()

        return dict(
            questionary=questionary,
            quest_compiled=questionary.evaluate_questionary,
            html=self.get_questionary_html(_id),
            previous_response=previous_response,
            recap=questionary.answers,
        )
Exemple #5
0
    def evaluate_expression(self, output_id):
        log.debug("evaluate_expression")

        expression = self.expressions[output_id]

        answers = dict()

        for _id, resp in self.qa_values.items():
            answer = resp['qa_response']
            if isinstance(answer, basestring):
                answers['q_' + _id] = answer
            else:
                # array
                answers['q_' + _id] = "[%s]" % ' ,'.join(map(lambda x: "'%s'" % x, answer))

        try:
            evaluation = eval(expression, answers)
        except NameError as ne:
            message = str(getattr(ne, 'message', ne))
            _id = message.split("'")[1][2:]
            return {
                'completed': False,
                'qa': _id
            }

        self.output_values[output_id] = {
            'evaluation': evaluation
        }

        DBSession.flush_all()

        return {
            'completed': True
        }
Exemple #6
0
    def test_document_content_validator(self):
        with test_context(self.app):
            model.Output(
                title="FakeOutput",
                content="Content of the fake output",
                html='',
                _owner=self._get_user('*****@*****.**')._id,
                _category=self._get_category('Area 1')._id,
                _precondition=None,
            )
            DBSession.flush()
            output = model.Output.query.get(title="FakeOutput")

            validator = DocumentContentValidator()
            try:
                res = validator._validate_python([
                    {
                        'type': "output",
                        'content': str(output._id),
                        'title': output.title
                    },
                ])
            except ValidationError:
                assert False
            else:
                assert True
Exemple #7
0
    def test_invisble_workspaces(self):
        iw = Workspace(name="invisible", visible=False)
        DBSession.flush(iw)

        self._login_lawyer()
        resp = self.app.get('/workspace/get_all')
        w = self._get_workspace('invisible')
        assert str(w._id) not in resp
Exemple #8
0
 def setUp(self):
     """Setup test fixture for each functional test method."""
     self.app = load_app(self.application_under_test)
     setup_app()
     w = model.Workspace(name="Area 1", visible=True)
     w2 = model.Workspace(name="Area 2", visible=True)
     DBSession.flush(w)
     DBSession.flush(w2)
Exemple #9
0
 def update_dependencies(self, old):
     from ksweb.model import Output
     outputs = Output.query.find({'$text': {'$search': old}}).all()
     for o in outputs:
         old_hash = o.hash
         o.html = o.html.replace(old, self.hash)
         DBSession.flush(o)
         o.update_dependencies(old_hash)
     self.generate_output_from()
Exemple #10
0
 def update_dependencies(self, old):
     from ksweb.model import Output
     from ksweb.model import Document
     outputs = Output.query.find({'$text': {'$search': old}}).all()
     documents = Document.query.find({'$text': {'$search': old}}).all()
     for e in (outputs + documents):
         old_hash = e.hash
         e.html = e.html.replace(old, self.hash)
         DBSession.flush(e)
         e.update_dependencies(old_hash)
Exemple #11
0
 def __upsert_document(self, cls, _id, body):
     filter_out = ['_id', 'entity', 'auto_generated', 'status', 'hash']
     body = {k: v for k, v in body.items() if k not in filter_out}
     found = self.__find_stored_entity(cls, _id, body)
     if found:
         return found
     body.update(self.__new_properties)
     inserted = cls(**body)
     DBSession.flush(inserted)
     return self.__add_to_conversion_table(_id, inserted)
Exemple #12
0
    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)
Exemple #13
0
    def upsert(cls, find, replace):
        # find_and_modify or other methods does not work for ming mapper extensions
        # so this is an artisan upsert implementation with instant flushes out of uow
        found = cls.query.get(**find)
        if not found:
            o = cls(**replace)
            DBSession.flush(o)
            return o

        for k, v in replace.items():
            found[k] = v
        DBSession.flush(found)
        return found
Exemple #14
0
 def test_output_exist_validator(self):
     model.Output(title="Fake_output",
                  html='',
                  _owner=self._get_user('*****@*****.**')._id,
                  _workspace=self._get_workspace('Area 1')._id,
                  _precondition=None)
     DBSession.flush()
     output = model.Output.query.get(title="Fake_output")
     validator = OutputExistValidator()
     try:
         res = validator._validate_python(str(output._id))
     except ValidationError:
         assert False
     else:
         assert True
Exemple #15
0
 def test_document_exist_validator(self):
     model.Document(_owner=self._get_user('*****@*****.**')._id,
                    _workspace=self._get_workspace('Area 1')._id,
                    title="Titolone",
                    html='',
                    public=True,
                    visible=True)
     DBSession.flush()
     document = model.Document.query.get(title="Titolone")
     validator = DocumentExistValidator()
     try:
         res = validator._validate_python(str(document._id))
     except ValidationError:
         assert False
     else:
         assert True
Exemple #16
0
    def _original_edit(self):
        params = session.get('entity')
        params['_workspace'] = to_object_id(params.get('_workspace'))
        params['_precondition'] = to_object_id(params.get('_precondition'))
        entity = entity_from_id(params['_id'])
        if (type(entity) is model.Precondition):
            if entity.is_advanced:
                params['condition'] = [to_object_id(__) if __ not in model.Precondition.PRECONDITION_OPERATOR else __ for __ in params['condition'] ]
            else:
                params['condition'][0] = ObjectId(params['condition'][0])

        old_hash = entity['hash']
        params.pop('entity', None)
        for k, v in params.items():
            setattr(entity, k, v)
        DBSession.flush(entity)
        entity.update_dependencies(old_hash)
        return entity
Exemple #17
0
    def test_document_content_validator(self):
        with test_context(self.app):
            model.Output(
                title="FakeOutput",
                html='',
                _owner=self._get_user('*****@*****.**')._id,
                _workspace=self._get_workspace('Area 1')._id,
                _precondition=None,
            )
            DBSession.flush()
            output = model.Output.query.get(title="FakeOutput")

            validator = DocumentContentValidator()
            try:
                res = validator._validate_python('#{%s}' % str(output.hash))
            except ValidationError:
                assert False
            else:
                assert True
Exemple #18
0
 def test_upsert_document(self):
     inserted = upsert_document(
         cls=model.Qa,
         _owner=ObjectId(self._get_user('*****@*****.**')._id),
         _workspace=ObjectId(self.ws._id),
         _parent_precondition=None,
         title='title 4',
         question='question',
         tooltip='tooltip',
         link='link',
         type='text',
         answers=['answers'],
         public=True,
         visible=True)
     DBSession.flush_all()
     assert isinstance(inserted, Qa), type(inserted)
     fetched = Qa.query.find({'title': 'title 4'}).all()
     assert inserted in fetched, fetched
     qas = model.Qa.query.find().all()
     assert len(qas) == 3, qas
Exemple #19
0
    def post(self, highlighted_text=u"", workspace=None, list_=[]):
        first_5_words = u" ".join(highlighted_text.split())
        title = u" ".join(first_5_words.split(" ")[:5])
        user = request.identity["user"]
        output = Output(
            _owner=user._id,
            _workspace=workspace,
            title=title,
            public=True,
            visible=True,
            html=highlighted_text,
            auto_generated=True,
            status=Output.STATUS.UNREAD,
        )
        for o in list_:
            m = entity_from_id(_id=ObjectId(o[2:-1]))
            output.insert_content(m)

        DBSession.flush(output)

        return dict(_id=str(output._id), title=title, hash=output.hash)
Exemple #20
0
    def responde(self, _id=None, qa_id=None, qa_response=None, **kwargs):
        questionary = model.Questionary.query.get(_id=ObjectId(_id))
        #  Check if the qa response is valid
        qa = model.Qa.query.get(_id=ObjectId(qa_id))
        if qa.type == "single" and not qa_response in qa.answers:
            response.status_code = 412
            return dict(errors={'qa_response': _('Invalid answer')})

        if qa.type == "multi":
            #  check each qa_response if is in qa.answers
            if isinstance(qa_response, basestring):
                qa_response = [qa_response]

                # This comment is needed for to allow users to 'not response' a question
                # For disable this, just uncomment followings rows

                # for elem in qa_response:
                #     if not elem in qa.answers:
                #         response.status_code = 412
                #         return dict(errors={'qa_response': _('Invalid answer')})

        if not questionary.qa_values:
            order_number = 0
        else:
            order_number = max([
                questionary.qa_values[elem]['order_number']
                for elem in questionary.qa_values
            ]) + 1
        questionary.qa_values[qa_id] = {
            'qa_response': qa_response,
            'order_number': order_number
        }

        # Not sure about flush here
        DBSession.flush(questionary)
        quest_compiled = questionary.evaluate_questionary

        return dict(questionary=questionary,
                    quest_compiled=quest_compiled,
                    html=self.get_questionary_html(_id))
Exemple #21
0
 def evolve(self):
     collection = mapper(Workspace).collection
     DBSession.drop_indexes(collection)
     DBSession.ensure_indexes(collection)
     DBSession.flush_all()
Exemple #22
0
 def evolve(self):
     collection = mapper(Category).collection
     DBSession.drop_indexes(collection)
     DBSession.ensure_indexes(collection)
     DBSession.flush_all()