Example #1
0
def add(request):
    '''
    新增反馈信息
    '''    
    if request.POST:
        
        title = request.POST.get('title', None)
        content = request.POST.get('content', None)         
        
        feedbacks = Feedback.objects.filter(title__iexact=title)
        if feedbacks: 
            return HttpResponse(simplejson.dumps({"statusCode": 400,
                                                  "message": u'此主题的反馈信息已存在,请查看'}),
                                mimetype='application/json')
        
        feedback = Feedback(title=title, content=content,
                            reporter=request.user.userprofile.realname)    
        feedback.save()
        # 发送邮件安
        email_content = render_to_string('feedback/to_IT_email.html',
                                         {'feedback': feedback})
        
        send_mail(u'IT总监绿色通道', settings.IT_HEAD_EMAIL, u'反馈信息提醒', email_content)    
        
        Log(username=request.user.username,
            content=u'新增反馈信息:‘' + title + u'’。',
            level=1).save()
        return HttpResponse(simplejson.dumps({'statusCode': 200,
                                              'url': '/feedback/index',
                                              'message': u'反馈信息‘' + title + u'’添加成功'}),
                            mimetype='application/json')
    return render_to_response('feedback/add.html',
                              context_instance=RequestContext(request))
Example #2
0
def activate_feedback(request, coursefaculty_id):
    if request.method == 'POST':
        temp=CourseFacultyLink.objects.get(id=coursefaculty_id)
        form = forms.CourseFacultyFeedbackForm(request.POST, instance=temp)
        if form.is_valid():
            tempform=form.save(commit=False)
            tempform.mid_design_value=0
            tempform.mid_instructor_value=0
            tempform.mid_tutorial_value=0
            tempform.mid_exam_value=0
            tempform.save()
            admin=User.objects.get(username='******')
            course=temp.course
            if temp.create == 0:
                for i in CourseStudentLink.objects.all():
                    if course.name==i.course.name:
                        feedback=Feedback(student=i.student,coursefaculty=temp)
                        feedback.save()
            temp.create=1
            temp.save()
            post_desc="There is an update in feedback"+" to "+str(temp.faculty)+" for this course."
            post=Post(student=admin.student,post=post_desc,course=course)
            post.save()
            coursefaculty=CourseFacultyLink.objects.all()
            # return HttpResponse("Yahooooo!")
            return render_to_response("feedback/home.html", {'coursefaculty':coursefaculty,},context_instance=RequestContext(request))
    else: 
        temp=CourseFacultyLink.objects.get(id=coursefaculty_id)
        form = forms.CourseFacultyFeedbackForm(instance=temp)

    return render_to_response("feedback/feedback.html", {'id':coursefaculty_id,'form':form,'temp':temp}, context_instance=RequestContext(request))
Example #3
0
def giveFeedback(request):
    if request.method == 'POST':
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        message = request.POST['message']
        feed = Feedback(name=name, email=email, phone=phone, message=message)
        feed.save()
        return redirect('home')
Example #4
0
def convert_to_feedback(request, e_id):
    email = get_object_or_404(Email, pk=e_id)
    if email.subject not in ('', None):
        title = email.subject
    else:
        title = email.body[:20]

    new = Feedback(title=title, description=email.body, method='email')
    new.save()
    email.feedback = new
    email.save()
    return redirect('edit_feedback', f_id=new.id)
Example #5
0
def feedback(request):
    request.POST = json.loads(request.body.decode('utf-8'))

    #Each feedback should be no longer than 500 letters, or it will be truncated.
    feedback_info = request.POST['feedback'].strip()[:500]
    if len(feedback_info) == 0:
        return JsonResponse(
            get_json_dict(data={}, err_code=-1, message="Empty Feedback"))
    else:
        feedback = Feedback(feedback=feedback_info)
        feedback.save()
        return JsonResponse(
            get_json_dict(data={}, err_code=0, message="Feedback Success"))
Example #6
0
def feedback(request):
    status = 405
    if request.is_ajax() and request.method == 'POST':
        status = 200
        feedback_message = request.POST['message']
        feedback_owner = request.user
        new_feedback = Feedback()
        new_feedback.message = feedback_message
        if request.user.is_authenticated():
            new_feedback.owner = request.user
        new_feedback.save()
        
    return HttpResponse(status=status)            
Example #7
0
def submit():
    form = FeedbackForm(request.form)
    if form.validate_on_submit():
        data = form.data
        feedback = Feedback(data['customer_name'], data['dealer'],
                            data['rating'], data['comments'])
        db.session.add(feedback)
        db.session.commit()
        feedback.send_email()
        flash('Your feedback was succesfully submitted')
        return redirect(url_for('main.success'))
    else:
        flash(form.errors, 'error')
        return render_template('index.html', form=form)
Example #8
0
def feedback(request):
    status = 405
    response = {}
    if request.is_ajax() and request.method == "POST":
        status = 200
        feedback_message = request.POST["message"]
        feedback_owner = request.user
        new_feedback = Feedback()
        new_feedback.message = feedback_message
        if request.user.is_authenticated():
            new_feedback.owner = request.user
        new_feedback.save()

    return JsonResponse(response, status=status)
Example #9
0
def feedback_service(request):
    user = None
    try:
        user = Account.objects.get(id=request.session['user_id'])
    except:
        user = None
    content = request.POST.get('content', '')
    if not content or len(content)>500:
        return HttpResponse('false')

    feedback = Feedback(user=user,user_content=content)
    feedback.save()

    return HttpResponse('true')
Example #10
0
 def save(self):
     feedback = Feedback()
     feedback.save()
     for key, value in self.cleaned_data.items():
         if not key.startswith("question_"): 
             continue
         q_id = key.split("_")[1]
         question = Question.objects.get(id=q_id)
         response = Response(feedback=feedback, question=question)
         if question.qtype == 1:
             response.text = value
         elif question.qtype == 2:
             response.selected = value
         response.save()
Example #11
0
def add(request):
    name = 'Kim'
    email = '*****@*****.**'
    comment = 'Hello'

    name = request.GET.get('name')
    email = request.GET.get('email')
    comment = request.GET.get('comment')

    fb = Feedback(name=name,
                  email=email,
                  comment=comment,
                  createDate=datetime.now())
    fb.save()
    return HttpResponse("<h1>Add!</h1>")
