def process_add(request, form_data): '''Returns the added book if add is successful, None if the field is blank, or raises Book.DoesNotExist if no such book is found''' form = AddForm(form_data) if not form.is_valid(): raise Book.DoesNotExist # Clean up the ISBN, or stop if there has been no ISBN entered isbn = form.cleaned_data['add'] if len(isbn) == 0: return None isbn = cleanisbn(isbn) # Get the book, or raise the exception that it does not exist if len(isbn) == 13: try: book = Book.objects.get(isbn13=isbn) except Book.DoesNotExist: book = book_details(isbn) if book != None: book.save() else: raise Book.DoesNotExist elif len(isbn) == 10: try: book = Book.objects.get(isbn10=isbn) except Book.DoesNotExist: book = book_details(isbn) if book != None: book.save() else: raise Book.DoesNotExist else: raise Book.DoesNotExist # Check that the item is not already in the wishlist user, created = User.objects.get_or_create(net_id=request.user.username) req_list = Request.objects.filter(user=user, status='o', book=book) if len(req_list) > 0: raise AlreadyInWishlist req = Request(user=user, book = book, status = 'o', maxprice = 0) req.save() return book
def process_add(request, form_data): '''Returns the added book if add is successful, None if the field is blank, or raises Book.DoesNotExist if no such book is found''' form = AddForm(form_data) if not form.is_valid(): raise Book.DoesNotExist # Clean up the ISBN, or stop if there has been no ISBN entered isbn = form.cleaned_data['add'] if len(isbn) == 0: return None isbn = cleanisbn(isbn) # Get the book, or raise the exception that it does not exist if len(isbn) == 13: try: book = Book.objects.get(isbn13=isbn) except Book.DoesNotExist: book = book_details(isbn) if book != None: book.save() else: raise Book.DoesNotExist elif len(isbn) == 10: try: book = Book.objects.get(isbn10=isbn) except Book.DoesNotExist: book = book_details(isbn) if book != None: book.save() else: raise Book.DoesNotExist else: raise Book.DoesNotExist # Check that the item is not already in the wishlist user, created = User.objects.get_or_create(net_id=request.user.username) req_list = Request.objects.filter(user=user, status='o', book=book) if len(req_list) > 0: raise AlreadyInWishlist req = Request(user=user, book=book, status='o', maxprice=0) req.save() return book
def buy(request): """Controller for /buy. Inputs: user session, an offer ID. Outputs: a pending offer, a pending request, confirmation emails, and capitalism.""" buyer, created = User.objects.get_or_create(net_id=request.user.username) if not buyer: return render(request, 'ptx/needlogin.html', { 'header_text': 'Buy a book', 'redirect_url': '/' }) if not request.method == "POST": return HttpResponseRedirect('/') offerid = request.POST.get("offer_id") if not offerid or not offerid.isdigit(): raise PermissionDenied() try: offer = Offer.objects.get(id=int(offerid)) except Offer.DoesNotExist: # Terribly invalid offer ID, inconsistent with our code. return HttpResponseRedirect(u'/browse') data = dict(offer=offer) today = date.today() # Offers must be open. if offer.status != 'o': # this shouldn't happen. TODO: do something reasonable return render(request, "ptx/alreadybought.html", data) # Prevent a person from buying his own book. if offer.user == buyer: return render(request, "ptx/yourownbook.html", data) # Change offer to pending. offer.status = 'p' offer.date_pending = today offer.save() # Check if a request exists already. requests = Request.objects.filter( Q(user=buyer) & Q(status='o') & Q(book=offer.book)) if len(requests) > 0: # Update the request instead. req = requests[0] req.maxprice = offer.price req.date_pending = today req.status = 'p' req.offer = offer req.save() else: # Otherwise, create a new pending request. req = Request(user=buyer, book=offer.book, status='p', maxprice=offer.price, date_open=today, date_pending=today, offer=offer) req.save() seller = offer.user # Email the seller. #################### emailto = [seller.net_id + u"@princeton.edu"] emailsubject = u"PTX: Your book has been purchased!" emailfrom = u"*****@*****.**" buyerclause = u"The buyer" if len(buyer.first_name) > 0 and len(buyer.last_name) > 0: args = buyer.first_name, buyer.last_name buyerclause = u"The buyer, %s %s," % args buyerdorm = u"" if len(buyer.dorm_name) > 0 and len(buyer.dorm_room) > 0: args = buyer.dorm_name, buyer.dorm_room buyerdorm = u"The buyer lives in %s %s. " % args args = offer.book.title, offer.price, buyerclause, buyer.net_id, buyerdorm emailmessage = u"""\ Your book "%s" has just been purchased for $%s. %s can be reached at \ <*****@*****.**>. %sPlease contact him or her and complete the \ transaction. Please do not reply to this email; our robots disdain \ communication with humans.""" % args send_mail(emailsubject, emailmessage, emailfrom, emailto) # Email the buyer. #################### emailto = [buyer.net_id + u"@princeton.edu"] emailsubject = u"PTX: You purchased a book!" emailfrom = u"*****@*****.**" sellerclause = u"The seller " if len(seller.first_name) > 0 and len(seller.last_name) > 0: args = seller.first_name, seller.last_name sellerclause = u"The seller, %s %s," % args sellerdorm = u"" if len(seller.dorm_name) > 0 and len(seller.dorm_room) > 0: args = seller.dorm_name, seller.dorm_room sellerdorm = u"The seller lives in %s %s. " % args args = offer.book.title, offer.price, sellerclause, seller.net_id, sellerdorm emailmessage = u"""\ You just purchased "%s" for $%s. %s can be reached at \ <*****@*****.**>. %sPlease contact him or her and complete the \ transaction. Please do not reply to this email; our robots have little \ training in the inferior language of "English".""" % args send_mail(emailsubject, emailmessage, emailfrom, emailto) # Thank you page. #################### return render(request, 'ptx/buy.html', data)
def buy(request): """Controller for /buy. Inputs: user session, an offer ID. Outputs: a pending offer, a pending request, confirmation emails, and capitalism.""" buyer, created = User.objects.get_or_create(net_id=request.user.username) if not buyer: return render(request, 'ptx/needlogin.html', {'header_text': 'Buy a book', 'redirect_url': '/'} ) if not request.method == "POST": return HttpResponseRedirect('/') offerid = request.POST.get("offer_id") if not offerid or not offerid.isdigit(): raise PermissionDenied() try: offer = Offer.objects.get(id=int(offerid)) except Offer.DoesNotExist: # Terribly invalid offer ID, inconsistent with our code. return HttpResponseRedirect(u'/browse') data = dict(offer=offer) today = date.today() # Offers must be open. if offer.status != 'o': # this shouldn't happen. TODO: do something reasonable return render(request, "ptx/alreadybought.html", data) # Prevent a person from buying his own book. if offer.user == buyer: return render(request, "ptx/yourownbook.html", data) # Change offer to pending. offer.status = 'p' offer.date_pending = today offer.save() # Check if a request exists already. requests = Request.objects.filter(Q(user=buyer) & Q(status='o') & Q(book=offer.book)) if len(requests) > 0: # Update the request instead. req = requests[0] req.maxprice = offer.price req.date_pending = today req.status = 'p' req.offer = offer req.save() else: # Otherwise, create a new pending request. req = Request(user=buyer, book=offer.book, status='p', maxprice=offer.price, date_open=today, date_pending=today, offer=offer) req.save() seller = offer.user # Email the seller. #################### emailto = [seller.net_id + u"@princeton.edu"] emailsubject = u"PTX: Your book has been purchased!" emailfrom = u"*****@*****.**" buyerclause = u"The buyer" if len(buyer.first_name) > 0 and len(buyer.last_name) > 0: args = buyer.first_name, buyer.last_name buyerclause = u"The buyer, %s %s," % args buyerdorm = u"" if len(buyer.dorm_name) > 0 and len(buyer.dorm_room) > 0: args = buyer.dorm_name, buyer.dorm_room buyerdorm = u"The buyer lives in %s %s. " % args args = offer.book.title, offer.price, buyerclause, buyer.net_id, buyerdorm emailmessage = u"""\ Your book "%s" has just been purchased for $%s. %s can be reached at \ <*****@*****.**>. %sPlease contact him or her and complete the \ transaction. Please do not reply to this email; our robots disdain \ communication with humans.""" % args send_mail(emailsubject, emailmessage, emailfrom, emailto) # Email the buyer. #################### emailto = [buyer.net_id + u"@princeton.edu"] emailsubject = u"PTX: You purchased a book!" emailfrom = u"*****@*****.**" sellerclause = u"The seller " if len(seller.first_name) > 0 and len(seller.last_name) > 0: args = seller.first_name, seller.last_name sellerclause = u"The seller, %s %s," % args sellerdorm = u"" if len(seller.dorm_name) > 0 and len(seller.dorm_room) > 0: args = seller.dorm_name, seller.dorm_room sellerdorm = u"The seller lives in %s %s. " % args args = offer.book.title, offer.price, sellerclause, seller.net_id, sellerdorm emailmessage = u"""\ You just purchased "%s" for $%s. %s can be reached at \ <*****@*****.**>. %sPlease contact him or her and complete the \ transaction. Please do not reply to this email; our robots have little \ training in the inferior language of "English".""" % args send_mail(emailsubject, emailmessage, emailfrom, emailto) # Thank you page. #################### return render(request, 'ptx/buy.html', data)
def process(request, step, ticket): # this function only processes POST requests if request.method != 'POST': raise PermissionDenied() step = int(step) if step == ChooseCourseForm.PROC: form = ChooseCourseForm(request.POST) if form.is_valid(): # break down the course input course = form.cleaned_data['course'] m = COURSE.match(course).groups() course_dept = m[0].upper() course_num = int(m[1]) # does it exist? if not, add it # TODO: MORE CHECKING HERE FOR INVALID DEPARTMENTS, ETC course_list = Course.objects.filter(dept__exact=course_dept, num__exact=course_num) if len(course_list) == 1: c = course_list[0] elif len(course_list) == 0: c = Course(dept=course_dept, num=course_num) c.save() else: # This can't really happen raise PermissionDenied # save the internal course id for later request.session['request_course_' + ticket] = c # show the list of books for the course return render_form(ChooseBookForm(c), '', ticket, request) else: return render_form(ChooseCourseForm(request.POST), '', ticket, request) elif step == ChooseBookForm.PROC: course = request.session['request_course_' + ticket] form = ChooseBookForm(course, request.POST) if form.is_valid(): isbn_from_db = form.cleaned_data['isbn_from_db'] isbn_from_user = form.cleaned_data['isbn_from_user'] if isbn_from_db != None: # book exists already, let the user list this book request.session['request_book_' + ticket] = isbn_from_db return render_form(RequestForm(), '', ticket, request) elif isbn_from_user != None: # check if book exists in DB, just not associated with that class if Book.objects.filter(isbn13=isbn_from_user).count() == 0: # book does not exist, let the user create it #form = AddBookForm() #form.fields['isbn13'].initial = isbn_from_user bookinfo = book_details(isbn_from_user) if bookinfo == None: return render_form(form, '', ticket, request) else: set_ticket_attr(request, ticket, 'bookinfo', bookinfo) return render_bookinfo(bookinfo, ticket, request) else: # book needs new class reference added. book = Book.objects.get(isbn13=isbn_from_user) book.course.add(course) book.save() request.session['request_book_' + ticket] = book return render_form(RequestForm(), '', ticket, request) else: # no book chosen, go back and make the user choose a book return render_form(form, '', ticket, request) else: return render_form(form, '', ticket, request) elif step == PROCESS_ADD_BOOK: bookinfo = get_ticket_attr(request, ticket, 'bookinfo') # TODO: MAKE SURE AGAIN THAT THE ISBN IS NOT ALREADY IN THE DATABASE book = Book(isbn13=bookinfo['isbn13'], isbn10=bookinfo['isbn10'], title=bookinfo['title'], desc='', author=bookinfo['author'], edition=bookinfo['edition'], year=bookinfo['year'], publisher=bookinfo['publisher'], list_price=0, imagename=bookinfo['img_name']) course = request.session['request_course_' + ticket] book.course.add(course) book.save() request.session['request_book_' + ticket] = book return render_form(RequestForm(), '', ticket, request) elif step == RequestForm.PROC: form = RequestForm(request.POST) if form.is_valid(): f = form.cleaned_data book = request.session['request_book_' + ticket] user, created = User.objects.get_or_create( net_id=request.user.username) maxprice = form.cleaned_data['maxprice'] the_request = Request(book=book, user=user, maxprice=maxprice) the_request.save() reset_request_session(request, ticket) # redirect to thank you page return HttpResponseRedirect('/request/thankyou?b=%s' % (book)) else: return render_form(form, '', ticket, request) return HttpResponse(step)
def process(request, step, ticket): # this function only processes POST requests if request.method != 'POST': raise PermissionDenied() step = int(step) if step == ChooseCourseForm.PROC: form = ChooseCourseForm(request.POST) if form.is_valid(): # break down the course input course = form.cleaned_data['course'] m = COURSE.match(course).groups() course_dept = m[0].upper() course_num = int(m[1]) # does it exist? if not, add it # TODO: MORE CHECKING HERE FOR INVALID DEPARTMENTS, ETC course_list = Course.objects.filter(dept__exact=course_dept, num__exact=course_num) if len(course_list) == 1: c = course_list[0] elif len(course_list) == 0: c = Course(dept=course_dept, num=course_num) c.save() else: # This can't really happen raise PermissionDenied # save the internal course id for later request.session['request_course_' + ticket] = c # show the list of books for the course return render_form(ChooseBookForm(c), '', ticket, request) else: return render_form(ChooseCourseForm(request.POST), '', ticket, request) elif step == ChooseBookForm.PROC: course = request.session['request_course_' + ticket] form = ChooseBookForm(course, request.POST) if form.is_valid(): isbn_from_db = form.cleaned_data['isbn_from_db'] isbn_from_user = form.cleaned_data['isbn_from_user'] if isbn_from_db != None: # book exists already, let the user list this book request.session['request_book_' + ticket] = isbn_from_db return render_form(RequestForm(), '', ticket, request) elif isbn_from_user != None: # check if book exists in DB, just not associated with that class if Book.objects.filter(isbn13=isbn_from_user).count() == 0: # book does not exist, let the user create it #form = AddBookForm() #form.fields['isbn13'].initial = isbn_from_user bookinfo = book_details(isbn_from_user) if bookinfo == None: return render_form(form, '', ticket, request) else: set_ticket_attr(request, ticket, 'bookinfo', bookinfo) return render_bookinfo(bookinfo, ticket, request) else: # book needs new class reference added. book = Book.objects.get(isbn13=isbn_from_user) book.course.add(course) book.save() request.session['request_book_' + ticket] = book return render_form(RequestForm(), '', ticket, request) else: # no book chosen, go back and make the user choose a book return render_form(form, '', ticket, request) else: return render_form(form, '', ticket, request) elif step == PROCESS_ADD_BOOK: bookinfo = get_ticket_attr(request, ticket, 'bookinfo') # TODO: MAKE SURE AGAIN THAT THE ISBN IS NOT ALREADY IN THE DATABASE book = Book( isbn13 = bookinfo['isbn13'], isbn10 = bookinfo['isbn10'], title = bookinfo['title'], desc = '', author = bookinfo['author'], edition = bookinfo['edition'], year = bookinfo['year'], publisher = bookinfo['publisher'], list_price = 0, imagename = bookinfo['img_name']) course = request.session['request_course_' + ticket] book.course.add(course) book.save() request.session['request_book_' + ticket] = book return render_form(RequestForm(), '', ticket, request) elif step == RequestForm.PROC: form = RequestForm(request.POST) if form.is_valid(): f = form.cleaned_data book = request.session['request_book_' + ticket] user, created = User.objects.get_or_create(net_id=request.user.username) maxprice = form.cleaned_data['maxprice'] the_request = Request( book=book, user=user, maxprice=maxprice) the_request.save() reset_request_session(request, ticket) # redirect to thank you page return HttpResponseRedirect('/request/thankyou?b=%s' % (book)) else: return render_form(form, '', ticket, request) return HttpResponse(step)