<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.website.models import website
from openerp import SUPERUSER_ID

import werkzeug
import json
import logging
import re

_logger = logging.getLogger(__name__)


class WebsiteSurvey(http.Controller):

    # Survey list
    @website.route(['/survey/',
        '/survey/list/'],
        type='http', auth='public', multilang=True)
    def list_surveys(self, **post):
        '''Lists all the public surveys'''
        cr, uid, context = request.cr, request.uid, request.context
        survey_obj = request.registry['survey.survey']
        survey_ids = survey_obj.search(cr, uid, [('state', '=', 'open'),
                                                ('page_ids', '!=', 'None')],
            context=context)
        surveys = survey_obj.browse(cr, uid, survey_ids, context=context)
        return request.website.render('survey.list', {'surveys': surveys})

    # Survey displaying
    @website.route(['/survey/fill/<model("survey.survey"):survey>',
        '/survey/fill/<model("survey.survey"):survey>/<string:token>'],
        type='http', auth='public', multilang=True)
    def fill_survey(self, survey, token=None, **post):
        '''Display and validates a survey'''
        cr, uid, context = request.cr, request.uid, request.context
        survey_obj = request.registry['survey.survey']
        user_input_obj = request.registry['survey.user_input']

        # In case of bad survey, redirect to surveys list
        if survey_obj.exists(cr, uid, survey.id, context=context) == []:
            return werkzeug.utils.redirect("/survey/")

        # In case of auth required, block public user
        if survey.auth_required and uid == request.registry['website'].get_public_user(request.cr, SUPERUSER_ID, request.context).id:
            return request.website.render("website.401")

        # In case of non open surveys
        if survey.state != 'open':
                return request.website.render("survey.notopen")

        # If enough surveys completed
        if survey.user_input_limit > 0:
            completed = user_input_obj.search(cr, SUPERUSER_ID, [('state', '=', 'done')], count=True)
            if completed >= survey.user_input_limit:
                return request.website.render("survey.notopen")

        # Manual surveying
        if not token:
            if survey.visible_to_user:
                user_input_id = user_input_obj.create(cr, uid, {'survey_id': survey.id})
                user_input = user_input_obj.browse(cr, uid, [user_input_id], context=context)[0]
            else:  # An user cannot open hidden surveys without token
                return request.website.render("website.403")

        # if not auth_required and not token:
        #   create un token et un user input
        #   page = précédente + 1
        # if token:
        #   calculer la prochaine page à visiter



        _logger.debug('Incoming data: %s', post)

        # Display success message if totally succeeded
        if post and post['next'] == "finished":
            return request.website.render('survey.finished', {'survey': survey})

        # Page selection
        pagination = {'current': -1, 'next': 0}
        # Default pagination if first opening

        if 'current' in post and 'next' in post and post['next'] != "finished":
            oldnext = int(post['next'])
            if oldnext not in range(0, len(survey.page_ids)):
                raise Exception("This page does not exist")
            else:
                pagination['current'] = oldnext
            if oldnext == len(survey.page_ids) - 1:
                pagination['next'] = 'finished'
            else:
                pagination['next'] = oldnext + 1

        return request.website.render('survey.survey',
                                    {'survey': survey,
                                    'pagination': pagination})

    # @website.route(['/survey/prefill/<model("survey.survey"):survey>'], type='json', auth='public', multilang=True):

    # @website.route(['/survey/validate/<model("survey.survey"):survey>'],
    #                 type='json', auth='public', multilang=True)
    # def validate(self, survey=None, **post):
    #     # for each {K:V} in post, check
    #     _logger.debug("Incoming json data: " + post.__str__())
    #     return {'valid': True, 'errors': None}

    @website.route(['/survey/submit/<model("survey.survey"):survey>'],
                    type='http', auth='public', multilang=True)
    def submit(self, survey, **post):
        _logger.debug('Incoming data: %s', post)
        page_nr = int(post['current'])
        questions = survey.page_ids[page_nr].question_ids

        errors = {}
        for question in questions:
            answer_tag = "%s_%s_%s" % (survey.id, page_nr, question.id)
            errors.update(self.validate_question(survey.id, page_nr, question, post, answer_tag))

        ret = {}
        if (len(errors) != 0):
            ret['errors'] = errors
        else:<commit_msg>[IMP] User input record selection<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.addons.web import http
from openerp.addons.web.http import request
from openerp.addons.website.models import website
from openerp import SUPERUSER_ID

import werkzeug
import json
import logging
import re

_logger = logging.getLogger(__name__)