Example #12
0
def feedback_page(request, feedback_page_template):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            message = request.POST['message']
            feedback = Feedback()            
            feedback.message = message
            feedback.demo = request.user
            feedback.save()
            logout(request)
            return render_to_response(feedback_page_template, locals())
        else:
            error = u'Your feedback is important to us !!'
            return render_to_response(feedback_page_template, locals())
    return render_to_response(feedback_page_template, locals())
 def test_feedback_product_name_str_test(self):
     test_feedback = Feedback(product_name="test",
                              user_feedback="good",
                              published_date="2020-05-06",
                              ratings='4',
                              upvote=1)
     self.assertEqual(str(test_feedback.product_name), "test")
Example #14
0
def alice_skill(request):
    try:
        req_json = json.loads(request.body)
    except Exception:
        req_json = {'version': 1, 'session': 1}
    uid = req_json['session']['user_id']
    cmd = req_json['request']['command']
    if uid not in aliceSession:
        aliceSession[uid] = 0
    response = {
        "version": req_json['version'],
        "session": req_json['session'],
        "response": {
            "end_session": True,
            'text': 'Привет :D'
        }
    }
    if aliceSession[uid] == 0:
        # TODO: make it sound must better
        response['response']['text'] = 'Привет!'
        aliceSession[uid] += 1
    elif aliceSession[uid] == 1:
        if len(cmd) < 20:
            response['response'][
                'text'] = 'Очень мало слов. Текст должен быть более 20 символов'
        else:
            Feedback(text=cmd).save()
            response['response']['text'] = 'Спасибо за отзыв!'
            response['response']['end_session'] = True
    aliceSession[uid] = aliceSession[uid] % 2
    return JsonResponse(response, json_dumps_params={'ensure_ascii': False})
Example #15
0
def feedback_recently(request, page=None):
    if page is None:
        page = request.META['PATH_INFO']
    query = Feedback.all()
    if page != 'all':
        query.filter('page', page)
    query.order('-submitted')
    return render_query(request, query, 20 if page == 'all' else 10)
def home(request):
    #return HttpResponse('Home page')
    #return render(request,'homepage.html')
    courseCode = request.GET.get('code', '')
    request.session['q'] = [0, 0, 0, 0, 0, 0]
    # request.session['prn']=request.session['prn']
    # request.session['courseCode']=request.session['courseCode']
    feedbackObj = Feedback(prn=request.session['prn'],
                           courseCode=courseCode,
                           q1=request.session['q'][0],
                           q2=request.session['q'][1],
                           q3=request.session['q'][2],
                           q4=request.session['q'][3],
                           q5=request.session['q'][4],
                           q6=request.session['q'][5])
    feedbackObj.save()
    request.session['f_id'] = feedbackObj.id
    return render(request, 'index1.html')
Example #17
0
def feedback_popular(request, page=None):
    if page is None:
        page = request.META['PATH_INFO']
    feedback_list = []
    query = Feedback.all()
    if page != 'all':
        query.filter('page', page)
    query.order('-points')
    query.order('-submitted')
    return render_query(request, query, 20 if page == 'all' else 10)
def addfeedback(request):
    objlist = Feedback.objects.filter(sender_id=request.session["student"])
    if request.method == "POST":
        obj = Feedback()
        obj.sender_id = request.session["student"]
        obj.feedback = request.POST.get("feedback")
        obj.f_date = datetime.date.today()
        obj.save()
    return render(request,'feedback/addfeedbackstud.html')
Example #19
0
def feedback_recently(request):
    page = request.META["PATH_INFO"]
    feedback_list = []
    for feedback in Feedback.all().filter("page", page).order("-points").order("-submitted"):
        try:
            submitter = feedback.submitter  # Attempt to dereference.
            feedback_list.append(feedback)
        except datastore_errors.Error:
            pass  # Ignore feedback if the submitter doesn't exist.
    feedback_list
    already_voted = get_already_voted(request)
    return render_to_string("feedback/messages.html", locals())
Example #20
0
    def post(self, request, format=None):
        text = request.POST['text']
        if not text.strip():
            return Response('Please enter a comment in the box.')

        client = request.user.client
        feedback = Feedback(client=client, text=text, date=datetime.now())
        feedback.save()

        subject = "Feedback from %s %s" % (str(client), client.user.email)
        email_message = text

        send_queued_mail(subject,
                         email_message,
                         settings.SUPPORT_EMAIL, [settings.SUPPORT_EMAIL],
                         reply_to=client.user.email)

        return Response((
            "<img src='%s/healersource/img/hs_logo_stripe.png' style='float:left; margin-right: 8px;' />"
            "<p><strong><em>Thanks so much for your suggestions!</em></strong></p>"
            "<p>We're constantly working to make HealerSource the best possible experience for you, so your feedback is most appreciated. </p>"
        ) % settings.STATIC_URL)
Example #21
0
def send_feedback_view(request):
    if request.method == "POST":
        sender_email = request.POST['email']
        text = request.POST['text']
        feedback = Feedback()
        feedback.sender_email = sender_email
        feedback.text = text
        feedback.save()
    return redirect('index')
Example #22
0
def feedback(request):
    if request.method == 'POST':

        data = parse_qs(request.POST.get('request'))

        print('data', data['name'], data['comment'])

        author = data['name'][0] if 'name' in data else None
        phone = data['cell'][0] if 'cell' in data else None
        content = data['comment'][0] if 'comment' in data else None

        if not (author and content):
            return JsonResponse({'message': 'Invalid data'}, status=400)

        Feedback(author=author, phone=phone, content=content).save()

        return JsonResponse({'message': 'Success'})
    elif request.method == 'GET':

        feedbacks = Feedback.objects.all()

        socials = SocialSection.objects.all()

        output = []

        categoires = Category.objects.all()

        for category in categoires:
            products = Product.objects.filter(categories=category)
            output.append({
                'name': category.name,
                'slug': category.slug,
                'is_show': category.is_show,
            })

        shares = SharesSection.objects.all()

        content = {
            'output': output,
            'shares': shares,
            'socials': socials,
            'feedbacks': feedbacks
        }

        tempalte = 'page/feedback.html'

        return render(request, tempalte, content)
Example #23
0
def feedback(request):
    response = {}
    status = 200
    feedback_message = request.POST["message"]
    new_feedback = Feedback()
    new_feedback.message = feedback_message
    if request.user.is_authenticated:
        new_feedback.owner = request.user
    new_feedback.save()

    return JsonResponse(response, status=status)
