def generate_quote_from_fileWC(request, outputformat, quotesource): ''' Function to generate the using either a generic template or a user specific one ''' ''' Quote data is sourced from a test data file or from the specific current quote ''' ''' Output can be rendered to screen or to an Email recipient as defined on the data from the form ''' # Initial check to see if user specific PDF template file exists # If it does then use that template, if not then use the generic template usr_pdf_template_file = Path( settings.BASE_DIR + "/templates/pdf/user_{}/serviceandorder_for_pdf.html".format( request.user.username)) print(usr_pdf_template_file) if os.path.isfile(usr_pdf_template_file): sourceHtml = "pdf/user_{}/serviceandorder_for_pdf.html".format( request.user.username) # Under templates folder else: sourceHtml = "pdf/serviceandorder_for_pdf.html" # Under templates folder # Determine where to source the quote data from - test_data.txt or the current quote for the user if quotesource == "testdata": quote_form_filename = Path( settings.BASE_DIR + "/pdf_output_archive/westchem/test_data.txt") else: # use the current quote data file quote_form_filename = Path( settings.BASE_DIR + "/pdf_output_archive/westchem/current_report_{}.txt".format( request.user.username)) # if a current quote data file does not exist then revery back to using the test data file if not os.path.isfile(quote_form_filename): quote_form_filename = Path( settings.BASE_DIR + "/pdf_output_archive/westchem/test_data.txt") with open(quote_form_filename) as file: file_form_datax = [] for line in file: file_form_datax.append(eval(line)) file_form_data = file_form_datax #'product_id = file_form_data[8].get('product_choice') idx = Profile.objects.get(user=request.user) # Get the ProductPrice record selection #'if quotesource == "testdata": # ProductPrice will come from the first user record or from the demo record #' if ProductPrice.objects.filter(user = request.user).count() > 0 : # Check if the user has created a product/price record #' product_record = ProductPrice.objects.filter(user = request.user).first() # A product price record exists - use the first one #' else: # Product Price record does not exist - select the Demo record #' product_record = ProductPrice.objects.first() #'else: # retrieve the user selected product record from the quote form #' product_record = ProductPrice.objects.get(pk = int(product_id)) frecords = Document.objects.filter( user=request.user.username).order_by('uploaded_at') #'try: # test to see if image is associated with product #' img_record = Document.objects.get(id = product_record.product_image.id ) #'except: # if not then continue with empty object #' img_record = "" # Calculate the daily_work_rate multiplied by the estimated_duration #'workload_cost = idx.daily_work_rate * int(file_form_data[8].get('estimated_duration')[0]) # Calculate the total quote price for the quote #'total_quote_price = workload_cost + product_record.price # Determine whether to output to screen as PDF or HTML if outputformat == "PDFOutput": request.session['created_quote_template'] = True created_quote_template_group = Group.objects.get( name='created_quote_template') request.user.groups.add(created_quote_template_group) pdf = render_to_pdf(sourceHtml, { 'form_data': file_form_data, 'idx': idx, 'frecords': frecords }) return HttpResponse(pdf, content_type='application/pdf') elif outputformat == "EmailOutput": # Get customer lastname customer = (file_form_data[0].get('customer')) # Assign file name to store generated PDF outputFilename = Path( settings.BASE_DIR + "/pdf_output_archive/westchem/Report_{}_{}{}.pdf".format( idx.quote_prefix, customer.replace(" ", "_"), f"{idx.current_quote_number:05}") ) # pad with leading zeros (5 positions) # Generate the PDF and write to disk convertHtmlToPdf2(sourceHtml, outputFilename, { 'form_data': file_form_data, 'idx': idx, 'frecords': frecords }) # Generate the email, attach the pdf and send out fd = file_form_data msg = "" msg = msg + "Hello {}.\nThank you for your ongoing business. Your service and order report is on the attached PDF file.\n".format( fd[0]['contact'].split()[0]) msg = msg + "Can you please review the report and confirm your acceptance by return email.\n\n" msg = msg + "Should you have any further questions please feel free to contact me on {}.\n\n".format( idx.telephone) msg = msg + "Kind regards,\n" msg = msg + idx.first_name email = EmailMessage( 'Service and Order Report from {}'.format(idx.company_name), msg, idx.email, [fd[0]['customer_email']]) email.attach_file(outputFilename) email.send() return HttpResponseRedirect('/quoteemailed/') else: # HTMLOutput return render(request, sourceHtml, { 'form_data': file_form_data, 'idx': idx, 'frecords': frecords })
def customer_order(request): if request.method == "POST": ProductFormSet = formset_factory(ProductForm) # Grab the form from the POST variable formset = ProductFormSet(request.POST) if formset.is_valid(): # Initialise calculated variables for output form_data = [] sub_total = 0 # Deconstruct and Reconstruct the formset adding extended price for f in formset: cd = f.cleaned_data extended_price = cd.get("quantity") * cd.get("price") sub_total += extended_price # Add the extended price to the dict. cd.update({'extended_price': extended_price}) form_data.append(cd) # Finalise calculated variables total_inc_vat = round(float(sub_total) * 0.20, 2) grand_total = round(float(sub_total) + total_inc_vat, 2) # Get the pdf template file usr_pdf_template_file = Path( settings.BASE_DIR + "/templates/pdf/user_{}/customerorder_for_pdf.html".format( request.user.username)) if os.path.isfile(usr_pdf_template_file): sourceHtml = "pdf/user_{}/customerorder_for_pdf.html".format( request.user.username) # Under templates folder else: sourceHtml = "pdf/customerorder_for_pdf.html" # Under templates folder # Assign file name to store generated PDF (will need revisting to increment rather than overwrite) outputFilename = Path( settings.BASE_DIR + "/pdf_output_archive/westchem/customer_order/Customer_Order.pdf" ) # Get the image file records frecords = Document.objects.filter( user=request.user.username).order_by('uploaded_at') # Generate the PDF file convertHtmlToPdf2( sourceHtml, outputFilename, { 'form_data': form_data, 'frecords': frecords, 'sub_total': sub_total, 'total_inc_vat': total_inc_vat, 'grand_total': grand_total }) # Redirect to page listing the pdf output file(s) return redirect('/orderreportgenerated/') # If the form is not being processed, create a new ProductFormSet and render it else: product_list = [] for product in ProductPrice.objects.filter(user=request.user): product_list.append({ 'product_id': product.id, 'model_name': product.model_name, 'size': product.product_code, 'price': product.price, 'stock': 0, 'quantity': 0 }) ProductFormSet = formset_factory(ProductForm, extra=0) formset = ProductFormSet(initial=product_list) return render(request, 'westchem/orderforms/CustomerOrderForm.html', {'formset': formset})
def done(self, form_list, **kwargs): # Initial check to see if user specific PDF template file exists # If it does then use that template, if not use the generic template usr_pdf_template_file = Path( settings.BASE_DIR + "/templates/pdf/user_{}/serviceandorder_for_pdf.html".format( self.request.user.username)) if os.path.isfile(usr_pdf_template_file): sourceHtml = "pdf/user_{}/serviceandorder_for_pdf.html".format( self.request.user.username) # Under templates folder else: sourceHtml = "pdf/serviceandorder_for_pdf.html" # Under templates folder print([form.cleaned_data for form in form_list]) # Get the data for the Installer from Installer table to populate email(id) and pdf(idx) idx = Profile.objects.get(user=self.request.user) #'product_id = ([form.cleaned_data for form in form_list][1].get('product_choice').id) # Get the record of the product that was selected #'product_record = ProductPrice.objects.get(pk = product_id) # Get the record of the Product Image that was selected and handle exception # if no image exists. #'try: #' img_record = Document.objects.get(id = product_record.product_image.id) #'except Exception as e: #' img_record = None #' print(type(e)) #' print("Error: No Image exists for the Product") # Calculate the daily_work_rate multiplied by the estimated_duration #'workload_cost = idx.daily_work_rate * int([form.cleaned_data for form in form_list][8].get('estimated_duration')[0]) # Calculate the total quote price for the quote #'total_quote_price = workload_cost + product_record.price # Get the records of the images file for the current user #'frecords = Document.objects.filter(user=self.request.user.username).order_by('uploaded_at') # Get customer name customer = ([form.cleaned_data for form in form_list][0].get('customer')) # Assign file name to store generated PDF outputFilename = Path( settings.BASE_DIR + "/pdf_output_archive/westchem/Report_{}_{}{}.pdf".format( idx.quote_prefix, customer.replace(" ", "_"), f"{idx.current_quote_number:05}") ) # pad with leading zeros (5 positions) # Write the form data input to a file in the folder pdf_quote_archive/user_xxxx/current_quote.txt current_quote_form_filename = Path( settings.BASE_DIR + "/pdf_output_archive/westchem/current_report_{}.txt".format( self.request.user.username)) file = open(current_quote_form_filename, 'w') #write to file for index, line in enumerate([form.cleaned_data for form in form_list]): #'if index == 1: # This code replaces the <object reference> in the form array[8] with the product_id #'string = str(line) #'firstDelPos=string.find("<") # get the position of < #'secondDelPos=string.find(">") # get the position of > #'stringAfterReplace = string.replace(string[firstDelPos:secondDelPos+1], "'" + str(product_id) + "'") #'file.write(str(stringAfterReplace) + "\n") #'else: file.write(str(line) + "\n") file.close() #close file # Generate the PDF and write to disk convertHtmlToPdf2( sourceHtml, outputFilename, { 'form_data': [form.cleaned_data for form in form_list], 'idx': idx }) # Increment the Profile.current_quote_number by 1 idx.current_quote_number = idx.current_quote_number + 1 idx.save() return HttpResponseRedirect('/reportgenerated/')