class WebsiteSurvey(http.Controller):

    # Survey list
    @website.route(['/survey/',
        '/survey/list/'],
        type='http', auth='public', multilang=True)
    def list_surveys(self, **post):
        '''Lists all the public surveys'''
        cr, uid, context = request.cr, request.uid, request.context
        survey_obj = request.registry['survey.survey']
        survey_ids = survey_obj.search(cr, uid, [('state', '=', 'open'),
                                                ('page_ids', '!=', 'None')],
            context=context)
        surveys = survey_obj.browse(cr, uid, survey_ids, context=context)
        return request.website.render('survey.list', {'surveys': surveys})

    # Survey displaying
    @website.route(['/survey/fill/<model("survey.survey"):survey>',
        '/survey/fill/<model("survey.survey"):survey>/<string:token>'],
        type='http', auth='public', multilang=True)
    def fill_survey(self, survey, token=None, **post):
        '''Display and validates a survey'''
        cr, uid, context = request.cr, request.uid, request.context
        survey_obj = request.registry['survey.survey']
        user_input_obj = request.registry['survey.user_input']

        # In case of bad survey, redirect to surveys list
        if survey_obj.exists(cr, uid, survey.id, context=context) == []:
            return werkzeug.utils.redirect("/survey/")

        # In case of auth required, block public user
        if survey.auth_required and uid == request.registry['website'].get_public_user(request.cr, SUPERUSER_ID, request.context).id:
            return request.website.render("website.401")

        # In case of non open surveys
        if survey.state != 'open':
                return request.website.render("survey.notopen")

        # If enough surveys completed
        if survey.user_input_limit > 0:
            completed = user_input_obj.search(cr, uid, [('state', '=', 'done')], count=True)
            if completed >= survey.user_input_limit:
                return request.website.render("survey.notopen")

        # Manual surveying
        if not token:
            if survey.visible_to_user:
                user_input_id = user_input_obj.create(cr, uid, {'survey_id': survey.id})
                user_input = user_input_obj.browse(cr, uid, [user_input_id], context=context)[0]
            else:  # An user cannot open hidden surveys without token
                return request.website.render("website.403")
        else:
            user_input_id = user_input_obj.search(cr, uid, [('token', '=', token)])[0]
            user_input = user_input_obj.browse(cr, uid, [user_input_id], context=context)[0]

        _logger.debug('Incoming data: %s', post)

        # if user input.state = new => page -1
        # sinon, chercher la dernière page sur laquelle on a des infos enregistrées
        # si c'est la dernière, afficher la page de conclusion

        # Display success message if totally succeeded
        if post and post['next'] == "finished":
            return request.website.render('survey.finished', {'survey': survey})

        # Page selection
        pagination = {'current': -1, 'next': 0}
        # Default pagination if first opening

        if 'current' in post and 'next' in post and post['next'] != "finished":
            oldnext = int(post['next'])
            if oldnext not in range(0, len(survey.page_ids)):
                raise Exception("This page does not exist")
            else:
                pagination['current'] = oldnext
            if oldnext == len(survey.page_ids) - 1:
                pagination['next'] = 'finished'
            else:
                pagination['next'] = oldnext + 1

        return request.website.render('survey.survey',
                                    {'survey': survey,
                                    'pagination': pagination,
                                    'token': user_input.token})

    # @website.route(['/survey/prefill/<model("survey.survey"):survey>'], type='json', auth='public', multilang=True):

    # @website.route(['/survey/validate/<model("survey.survey"):survey>'],
    #                 type='json', auth='public', multilang=True)
    # def validate(self, survey=None, **post):
    #     # for each {K:V} in post, check
    #     _logger.debug("Incoming json data: " + post.__str__())
    #     return {'valid': True, 'errors': None}

    @website.route(['/survey/submit/<model("survey.survey"):survey>'],
                    type='http', auth='public', multilang=True)
    def submit(self, survey, **post):
        _logger.debug('Incoming data: %s', post)
        page_nr = int(post['current'])
        questions = survey.page_ids[page_nr].question_ids

        errors = {}
        for question in questions:
            answer_tag = "%s_%s_%s" % (survey.id, page_nr, question.id)
            errors.update(self.validate_question(survey.id, page_nr, question, post, answer_tag))

        ret = {}
        if (len(errors) != 0):
            ret['errors'] = errors
        else:
{'fraction_non_alphanumeric': 0.1476905684754522, 'fraction_numerical': 0.0035529715762273903, 'mean_word_length': 2.607631808913487, 'pattern_counts': {'":': 4, '<': 19, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7299006', 'n_tokens_mistral': 3576, 'n_tokens_neox': 3428, 'n_words': 951}