Example #24
0
def feedback():
    form = feedbackForm()
    if form.validate_on_submit():
        record = Feedback.query.filter_by(customerName=form.customerName.data).first()
        if record is None:
            reqFeedback = Feedback(customerName=form.customerName.data, dealerName=form.dealerName.data,
                                   rating=form.ratingChoice.data, comments=form.comments.data)
            db.session.add(reqFeedback)
            db.session.commit()
            flash('Thank you for feedback!!', category='success')
            print(reqFeedback)
            sendMailOnSubmission(reqFeedback)
            return redirect(url_for('input.feedback'))
        else:
            flash('You have already provided your feedback. Thanks again!!', category='warning')
            return redirect(url_for('input.feedback'))
    return render_template('feedback.html', title='Feedback', form=form)
Example #25
0
def feedback(request):
    status = 405
    response = {}
    if request.is_ajax() and request.method == 'POST':
        status = 200
        feedback_message = request.POST['message']
        new_feedback = Feedback()
        new_feedback.message = feedback_message
        if request.user.is_authenticated:
            new_feedback.owner = request.user
        new_feedback.save()

    return JsonResponse(response, status=status)
Example #26
0
def feedback(request):
    status = 405
    if request.is_ajax() and request.method == 'POST':
        status = 200
        feedback_message = request.POST['message']
        feedback_owner = request.user
        new_feedback = Feedback()
        new_feedback.message = feedback_message
        if request.user.is_authenticated():
            new_feedback.owner = request.user
        new_feedback.save()

    return HttpResponse(status=status)
Example #27
0
def submitFeedback(request):
    d = {}

    try:
        if request.method == "POST":
            f = Feedback()
            f.email = request.POST['email']
            f.username = request.POST['name']
            f.message = request.POST['body']
            f.save()
            deliverEmail("feedbacksubject.html", "feedbackmessage.html",
                         {'f': f}, getAlumClubAdminEmail())

    except:
        d['error'] = "oops........some problem at the server end"

    json = simplejson.dumps(d)
    return HttpResponse(json)
Example #28
0
def eventDetailedView(request, event_id):

    is_signed_in = request.user.is_authenticated()
    is_admin = request.user.is_superuser
    myEvent = Event.objects.filter(id=event_id)
    available = myEvent.values_list('available_tickets')[0][0]
    username = request.user.username
    newType = myEvent.values_list('type')[0][0]
    rate = myEvent.values_list('rate')[0][0]
    notrate = 5-rate
    myEvent = myEvent[0]
    feedbacks = Feedback.objects.filter(event = myEvent).order_by('-id')
    counter = 0
    sum = 0
    for feed in feedbacks:
        counter+=1
        sum += feed.rate
        rate = (int) (sum / counter)


    if request.method == "POST":
        rate = request.POST.get("rate")
        comment = request.POST.get("comment")
        if comment == '':
            comment = None
        Event.objects.filter(id=event_id).update(rate=rate)
        rate = int(rate)
        if not is_admin:
            djuser=models.User.objects.filter(username=username)
            user1 = User.objects.filter(user=djuser)[0]
            feedback = Feedback(rate=rate,comment=comment,user=user1,event=myEvent)
            feedback.save()
        else:
            feedback = Feedback(rate=rate,comment=comment,user=None,event=myEvent)
            feedback.save()
        feedbacks = Feedback.objects.filter(event = myEvent).order_by('-id')
        print(feedbacks.values_list('comment'))
    return render(request, 'event.html', {
        'guest': not is_signed_in,
        'signed_in': is_signed_in,
        'admin': is_admin,
        'type':newType,
        'event': myEvent,
        'rate': range(rate),
        'notrange':range(notrate),
        'username':username,
        'comments': feedbacks,
        'tickets': available
        })
Example #29
0
def submitFeedback(request):
    d = {}
   

    try:
            if request.method == "POST" :                 
                f = Feedback()
                f.email = request.POST['email']
                f.username = request.POST['name']
                f.message = request.POST['body']
                f.save()
                deliverEmail("feedbacksubject.html","feedbackmessage.html",{'f':f},getAlumClubAdminEmail())
               
    except:
        d['error'] = "oops........some problem at the server end"
    
    json = simplejson.dumps(d)
    return HttpResponse(json)  
Example #30
0
    def process(self, request):
        resp = Response()
        email = request.POST.get('email', None)
        from_page = request.POST.get('from_page', None)
        feedback = request.POST.get('feedback', None)

        if feedback is not None:
            f = Feedback(text=feedback)
            if email is not None:
                f.email = email
            if from_page is not None:
                try:
                    f.from_page = Page.objects.get(pk=int(from_page))
                except ValueError:
                    return resp.set_error(ApiError.INCORRECT_POST_FIELD)
                except ObjectDoesNotExist:
                    # id == 0 - Home Screen
                    pass
            f.save()
            return resp.set_ok()
        else:
            return resp.set_error(ApiError.MISSING_POST_FIELD)
Example #31
0
def index( request ):
  #checking to see if the form has been submitted
  if request.method == 'POST':
    try:
      form = ContactForm(request.POST)
      if form.is_valid():
        cd = form.cleaned_data
        #message
        message = u'Name: ' + cd['name'] + '\r\n'
        message += u'Address: ' + cd['address'] +'\r\n'
        message += u'City: ' + cd['city'] +'\r\n'
        message += u'State: ' + cd['state'] +'\r\n'
        message += u'Zip Code: ' + cd['zip_code'] +'\r\n'
        message += u'Email: ' + cd['email'] +'\r\n'
        message += u'Phone Number: ' + cd['phone_number'] +'\r\n'
        message += u'Feedback Type: ' + cd['feedback_type'] + '\r\n'
        message += u'Message: '
        #converting unicode characters to ascii. hopefully.
        message += cd['message']
        message += u'\r\n\r\n\r\nDebug Information\r\rUser Agent: ' + request.META['HTTP_USER_AGENT'] +'\r\n' 
        message += u'IP Address: ' + request.META['REMOTE_ADDR'] +'\r\n' 
        message += u'Referer: ' + request.META['HTTP_REFERER'] +'\r\n'
        message += u'Number of Words: ' + str( len(cd['message'].split()) ) +'\r\n'
        message += u'COPPA: ' + cd['coppa'] +'\r\n'
        #saving feedback in the database
        feedback = Feedback()
        feedback.feedback_type = cd['feedback_type']
        feedback.name = cd['name']
        feedback.address = cd['address']
        feedback.city = cd['city']
        feedback.state = cd['state']
        feedback.zip_code = cd['zip_code']
        feedback.phone_number = cd['phone_number']
        feedback.email = cd['email']
        feedback.message = message
        #saving the feedback
        feedback.save()

        #setting where the email goes
        #by default everything goes to letters UNLESS specified
        to = "*****@*****.**"
        feedback_type = cd["feedback_type"]
        if feedback_type == "feedback" or feedback_type == "other":
          to = "*****@*****.**"
        elif feedback_type == "story_idea" or feedback_type == "press_release" or feedback_type == "you_asked":
          to = "*****@*****.**"

        if feedback_type == 'letter_to_editor':
          feedback_type_text = 'Letter To The Editor'
        elif feedback_type == 'voice_of_day':
          feedback_type_text = 'Voice of the Day'
        elif feedback_type == 'to_the_point':
          feedback_type_text = 'To The Point'
        elif feedback_type == 'rose_thorn':
          feedback_type_text = 'Roses and Thorn'
        elif feedback_type == 'feedback':
          feedback_type_text = 'Story Feedback'
        elif feedback_type == 'story_idea':
          feedback_type_text = 'Story Idea'
        elif feedback_type == 'press_release':
          feedback_type_text = 'Press Release'
        elif feedback_type == 'you_asked':
          feedback_type_text = 'You Asked'
        elif feedback_type == 'other':
          feedback_type_text = 'Other'

        #sending the email
        send_mail(
            'News-Leader.com ' + feedback_type_text + ' Submission: ' + str(cd['name']),
            message,
            '*****@*****.**',
            #['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**'],
            [to,'*****@*****.**','*****@*****.**',],
            )

        #secondary message to the user without the debug
        message = u'Thank you for submitting your feedback. It has been sent to editors for evaluation.\r\n'
        message += u'Below is a copy for your records:\r\n'
        message += u'Name: ' + cd['name'] + '\r\n'
        message += u'Address: ' + cd['address'] +'\r\n'
        message += u'City: ' + cd['city'] +'\r\n'
        message += u'State: ' + cd['state'] +'\r\n'
        message += u'Zip Code: ' + cd['zip_code'] +'\r\n'
        message += u'Email: ' + cd['email'] +'\r\n'
        message += u'Phone Number: ' + cd['phone_number'] +'\r\n'
        message += u'Message: '
        #converting unicode to ascii, hopefully
        message += cd['message']

        send_mail(
            'News-Leader ' + feedback_type_text + ' Submission: ' + str(cd['name']),
            message,
            '*****@*****.**',
            [cd['email'],],
            )


        return HttpResponseRedirect('/feedback/thanks')
    except:
      #there was an error.. send to the error page.
      return HttpResponseRedirect('/feedback/error')
  else:
    #first submission of the form
    feedback_type= "letter_to_editor"
    if 'feedback_type' in request.GET.keys():
      feedback_type = request.GET['feedback_type']
    form = ContactForm(initial={'state':'MO','feedback_type': feedback_type})
  return render_to_response('feedback/feedback.html', {'form': form},context_instance = RequestContext(request))
Example #32
0
		projects = Project.objects.all()
	except Exception, e:
		print e
	try:
		feedback = SignedFeedback.objects.all()
	except Exception, e:
		print e
	return render_to_response('feedback/signed_all.html', {'projects': projects, 'signed': feedback}, context_instance=RequestContext(request))


@login_required
def recordFeedback(request):
	to_json = {"success": True}
	try:
		referrer = request.META["HTTP_REFERER"]
	except Exception, e:
		to_json["success"] = False
		to_json["error_message"] = "HTTP Referer could not be retrieved"
	try:
		data = request.POST["data"]
	except Exception, e:
		to_json["success"] = False
		to_json["error_message"] = "POST data required"
	try:
		feedback = Feedback(page=referrer, feedback=data, user=request.user)
		feedback.save()
	except Exception, e:
		to_json["success"] = False
		to_json["error_message"] = "Database Failure"
	return HttpResponse(json.dumps(to_json), content_type='application/json')
Example #33
0
 def handle(self, *args, **options):
     event_name = options['event_name'][0]
     try:
         event = Event.objects.get(name=event_name)
     except Event.DoesNotExist:
         self.stdout.write('event does not exist')
         return
     if options['flush']:
         self.stdout.write('Removing all applicants in event %s...' %
                           event_name)
         self.stdout.write('%s users in the database' %
                           Applicant.objects.all().count())
         applicants = Applicant.objects.filter(event__name=event_name)
         self.stdout.write('%s users in the event %s' %
                           (applicants.count(), event_name))
         applicants.delete()
         self.stdout.write('%s users left in the database' %
                           Applicant.objects.all().count())
     if options['applicants']:
         if not os.path.exists('tmp'):
             os.makedirs('tmp')
         with open(options['applicants'], 'rU') as csvfile:
             applicants = list(csv.reader(csvfile))
             event = Event.objects.get_or_create(
                 name=options['event_name'][0])[0]
             for applicant in applicants[1:]:
                 self.add_applicant(
                     {
                         key: value
                         for (key, value) in zip(applicants[0], applicant)
                     }, event_name)
     if options['testing']:
         for _ in xrange(10):
             applicant = Applicant()
             applicant.first_name = randomString(10)
             applicant.last_name = randomString(10)
             applicant.high_school = '%s High School ' % randomString(8)
             applicant.hometown = randomString(7)
             applicant.hometown_state = random.choice(US_STATES)[0]
             applicant.gender = random.choice(['Mr.', 'Ms.'])
             applicant.event = event
             applicant.save()
             self.stdout.write('Created user %s' %
                               applicant.get_full_name())
     if options['feedback']:
         scholars = McUser.objects.all()
         applicants = Applicant.objects.all()
         for scholar in scholars:
             chance = random.random() / 3
             for applicant in applicants:
                 if random.random() < chance:
                     try:
                         f = Feedback.objects.get(scholar=scholar,
                                                  applicant=applicant)
                     except Feedback.DoesNotExist:
                         f = Feedback(scholar=scholar, applicant=applicant)
                     f.rating = random.choice([0, 1, 2, 3, 4, 5])
                     f.interest = random.choice([0, 1, 3, 4, 5])
                     f.comments = randomWords(random.randint(4, 15))
                     f.save()
     if options['pics']:
         for f in os.listdir('tmp'):
             f_split = f.split('.')[0].split(',')
             scholar_name = normalize_name('%s%s' %
                                           (f_split[1], f_split[0]))
             try:
                 app = Applicant.objects.get(norm_name=scholar_name,
                                             event__name=event_name)
             except Applicant.DoesNotExist:
                 self.stdout.write('Could not find user %s for pic %s' %
                                   (scholar_name, f))
                 continue
             extension = f.split('.')[-1]
             file_name = '%s,%s-fw.%s' % (app.last_name, app.first_name,
                                          extension)
             with open('tmp/%s' % f, 'rb') as img_file:
                 app.actual_pic.save(file_name, File(img_file), save=True)
             app.save()
             self.stdout.write('Saved pic %s for %s' % (f, scholar_name))
 def handle(self, *args, **options):
   event_name = options['event_name'][0]
   try:
     event = Event.objects.get(name=event_name) 
   except Event.DoesNotExist:
     self.stdout.write('event does not exist')
     return
   if options['flush']:
     self.stdout.write('Removing all applicants in event %s...' % event_name)
     self.stdout.write('%s users in the database' % Applicant.objects.all().count())
     applicants = Applicant.objects.filter(event__name=event_name)
     self.stdout.write('%s users in the event %s' % (applicants.count(), event_name))
     applicants.delete()
     self.stdout.write('%s users left in the database' % Applicant.objects.all().count())
   if options['applicants']:
     if not os.path.exists('tmp'):
       os.makedirs('tmp')
     with open(options['applicants'], 'rU') as csvfile:
       applicants = list(csv.reader(csvfile))
       event = Event.objects.get_or_create(name=options['event_name'][0])[0]
       for applicant in applicants[1:]:
         self.add_applicant({key: value for (key, value) in zip(applicants[0], applicant)}, event_name)
   if options['testing']:
     for _ in xrange(10):
       applicant = Applicant()
       applicant.first_name = randomString(10)
       applicant.last_name = randomString(10)
       applicant.high_school = '%s High School ' % randomString(8)
       applicant.hometown = randomString(7)
       applicant.hometown_state = random.choice(US_STATES)[0]
       applicant.gender = random.choice(['Mr.', 'Ms.'])
       applicant.event = event
       applicant.save()
       self.stdout.write('Created user %s' % applicant.get_full_name())
   if options['feedback']:
     scholars = McUser.objects.all()
     applicants = Applicant.objects.all()
     for scholar in scholars:
       chance = random.random() / 3
       for applicant in applicants:
         if random.random() < chance:
           try:
             f = Feedback.objects.get(scholar=scholar, applicant=applicant)
           except Feedback.DoesNotExist:
             f = Feedback(scholar=scholar, applicant=applicant)
           f.rating = random.choice([0, 1, 2, 3, 4, 5])
           f.interest = random.choice([0, 1, 3, 4, 5])
           f.comments = randomWords(random.randint(4, 15))
           f.save()
   if options['pics']:
     for f in os.listdir('tmp'):
       f_split = f.split('.')[0].split(',')
       scholar_name = normalize_name('%s%s' % (f_split[1], f_split[0]))
       try:
         app = Applicant.objects.get(norm_name=scholar_name, event__name=event_name)
       except Applicant.DoesNotExist:
         self.stdout.write('Could not find user %s for pic %s' % (scholar_name, f))
         continue
       extension = f.split('.')[-1]
       file_name = '%s,%s-fw.%s' % (app.last_name, app.first_name, extension)
       with open('tmp/%s' % f, 'rb') as img_file:
         app.actual_pic.save(file_name, File(img_file), save=True)
       app.save()
       self.stdout.write('Saved pic %s for %s' % (f, scholar_name))
Example #35
0
 def test_last_feedback_duration_attribute(self):
     self.feedback.duration = timedelta(hours=3)
     self.feedback.save()
     feedback = Feedback(subject=self.subject)
     feedback.save()
     self.assertEqual(feedback.duration, self.feedback.duration)
Example #36
0
    def save(self):
        user = self.context.get("request").user
        customer = user.customer
        if self.validated_data["feature_request_title"]:
            feature_request, created = FeatureRequest.objects.get_or_create(
                customer=customer,
                title=self.validated_data["feature_request_title"])

            if created:
                tracking.feature_request_created(user,
                                                 tracking.EVENT_SOURCE_CE)
            fr_id = feature_request.pk
        else:
            fr_id = self.validated_data["feature_request_id"]

        if self.validated_data["app_user_email"]:
            app_user, created = AppUser.objects.update_or_create(
                customer=customer,
                email=self.validated_data["app_user_email"],
                defaults={
                    "name": self.validated_data["app_user_name"],
                },
            )
            app_user_id = app_user.pk
        elif self.validated_data["app_user_name"]:
            try:
                app_user, created = AppUser.objects.update_or_create(
                    customer=customer,
                    name=self.validated_data["app_user_name"],
                    email=None,
                )
            except AppUser.MultipleObjectsReturned:
                app_user = AppUser.objects.filter(
                    customer=customer,
                    name=self.validated_data["app_user_name"],
                    email=None,
                )[0]
            app_user_id = app_user.pk
        else:
            app_user_id = self.validated_data["app_user_id"]

        feedback = Feedback(
            customer=customer,
            created_by=user,
            user_id=app_user_id,
            feature_request_id=fr_id,
            problem=self.validated_data["problem"],
            solution="",  # self.validated_data['solution'],
            source_url=self.validated_data["source_url"],
            feedback_type=self.validated_data["feedback_type"],
        )
        feedback.save()

        total_created_by_user = Feedback.objects.filter(
            customer=customer, created_by=user).count()
        first_entry = total_created_by_user == 1

        tracking.feedback_created(user.id, user.customer, feedback,
                                  tracking.EVENT_SOURCE_CE)

        OnboardingTask.objects.filter(
            customer=customer,
            task_type=OnboardingTask.TASK_CREATE_FEEDBACK_CE).update(
                completed=True, updated=timezone.now())

        return {"id": feedback.pk, "first_entry": first_entry}
Example #37
0
def index(request):
    """
    Check reminders and tags for consistency.
    """
    if (request.META.get('HTTP_X_APPENGINE_CRON', '') != 'true'
        and not request.user.is_staff):
        return HttpResponseRedirect('/accounts/login/?next=/consistency/')

    # Get all tags and suggestions from the datastore.
    tag_dict = dict((tag.key().name(), tag) for tag in Tag.all())
    suggestion_dict = dict((suggestion.key().name(), suggestion)
        for suggestion in Reminder.all().filter('owner', None))

    # Initialize empty problems dict.
    problems = dict((problem, []) for problem in PROBLEM_MESSAGES)

    # Check all tags.
    for tag_key, tag in tag_dict.items():
        if tag.count != len(tag.suggestions):
            problems['tag_count'].append(
                (tag, tag.count, len(tag.suggestions)))
        elif tag.count == 0:
            problems['tag_empty'].append((tag, ))
        oldest = None
        for suggestion_key in tag.suggestions:
            if tag.suggestions.count(suggestion_key) > 1:
                problems['tag_suggestion_duplicate'].append(
                    (tag, tag.suggestions.count(suggestion_key),
                     suggestion_key))
            if suggestion_key not in suggestion_dict:
                problems['tag_suggestion_missing'].append(
                    (tag, suggestion_key))
                continue
            suggestion = suggestion_dict[suggestion_key]
            if tag.key().name() not in suggestion.tags:
                problems['tag_suggestion_reverse'].append((tag, suggestion))
            if oldest is None or suggestion.created < oldest.created:
                oldest = suggestion
        if oldest:
            if tag.created is None:
                problems['tag_created_none'].append((tag, oldest))
            elif tag.created > oldest.created:
                problems['tag_created_later'].append((tag, oldest))

    # Check all suggestions.
    for suggestion_key, suggestion in suggestion_dict.items():
        for tag_key in suggestion.tags:
            if tag_key not in tag_dict:
                problems['suggestion_tag_missing'].append(
                    (suggestion, tag_key))
                continue
            tag = tag_dict[tag_key]
            if suggestion.key().name() not in tag.suggestions:
                problems['suggestion_tag_reverse'].append((suggestion, tag))

    # Check all feedback submitters.
    for feedback in Feedback.all().filter('submitter !=', None):
        try:
            submitter = feedback.submitter # Attempt to dereference.
        except datastore_errors.Error:
            problems['feedback_submitter'].append((feedback, request.user))

    # Check all reminders.
    for reminder in Reminder.all().filter('owner !=', None):
        try:
            owner = reminder.owner # Attempt to dereference.
        except datastore_errors.Error:
            problems['reminder_owner'].append((reminder, request.user))

    # Remove empty problem sections.
    for problem in PROBLEM_MESSAGES:
        if not problems[problem]:
            assert problems.pop(problem) == []

    # Return plain-text summary if cron is calling, development test with:
    # curl --header "X-AppEngine-Cron: true" http://localhost:8000/consistency/
    if request.META.get('HTTP_X_APPENGINE_CRON', '') == 'true':
        message = []
        for problem in problems:
            message.append(PROBLEM_HEADLINES[problem].rstrip('.') + ':')
            for data in problems[problem]:
                message.append("* " + format_problem(problem, data))
            message.append('')
        if not message:
            message.append("No problems found.")
            message.append('')
        message.append('http://www.minderbot.com/consistency/')
        message.append('')
        message = '\n'.join(message)
        if problems:
            if request.META.get('HTTP_USER_AGENT', '') != 'django.test.Client':
                logging.error(message)
            mail_admins('Consistency check found problems',
                        message, fail_silently=True)
        return HttpResponse(message, mimetype="text/plain")

    # Fix inconsistencies if admin clicked one of the buttons.
    if request.user.is_staff:
        for problem in problems:
            if problems[problem] and problem in request.POST:
                func = getattr(repair, problem)
                assert callable(func)
                for item in problems[problem]:
                    func(*item)
                return HttpResponseRedirect(request.path)

    # Collect errors and remove sections without problems.
    consistency_results = []
    for problem in problems:
        consistency_results.append(
            (problem,
             PROBLEM_HEADLINES[problem],
             [format_problem(problem, item) for item in problems[problem]],
             PROBLEM_BUTTONS[problem]))
    consistency_results.sort()
    return render_to_response(request, 'consistency/index.html', locals())
Example #38
0
def index(request):
    # checking to see if the form has been submitted
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            # message
            message = u"Name: " + cd["name"] + "\r\n"
            message += u"Address: " + cd["address"] + "\r\n"
            message += u"City: " + cd["city"] + "\r\n"
            message += u"State: " + cd["state"] + "\r\n"
            message += u"Zip Code: " + cd["zip_code"] + "\r\n"
            message += u"Email: " + cd["email"] + "\r\n"
            message += u"Phone Number: " + cd["phone_number"] + "\r\n"
            message += u"Feedback Type: " + cd["feedback_type"] + "\r\n"
            message += u"Message: "
            # converting unicode characters to ascii. hopefully.
            message += cd["message"]
            message += u"\r\n\r\n\r\nDebug Information\r\rUser Agent: " + request.META["HTTP_USER_AGENT"] + "\r\n"
            message += u"IP Address: " + request.META["REMOTE_ADDR"] + "\r\n"
            message += u"Referer: " + request.META["HTTP_REFERER"] + "\r\n"
            message += u"Number of Words: " + str(len(cd["message"].split())) + "\r\n"
            # saving feedback in the database
            feedback = Feedback()
            feedback.feedback_type = cd["feedback_type"]
            feedback.name = cd["name"]
            feedback.address = cd["address"]
            feedback.city = cd["city"]
            feedback.state = cd["state"]
            feedback.zip_code = cd["zip_code"]
            feedback.phone_number = cd["phone_number"]
            feedback.email = cd["email"]
            feedback.message = message
            # saving the feedback
            feedback.save()

            # setting where the email goes
            # by default everything goes to letters UNLESS specified
            to = "*****@*****.**"
            feedback_type = cd["feedback_type"]
            if feedback_type == "feedback" or feedback_type == "other":
                to = "*****@*****.**"
            elif feedback_type == "story_idea" or feedback_type == "press_release" or feedback_type == "you_asked":
                to = "*****@*****.**"

            if feedback_type == "letter_to_editor":
                feedback_type_text = "Letter To The Editor"
            elif feedback_type == "voice_of_day":
                feedback_type_text = "Voice of the Day"
            elif feedback_type == "to_the_point":
                feedback_type_text = "To The Point"
            elif feedback_type == "rose_thorn":
                feedback_type_text = "Roses and Thorn"
            elif feedback_type == "feedback":
                feedback_type_text = "Story Feedback"
            elif feedback_type == "story_idea":
                feedback_type_text = "Story Idea"
            elif feedback_type == "press_release":
                feedback_type_text = "Press Release"
            elif feedback_type == "you_asked":
                feedback_type_text = "You Asked"
            elif feedback_type == "other":
                feedback_type_text = "Other"

            # sending the email
            send_mail(
                "News-Leader.com " + feedback_type_text + " Submission: " + str(cd["name"]),
                message,
                "*****@*****.**",
                # ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**'],
                [to, "*****@*****.**", "*****@*****.**"],
            )

            # secondary message to the user without the debug
            message = "Name: " + str(cd["name"]) + "\r\n"
            message += "Address: " + str(cd["address"]) + "\r\n"
            message += "City: " + str(cd["city"]) + "\r\n"
            message += "State: " + str(cd["state"]) + "\r\n"
            message += "Zip Code: " + str(cd["zip_code"]) + "\r\n"
            message += "Email: " + str(cd["email"]) + "\r\n"
            message += "Phone Number: " + str(cd["phone_number"]) + "\r\n"
            message += "Message: "
            # converting unicode to ascii, hopefully
            message += str(cd["message"].encode("ascii", "xmlcharrefreplace"))

            send_mail(
                "News-Leader " + feedback_type_text + " Submission: " + str(cd["name"]),
                message,
                "*****@*****.**",
                [cd["email"]],
            )

            return HttpResponseRedirect("/feedback/thanks")
    else:
        # first submission of the form
        feedback_type = "letter_to_editor"
        if "feedback_type" in request.GET.keys():
            feedback_type = request.GET["feedback_type"]
        form = ContactForm(initial={"state": "MO", "feedback_type": feedback_type})
    return render_to_response("feedback/feedback.html", {"form": form}, context_instance=RequestContext(request))
Example #39
0
 def test_last_feedback_duration_attribute(self):
     self.feedback.duration = timedelta(hours=3)
     self.feedback.save()
     feedback = Feedback(subject=self.subject)
     feedback.save()
     self.assertEqual(feedback.duration, self.feedback.duration)
Example #40
0
def slack_dialog(request):  # noqa: C901

    json_payload, slack_settings = validate_slack_request(request)

    # An error occured in validate_slack_response.  So we return a 200
    # and tell Slack to not retry.
    if slack_settings is None:
        response = HttpResponse(status=200)
        response["X-Slack-No-Retry"] = "1"
        return response

    customer = slack_settings.customer

    channel_id = json_payload["channel"]["id"]
    payload_type = json_payload["type"]

    headers = {"Content-Type": "application/json; charset=utf-8"}

    if payload_type == "block_actions":
        # Yes or No button has been clicked

        if json_payload["actions"][0]["text"]["text"] == "No":
            # "No" Button clicked - delete ephemeral message
            delete_ephemeral_message(
                json_payload["container"]["message_ts"],
                json_payload["response_url"],
                headers,
            )

        else:
            # "Yes" button clicked - show dialog

            trigger_id = json_payload["trigger_id"]

            # message_ts is the pointer to the message we care about adding to Savio, NOT the timestamp
            # of the response to the Yes/No ephemeral message that just got POSTed
            message_ts = json_payload["actions"][0]["value"]

            # Get Message so we can display "problem" as a default in the Dialog's problem textarea
            message_url = "https://slack.com/api/channels.history"
            message_json = {
                "oldest": message_ts,
                "count": 1,
                "inclusive": True,
                "channel": channel_id,
            }

            headers = {
                "Content-Type":
                "application/x-www-form-urlencoded;",
                "Authorization":
                "Bearer " + slack_settings.slack_user_access_token,
            }
            response = requests.post(message_url,
                                     data=message_json,
                                     headers=headers)

            if not response.json()["ok"]:
                capture_message(
                    f"Error getting Slack Message: message.json: {response.json()}. slack_settings_id: {slack_settings.id}."
                )
                response = HttpResponse(status=200)
                response["X-Slack-No-Retry"] = "1"
                return response
            else:
                message = response.json()["messages"][0]["text"]

            dialog_json = get_dialog_json(trigger_id,
                                          "show_create_feedback_dialog",
                                          message_ts, message, customer)

            headers = {
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": "Bearer " + slack_settings.slack_bot_token,
            }

            dialog_url = "https://slack.com/api/dialog.open"
            response = requests.post(dialog_url,
                                     data=json.dumps(dialog_json),
                                     headers=headers)

            if not response.json()["ok"]:
                capture_message(
                    f"Error generating Slack dialog: response.json: {response.json()}. message: {message}. message_ts: {message_ts}. slack_settings_id: {slack_settings.id}"
                )
                response = HttpResponse(status=200)
                response["X-Slack-No-Retry"] = "1"
                return response

            delete_ephemeral_message(
                json_payload["container"]["message_ts"],
                json_payload["response_url"],
                headers,
            )

    else:
        # Dialog initiated by message action
        callback_id = json_payload["callback_id"]

        if callback_id == "show_create_feedback_dialog":
            if payload_type == "dialog_submission":

                # Saving a Posted Dialog

                slack_user_name = json_payload["user"]["name"]
                slack_user_id = json_payload["user"]["id"]
                problem = json_payload["submission"]["problem"]
                person = json_payload["submission"]["person"]
                new_person_email = json_payload["submission"][
                    "new_person_email"]
                feedback_from = json_payload["submission"]["feedback_from"]
                feature_request = json_payload["submission"]["feature_request"]
                response_url = json_payload["response_url"]

                # Validate submitted data
                errors = {"errors": []}
                if not problem:
                    errors["errors"].append({
                        "name":
                        "problem",
                        "error":
                        "Can't be blank. Please try again.",
                    })

                if not feedback_from:
                    errors["errors"].append({
                        "name":
                        "feedback_from",
                        "error":
                        "Can't be blank. Please try again.",
                    })

                if not (person or new_person_email):

                    errors["errors"].append({
                        "name":
                        "person",
                        "error":
                        "You need to select an existing or new person.",
                    })
                    errors["errors"].append({
                        "name":
                        "new_person_email",
                        "error":
                        "You need to select an existing or new person.",
                    })

                if len(errors["errors"]) > 0:
                    capture_message(
                        f"Invalid params submitted from Slack. problem: {problem}. person: {person}. feedback_from: {feedback_from}"
                    )
                    return JsonResponse(errors)

                # To post to the Slack channel, we first need to get the permalink of the parent message.
                permalink_url = "https://slack.com/api/chat.getPermalink"
                shared_ts = json_payload["state"]

                # Add Auth header to headers. We don't need it for previous posts to response_url, but we do
                # post web API methods like chat.getPermalink
                headers[
                    "Authorization"] = "Bearer " + slack_settings.slack_bot_token

                permalink_params = {
                    "channel": channel_id,
                    "message_ts": shared_ts
                }
                permalink_response = requests.post(permalink_url,
                                                   params=permalink_params,
                                                   headers=headers).json()

                if not permalink_response["ok"]:

                    params = {
                        "text":
                        "There was an error saving your feedback.  Please try again.",
                    }
                    requests.post(response_url,
                                  data=json.dumps(params),
                                  headers=headers)

                    capture_message(
                        f"Invalid permalink from Slack. channel: {channel_id}. message timestamp: {shared_ts}. "
                    )
                    return HttpResponse(status=406)

                message_permalink = permalink_response["permalink"]

                # Look up User. The user in Slack likely won't have a row in our users table.
                if slack_settings.slack_user_id == slack_user_id:
                    u = slack_settings.user
                else:
                    u = None

                # Are we creating a new person, or using an existing one?  Figure it out.
                if person:
                    use_person_id = person
                else:
                    # handle case where email entered but user exists.
                    try:
                        user = AppUser.objects.get(email=new_person_email,
                                                   customer_id=customer.id)
                    except AppUser.DoesNotExist:
                        user = AppUser.objects.create(email=new_person_email,
                                                      customer_id=customer.id)

                    use_person_id = user.id

                # Save feedback to DB
                feedback = Feedback(
                    customer=customer,
                    source_url=message_permalink,
                    problem=problem,
                    feedback_type=feedback_from,
                    feature_request_id=feature_request,
                    user_id=use_person_id,
                    source_username=slack_user_name,
                    created_by=u,
                )
                feedback.save()

                if u:
                    user_id = u.id
                else:
                    user_id = f"Slack - {slack_user_id}"

                tracking.feedback_created(user_id, customer, feedback,
                                          tracking.EVENT_SOURCE_SLACK)

                # Then, we'll post a reply to the message as part of a thread
                post_message_url = "https://slack.com/api/chat.postMessage"

                now = datetime.datetime.now()
                unix_time = now.timestamp()

                savio_feedback_url = settings.HOST + feedback.get_absolute_url(
                )

                date_string = ("<!date^" + repr(int(unix_time)) +
                               "^{date} at {time}^" + savio_feedback_url +
                               "|" + now.strftime("%b %d %Y at %I:%M %p") +
                               ">")

                company_str = ""
                if feedback.user.company:
                    company_str = f" @ {feedback.user.company.name}"

                fr_string = "None"
                if feedback.feature_request is not None:
                    fr_url = settings.HOST + reverse(
                        "feature-request-feedback-details",
                        kwargs={"pk": feedback.feature_request.id},
                    )
                    fr_string = f"<{fr_url}|{feedback.feature_request.title}>"

                # This Code creates a payload to reply in a thread with the original message as the parent
                reply_json = {
                    "channel":
                    channel_id,
                    "as_user":
                    False,
                    "link_names":
                    True,
                    "mrkdwn":
                    True,
                    "unfurl_links":
                    True,
                    "thread_ts":
                    shared_ts,
                    "blocks": [
                        {
                            "type":
                            "context",
                            "elements": [
                                {
                                    "type":
                                    "mrkdwn",
                                    "text":
                                    f"@{slack_user_name} pushed this customer feedback to Savio on {date_string}:",
                                },
                            ],
                        },
                        {
                            "type": "section",
                            "text": {
                                "type":
                                "mrkdwn",
                                "text":
                                f"*From*\n{feedback.user.get_name_or_email()}{company_str} ({dict(feedback.TYPE_CHOICES)[feedback.feedback_type]})\n\n*Feedback*\n{problem}\n\n*Feature Request*\n{fr_string}",
                            },
                        },
                    ],
                }
                # End Code posts a response to the Slack Channel with the message posted to Savio

                response = requests.post(post_message_url,
                                         data=json.dumps(reply_json),
                                         headers=headers)

            elif payload_type == "message_action":

                # Show a Dialog
                trigger_id = json_payload["trigger_id"]
                message = json_payload["message"]["text"]
                message_ts = json_payload["message_ts"]

                dialog_json = get_dialog_json(trigger_id, callback_id,
                                              message_ts, message, customer)

                headers = {
                    "Content-Type": "application/json; charset=utf-8",
                    "Authorization":
                    "Bearer " + slack_settings.slack_bot_token,
                }

                dialog_url = "https://slack.com/api/dialog.open"
                response = requests.post(dialog_url,
                                         data=json.dumps(dialog_json),
                                         headers=headers)

    return Response(status=status.HTTP_200_OK)
 def create(self, validated_data):
     return Feedback(**validated_data)
Example #42
0
    def save(self):
        user = self.context.get("request").user
        customer = user.customer
        fr_title = self.validated_data.get("feature_request_title", "")
        if fr_title:
            feature_request, created = FeatureRequest.objects.get_or_create(
                customer=customer,
                title__iexact=fr_title,
                defaults={
                    "title": fr_title,
                })

            if created:
                tracking.feature_request_created(user,
                                                 tracking.EVENT_SOURCE_API)
            fr_id = feature_request.pk
        else:
            fr_id = None

        email = self.validated_data.get("person_email", "")
        name = self.validated_data.get("person_name", "")
        if email:
            app_user, created = AppUser.objects.update_or_create(
                customer=customer,
                email__iexact=email,
                defaults={
                    "email": email,
                    "name": name,
                },
            )
            app_user_id = app_user.pk
        elif name:
            app_user, created = AppUser.objects.get_or_create(
                customer=customer,
                name=name,
                defaults={
                    "email": email or None,
                })
            app_user_id = app_user.pk
        else:
            app_user_id = None

        feedback = Feedback(
            customer=customer,
            created_by=user,
            user_id=app_user_id,
            feature_request_id=fr_id,
            problem=self.validated_data["problem"],
            source_url=self.validated_data.get("source_url", ""),
            feedback_type=self.validated_data["feedback_type"],
            state=self.validated_data["state"],
            source_username="******",
        )
        feedback.save(override_auto_triage=True)

        for theme_name in self.validated_data.get("tags", list()):
            defaults = {
                "title": theme_name,
            }

            theme, created = Theme.objects.get_or_create(
                customer=user.customer,
                title__iexact=theme_name,
                defaults=defaults)
            feedback.themes.add(theme)

        tracking.feedback_created(user.id, user.customer, feedback,
                                  tracking.EVENT_SOURCE_API)
        return {"id": feedback.pk}