Exemple #1
0
    def get(self, request, *args, **kwargs):
        template_name = "invoice.html"

        conference = Conference.get_current()
        school = School.objects.get(pk=kwargs['pk'])
        due_date = school.registered + datetime.timedelta(days=21)
        delegate_total = sum((
            school.beginner_delegates,
            school.intermediate_delegates,
            school.advanced_delegates,
        ))
        delegate_fee = conference.delegate_fee
        delegate_fees = delegate_total*delegate_fee
        fees_owed = school.fees_owed
        fees_paid = school.fees_paid
        amount_due = fees_owed - fees_paid

        context = Context({
            "name": school.name,
            "date_registered": school.registered.strftime("%m/%d/%y"),
            "due_date": due_date.strftime("%m/%d/%y"),
            "delegate_total": delegate_total,
            "delegate_fee": delegate_fee,
            "delegate_fees": delegate_fees,
            "registration_fee": conference.registration_fee,
            "fees_owed": fees_owed,
            "fees_paid": fees_paid,
            "amount_due": amount_due})

        return render_to_pdf_response(request, template_name, context, **kwargs)
def note2pdf_response(request: HttpRequest, note: Note) -> HttpResponse:
    # Source: https://stackoverflow.com/a/48697734
    template = 'note2pdf.html'
    note.rendered_content = render_markdown(note.content)
    context = {'note': note}
    response = render_to_pdf_response(request, template, context)
    response['Content-Disposition'] = 'attachment; filename="note-%s.pdf"' % str(note.id)
    return response
Exemple #3
0
def test_pdf(request,case_id=5):
	#case = Content.objects.filter(id=1)
	#path = request.path
	#a = '/case/detail/5/'
	#path=path.split("/")
	#print(path)
	#p_num = path[-2]
	#print(int(p_num))
	case = get_object_or_404(Content,id=case_id)
	return render_to_pdf_response(request,'case/detail.html',{'case':case})
Exemple #4
0
def index(request):
	# return render(request, 'pdf.html', {})
	template = "pdf.html"
	# returns hypertext protocol: http or https
	domain = request.scheme
	domain += "://"
	# returns domain name
	domain += request.META["HTTP_HOST"]
	context_dict = {"domain":domain}
	return render_to_pdf_response(request, template, context_dict)
Exemple #5
0
def generateInventoryOrderReport(request, pk=None):
	order = get_object_or_404(InventoryOrder, pk=pk)
	if not order.completed:
		return Http404
	reports = InventoryRoomReport.objects.filter(order=order)
	entries = InventoryEntryNote.objects.filter(report__in=reports)
	present_entries = entries.filter(status='P')
	misplaced_entries = entries.filter(status='E').exclude(entry__in=present_entries.values('entry'))
	duplicate_entries = entries.filter(status='E').filter(entry__in=present_entries.values('entry'))
	missing_entries = entries.filter(status='M').exclude(entry__in=misplaced_entries.values('entry'))
	return render_to_pdf_response(request, 'inventoryOrderReportPdf.html', { 'present_entries' : present_entries , 'misplaced_entries' : misplaced_entries , 'duplicate_entries' : duplicate_entries , 'missing_entries' : missing_entries , 'order' : order})
Exemple #6
0
def signature_render(request, username, doc_type, signature_file):
    user = get_object_or_404(User, username=username)
    today = timezone.localtime(timezone.now()).date()
    pdf_args = {'name': user.get_full_name, 'date': today, 'doc_type': doc_type, 'signature_file': signature_file}
    if 'save_file' in request.GET:
        # Save the PDF as a file and redirect them back to the document list
        pdf_data = render_to_pdf('tablet/signature_render.html', pdf_args)
        pdf_file = FileUpload.objects.pdf_from_string(user, pdf_data, doc_type, user)
        os.remove(os.path.join(settings.MEDIA_ROOT, "signatures/%s" % signature_file))
        return HttpResponseRedirect(reverse('tablet_document_list', kwargs={'username': user.username}))
    return render_to_pdf_response(request, 'tablet/signature_render.html', pdf_args)
Exemple #7
0
def pdf_sea_services(request, id):
	if id:
		sea_service = ApplicationFormSeaService.objects.filter(user=id)
		sea_service_count = len(sea_service)
		template = "application_form/pdf-report-sea-service.html"
		context_dict = {}
		context_dict['sea_service'] = sea_service
		context_dict['sea_service_count'] = sea_service_count
		return render_to_pdf_response(request, template, context_dict)
	else:
		raise Http404("System Error.")
def pdf_report_sea_services(request, id):
	if id:
		print id
		appform = AppForm.objects.get(id=id)
		personaldata = appform.personal_data
		sea_service = SeaService.objects.filter(personal_data=personaldata)
		sea_service_count = len(sea_service)
		template = "application_form/pdf-report-sea-service.html"
		context_dict = {}
		context_dict['sea_service'] = sea_service
		context_dict['sea_service_count'] = sea_service_count
		return render_to_pdf_response(request, template, context_dict)
Exemple #9
0
def hello_pdf_5(request):
    query_results = Choice.objects.all()
    template_name = "main/hello2.html"
    context = {}
    context["query_results"] = query_results
    cod = request.GET.get('cod', '')
    logger.debug("cod: " + cod)
    # bts = render_to_pdf(template_name, context)
    # logger.debug(type(bts))
    # rs = base64.b64encode(bts)
    # return HttpResponse(bts, content_type='application/pdf; charset=utf-8')
    # return HttpResponse(bts, content_type='application/x-www-form-urlencoded; charset=UTF-8')
    return render_to_pdf_response(request, template_name, context)
Exemple #10
0
def landscape(request):
	# return render(request, 'pdf.html', {})
	template = "pdf-landscape.html"
	# returns hypertext protocol: http or https
	domain = request.scheme
	domain += "://"
	# returns domain name
	domain += request.META["HTTP_HOST"]
	context_dict = {"domain":domain}
	return render_to_pdf_response(request, template, context_dict)
	# template_name = "hello.html"
	# resp = HttpResponse(content_type='application/pdf')
	# result = generate_pdf('pdf.html', file_object=resp)
	# return result
Exemple #11
0
def pdf_view(request, bill_id):
    bill = Bill.objects.get(pk=bill_id)
    items = bill.billitem_set.all()
    categories = Category.objects.all()
    billitems = {}
    headeritems = {}
    for cat in categories:
        itemlist = list(items.filter(category=cat)) 
        if itemlist:
            if cat.printable:
                billitems[cat] = itemlist
            headeritems[cat] = itemlist
    context = {'bill':bill, 'billitems':billitems, 'headeritems':headeritems}
    return render_to_pdf_response(request, 'webpos/comanda.html', context)
Exemple #12
0
def cover_letter_pdf(request):
    if request.method == 'GET':
        return (request, 'cover_letter_pdf.html')
    else:

        arguments = {
            "hr_name": request.POST.get('hr_name'),
            "company": request.POST.get('company'),
            "company_url": request.POST.get('company_url'),
            "job_position": request.POST.get('job_position'),
            "job_areas": request.POST.get('job_areas'),
            "experience": request.POST.get('experience')
        }
        context = Context(arguments)
        template = 'cover_letter_pdf.html'
        return render_to_pdf_response(request, template, context)
Exemple #13
0
def pdfGeneral(request):
    imagen_path = STATICFILES_DIRS[0] + '/logos/logomopsv.png'
    imagen_bol_path = STATICFILES_DIRS[0] + '/logos/logobolivia.png'
    with open(imagen_path, 'rb') as img:
        imagen_path = b64encode(img.read())
    with open(imagen_bol_path, 'rb') as img:
        imagen_bol_path = b64encode(img.read())
    return render_to_pdf_response(
        request,
        'reportes/llamadas.html',
        {
            'today': tznow(),
            'imagen': imagen_path,
            'imagen_bol': imagen_bol_path
        }
    )
Exemple #14
0
def pdfUsuario(request):
    imagen_path = STATICFILES_DIRS[0] + '/logos/logomopsv.png'
    imagen_bol_path = STATICFILES_DIRS[0] + '/logos/logobolivia.png'
    data = Funcionario.objects.all()
    with open(imagen_path, 'rb') as img:
        imagen_path = b64encode(img.read())
    with open(imagen_bol_path, 'rb') as img:
        imagen_bol_path = b64encode(img.read())
    return render_to_pdf_response(
        request,
        'reportes/user.html',
        {
            'today': tznow(),
            'imagen': imagen_path,
            'imagen_bol': imagen_bol_path,
            'usuarios': data,
        }
    )
Exemple #15
0
def answers_view(request):
    
    context = RequestContext(request)
    checks = request.POST
    a_dict = slicedict(request.POST, 'a-')
    res = []
    for k, v in a_dict.iteritems():
        if v == 'checked':
            t = k.split('-',2)
            exercise_id = t[1]
            user_id = t[2]
            try:
                exercise = Exercise.objects.get(pk=exercise_id)
                student = User.objects.get(pk=user_id)
                student_fullname = get_moodle_fullname(student)
            
                submission = Submission.get_submission(exercise,student)
                try:
                    course.group = exercise.course.get_group(student).name
                except:
                    course.group = None
            
                questions = exercise.questions
                for q in questions:
                    try:
                        obj = Answer.get_answer(q,student)
                        q.answer = obj.answer
                        q.img = obj.img
                    except:
                        q.answer = 'No answer'
                        q.img = False
            
                res.append({
                    'exercise': exercise,
                    'questions': questions,
                    'student': student,
                    'student_fullname': student_fullname,
                    'group': course.group,
                    'submission': submission,
                })
            except:
                print 'error'
    context['res'] = res
    return render_to_pdf_response(request, "pdf_answer.html", context, 'answers', "utf-8")
Exemple #16
0
def pdfTopLlamadas(request):
    imagen_path = STATICFILES_DIRS[0] + '/logos/logomopsv.png'
    imagen_bol_path = STATICFILES_DIRS[0] + '/logos/logobolivia.png'
    top_usuario = full_complex_procedure(
        ['usuario', 'entrantes', 'salientes', 'operador'],
        'bar_complete_usuario',
        '1999-01-01',
        str(datetime.date.today())
    )
    top_oficina = full_complex_procedure(
        ['oficina', 'entrantes', 'salientes', 'operador'],
        'bar_complete_oficina',
        '1999-01-01',
        str(datetime.date.today())
    )

    print top_usuario
    print top_oficina
    c_llamadas = Llamada.objects.count()
    c_llamadas_entrantes = Llamada.objects.filter(tipo_llamada_id=1).count()
    c_llamadas_salientes = Llamada.objects.filter(tipo_llamada_id=2).count()
    c_llamadas_operador = Llamada.objects.filter(tipo_llamada_id=3).count()
    with open(imagen_path, 'rb') as img:
        imagen_path = b64encode(img.read())
    with open(imagen_bol_path, 'rb') as img:
        imagen_bol_path = b64encode(img.read())
    return render_to_pdf_response(
        request,
        'reportes/topllamadas.html',
        {
            'today': tznow(),
            'imagen': imagen_path,
            'imagen_bol': imagen_bol_path,
            'c_llamadas': c_llamadas,
            'c_llamadas_s': c_llamadas_salientes,
            'c_llamadas_e': c_llamadas_entrantes,
            'c_llamadas_o': c_llamadas_operador,
            'top_usuarios': top_usuario,
            'top_oficinas': top_oficina
        }
    )
Exemple #17
0
    def export_pdf(self, request, *args, **kwargs):
        obj = self.get_object()

        engagement_params = self.ENGAGEMENT_MAPPING.get(obj.engagement_type, {})
        pdf_serializer_class = engagement_params.get('pdf_serializer_class', None)
        template = engagement_params.get('pdf_template', None)

        if not pdf_serializer_class or not template:
            raise NotImplementedError

        # we use original serializer here for correct field labels
        serializer = self.get_serializer(
            instance=obj, serializer_class=engagement_params.get('serializer_class', None)
        )

        return render_to_pdf_response(
            request, template,
            context={'engagement': pdf_serializer_class(obj).data,
                     'serializer': serializer},
            filename='engagement_{}.pdf'.format(obj.unique_id),
        )
Exemple #18
0
def generate_letter_of_request_pdf(request, expert_request_id):
    """
    Generates letter of request PDF request
    :param request:
    :param expert_request_id:
    :return:
    """
    try:
        expert_request = ExpertRequest.objects.get(pk=expert_request_id)
        test = test_is_on()
        context = {'expert_request': expert_request,
                   'pagesize': 'A4',
                   'BASE_DIR': os.path.join(BASE_DIR, 'crppdmt/static/'),
                   'test_env': test,
                }
        return render_to_pdf_response(request, "crppdmt/pdf/letter_of_request.html", context, filename=None, encoding=u'utf-8')
    except:
        if debug_is_on():
            raise
        else:
            return render_to_response("crppdmt/error.html",
                                      {"error_description": sys.exc_info(),},
                                      context_instance=RequestContext(request))
Exemple #19
0
def pdf(request, id):
	if id:
		user_profile = UserProfile.objects.get(id=id)
		personal_data = ApplicationFormPersonalData.objects.get(name=id)
		try:
			spouse = ApplicationFormSpouse.objects.get(user=id)
		except:
			spouse = ''
		college = ApplicationFormCollege.objects.filter(user=id)
		highschool = ApplicationFormHighSchool.objects.get(user=id)
		emergency_contact = ApplicationFormEmergencyContact.objects.filter(user=id)
		visa_application = ApplicationFormVisaApplication.objects.get(user=id)
		detained = ApplicationFormDetained.objects.get(user=id)
		disciplinary_action = ApplicationFormDisciplinaryAction.objects.get(user=id)
		charged_offense = ApplicationFormChargedOffense.objects.get(user=id)
		termination = ApplicationFormTermination.objects.get(user=id)
		passport = ApplicationFormPassport.objects.get(user=id)
		sbook = ApplicationFormSbook.objects.get(user=id)
		coc = ApplicationFormCOC.objects.get(user=id)
		license = ApplicationFormLicense.objects.get(user=id)
		src = ApplicationFormSRC.objects.get(user=id)
		goc = ApplicationFormGOC.objects.get(user=id)
		us_visa = ApplicationFormUSVisa.objects.get(user=id)
		schengen_visa = ApplicationFormSchengenVisa.objects.get(user=id)
		yellow_fever = ApplicationFormYellowFever.objects.get(user=id)
		application_form = ApplicationForm.objects.get(user=id)

		flags = ApplicationFormFlagDocuments.objects.get(user=user_profile)
		certificates_documents = ApplicationFormTrainingCertificateDocuments.objects.get(user=user_profile)
			
		cayman_islands = flags.flags.filter(flags='Cayman Islands')
		marshall_islands = flags.flags.filter(flags='Marshall Islands')
		liberia = flags.flags.filter(flags='Liberia')
		cyprus = flags.flags.filter(flags='Cyprus')
		singapore = flags.flags.filter(flags='Singapore')
		greek = flags.flags.filter(flags='Greek')
		barbados = flags.flags.filter(flags='Barbados')
		german = flags.flags.filter(flags='German')
		bahamas = flags.flags.filter(flags='Bahamas')

		cop_bt = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Basic Training')
		cop_btoc = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Basic Training for Oil and Chemical Tanker')
		cop_atot = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Advance Training for Oil Tanker')
		cop_atct = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Advance Training for Chemical Tanker')
		cop_pfrb = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Proficiency in Fast Rescue Boat')
		cop_aff = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Advance Fire Fighting')
		cop_mefa = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Medical Emergency First Aid')
		cop_meca = certificates_documents.trainings_certificates.filter(trainings_certificates='	Certificate of Proficiency / Meical Care')
		cop_sso = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Ship Security Officer')
		cop_pscrb = certificates_documents.trainings_certificates.filter(trainings_certificates='	Certificate of Proficiency / Proficiency in Survival Craft and Rescue Boat')
		cop_ssa_sdsd = certificates_documents.trainings_certificates.filter(trainings_certificates='Certificate of Proficiency / Ship Security Awareness / Seafarers with Designated Security Duties')
		bt = certificates_documents.trainings_certificates.filter(trainings_certificates='Basic Training')
		pscrb = certificates_documents.trainings_certificates.filter(trainings_certificates='Proficiency in Survival Craft and Recue Boat')
		aff = certificates_documents.trainings_certificates.filter(trainings_certificates='Advance Fire Fighting')
		mefa = certificates_documents.trainings_certificates.filter(trainings_certificates='Medical Emergency First Aid')
		meca = certificates_documents.trainings_certificates.filter(trainings_certificates='Medical Care')
		pfrb = certificates_documents.trainings_certificates.filter(trainings_certificates='Proficiency in Fast Rescue Boat')
		ssbt = certificates_documents.trainings_certificates.filter(trainings_certificates='Ship Simulator and Bridge Team Work')
		brm = certificates_documents.trainings_certificates.filter(trainings_certificates='Bridge Resource Management')
		btm = certificates_documents.trainings_certificates.filter(trainings_certificates='Bridge Team Management')
		btoc = certificates_documents.trainings_certificates.filter(trainings_certificates='Basic Training for Oil and Chemical Tanker Cargo Operations')
		sbff = certificates_documents.trainings_certificates.filter(trainings_certificates='Shore Based Fire Fighting')
		atot = certificates_documents.trainings_certificates.filter(trainings_certificates='Advance Training for Oil Tanker')
		atct = certificates_documents.trainings_certificates.filter(trainings_certificates='Advance Training for Chemical Tanker')
		inmarsat = certificates_documents.trainings_certificates.filter(trainings_certificates='International Maritime Satellite')
		gmdss = certificates_documents.trainings_certificates.filter(trainings_certificates='Global Maritime Distress and Safety System')
		padams = certificates_documents.trainings_certificates.filter(trainings_certificates='Prevention of Alcohol and Drug Abuse in the Maritime Sector')
		hazmat = certificates_documents.trainings_certificates.filter(trainings_certificates='Hazardous Material')
		cow_igs = certificates_documents.trainings_certificates.filter(trainings_certificates='Crude Oil Washing / Inert Gas System')
		ers_erm = certificates_documents.trainings_certificates.filter(trainings_certificates='Engine Room Simulator with Engine Room Management')
		srroc = certificates_documents.trainings_certificates.filter(trainings_certificates='Ship Restricted Radiotelephone Operator Course')
		framo = certificates_documents.trainings_certificates.filter(trainings_certificates='FRAMO')
		sos = certificates_documents.trainings_certificates.filter(trainings_certificates='Ship Security Officer')
		soc = certificates_documents.trainings_certificates.filter(trainings_certificates='Safety Officer Course')
		bwk_ewk = certificates_documents.trainings_certificates.filter(trainings_certificates='Deck Watch Keeping / Engine Watch Keeping')
		rsc = certificates_documents.trainings_certificates.filter(trainings_certificates='Radar Simulator Course')
		ism = certificates_documents.trainings_certificates.filter(trainings_certificates='International Safety Management')
		ssmep = certificates_documents.trainings_certificates.filter(trainings_certificates='Shipboard Managerial Skills Enhancement Program')
		acni = certificates_documents.trainings_certificates.filter(trainings_certificates='Accident and Near-miss Investigation')
		ssa_sdsd = certificates_documents.trainings_certificates.filter(trainings_certificates='Ship Security Awareness / Seafarers with Designated Security Duties')
		arpa_ropa = certificates_documents.trainings_certificates.filter(trainings_certificates='Radar Navigation / Radar Plotting and use of ARPA ROPA')
		ecdis_generic = certificates_documents.trainings_certificates.filter(trainings_certificates='Electronic Chart Display and Information System')
		mlc_deck = certificates_documents.trainings_certificates.filter(trainings_certificates='Management Level Course - Deck')
		marpol = certificates_documents.trainings_certificates.filter(trainings_certificates='Marine Pollution I-VI')
		mlc_engine = certificates_documents.trainings_certificates.filter(trainings_certificates='Management Level Course - Engine')
		ecdis_specific = certificates_documents.trainings_certificates.filter(trainings_certificates='Electronic Chart Display and Information System Specific')
		ship_vetting = certificates_documents.trainings_certificates.filter(trainings_certificates='Ship Vetting')
		ship_handling = certificates_documents.trainings_certificates.filter(trainings_certificates='Ship Handling')
		maritime_eng = certificates_documents.trainings_certificates.filter(trainings_certificates='Maritime Eng.')

		domain = request.scheme
		domain += "://"
		# returns domain name
		domain += request.META["HTTP_HOST"]
		media = domain+"/media/"
		picture = media+str(application_form.picture)
		signature = media+str(application_form.signature)
		check = domain+"/static/img/check.jpg"
		uncheck = domain+"/static/img/uncheck.jpg"
		logo = domain+"/static/img/small_logo.png"

		# count essay words
		count_words = ''.join(c if c.isalnum() else ' ' for c in application_form.essay.essay).split()
		count_words = len(count_words)

		if str(personal_data.civil_status) == "Domestic Partner":
			partner = "Live-In"
		else:
			partner = "Spouse"

		template = "application_form/pdf-report.html"
		context_dict = { "appform":application_form, "personaldata":personal_data, "emergency":emergency_contact, "domain":domain, "picture":picture , "signature":signature, "check":check, "uncheck":uncheck, "logo":logo, "cayman_islands": cayman_islands, "marshall_islands": marshall_islands, "liberia":liberia, "cyprus":cyprus, "singapore":singapore, "greek":greek, "cop_bt":cop_bt, "cop_btoc":cop_btoc, "cop_atot":cop_atot, "cop_atct":cop_atct, "cop_pfrb":cop_pfrb, "cop_aff":cop_aff, "cop_mefa":cop_mefa, "cop_meca":cop_meca, "cop_sso":cop_sso, "cop_pscrb":cop_pscrb, "cop_ssa_sdsd":cop_ssa_sdsd, "bt":bt, "pscrb":pscrb, "aff":aff, "mefa":mefa, "meca":meca, "pfrb":pfrb, "ssbt":ssbt, "brm":brm, "btm":btm, "btoc":btoc, "sbff":sbff, "atot":atot, "atct":atct, "inmarsat":inmarsat, "gmdss":gmdss, "padams":padams, "hazmat":hazmat, "cow_igs":cow_igs, "ers_erm":ers_erm, "srroc":srroc, "framo":framo, "sos":sos, "soc":soc, "bwk_ewk":bwk_ewk, "rsc":rsc, "ism":ism, "ssmep":ssmep, "acni":acni, "ssa_sdsd":ssa_sdsd, "arpa_ropa":arpa_ropa, "ecdis_generic":ecdis_generic, "mlc_deck":mlc_deck, "marpol":marpol, "mlc_engine":mlc_engine, "ecdis_specific":ecdis_specific, "ship_vetting":ship_vetting, "ship_handling":ship_handling, "maritime_eng":maritime_eng, "count_words":count_words}
		context_dict['user_profile'] = user_profile
		context_dict['spouse'] = spouse
		context_dict['college'] = college
		context_dict['highschool'] = highschool
		context_dict['visa_application'] = visa_application
		context_dict['detained'] = detained
		context_dict['disciplinary_action'] = disciplinary_action
		context_dict['charged_offense'] = charged_offense
		context_dict['termination'] = termination
		context_dict['passport'] = passport
		context_dict['sbook'] = sbook
		context_dict['coc'] = coc
		context_dict['license'] = license
		context_dict['src'] = src
		context_dict['goc'] = goc
		context_dict['us_visa'] = us_visa
		context_dict['schengen_visa'] = schengen_visa
		context_dict['yellow_fever'] = yellow_fever
		context_dict['partner'] = partner
		return render_to_pdf_response(request, template, context_dict)
	else:
		raise Http404("System Error.")
Exemple #20
0
def generate_report(request, obj):
    product_type = None
    product = None
    engagement = None
    test = None
    endpoint = None
    user = Dojo_User.objects.get(id=request.user.id)

    if type(obj).__name__ == "Product":
        if request.user.is_staff or request.user in obj.authorized_users.all():
            pass  # user is authorized for this product
        else:
            raise PermissionDenied
    elif type(obj).__name__ == "Endpoint":
        if request.user.is_staff or request.user in obj.product.authorized_users.all():
            pass  # user is authorized for this product
        else:
            raise PermissionDenied
    elif type(obj).__name__ == "QuerySet":
        # authorization taken care of by only selecting findings from product user is authed to see
        pass
    else:
        if not request.user.is_staff:
            raise PermissionDenied

    report_format = request.GET.get('report_type', 'AsciiDoc')
    include_finding_notes = int(request.GET.get('include_finding_notes', 0))
    include_executive_summary = int(request.GET.get('include_executive_summary', 0))
    include_table_of_contents = int(request.GET.get('include_table_of_contents', 0))
    generate = "_generate" in request.GET

    add_breadcrumb(title="Generate Report", top_level=False, request=request)
    if type(obj).__name__ == "Product_Type":
        product_type = obj
        findings = ReportFindingFilter(request.GET, queryset=Finding.objects.filter(
            test__engagement__product__prod_type=product_type).distinct())
        filename = "product_type_finding_report.pdf"
    elif type(obj).__name__ == "Product":
        product = obj
        findings = ReportFindingFilter(request.GET, queryset=Finding.objects.filter(test__engagement__product=product,
                                                                                    ).distinct())
        filename = "product_finding_report.pdf"
    elif type(obj).__name__ == "Engagement":
        engagement = obj
        findings = ReportFindingFilter(request.GET, queryset=Finding.objects.filter(test__engagement=engagement,
                                                                                    ).distinct())
        filename = "engagement_finding_report.pdf"
    elif type(obj).__name__ == "Test":
        test = obj
        findings = ReportFindingFilter(request.GET, queryset=Finding.objects.filter(test=test).distinct())
        filename = "test_finding_report.pdf"
    elif type(obj).__name__ == "Endpoint":
        endpoint = obj
        host = endpoint.host_no_port
        endpoints = Endpoint.objects.filter(host__regex="^" + host + ":?",
                                            product=endpoint.product).distinct()

        findings = ReportFindingFilter(request.GET, queryset=Finding.objects.filter(endpoints__in=endpoints,
                                                                                    ).distinct())
        filename = "endpoint_finding_report.pdf"
    elif type(obj).__name__ == "QuerySet":
        findings = ReportAuthedFindingFilter(request.GET, queryset=obj.distinct(), user=request.user)
        filename = "finding_report.pdf"
    else:
        raise Http404()

    report_form = ReportOptionsForm()
    if len(findings) > 150:
        report_form.fields['report_type'].choices = (('AsciiDoc', 'AsciiDoc'),)

    if generate:
        report_form = ReportOptionsForm(request.GET)
        if report_format == 'AsciiDoc':
            return render(request,
                          'dojo/asciidoc_report.html',
                          {'product_type': product_type,
                           'product': product,
                           'engagement': engagement,
                           'test': test,
                           'endpoint': endpoint,
                           'findings': findings,
                           'include_finding_notes': include_finding_notes,
                           'include_executive_summary': include_executive_summary,
                           'include_table_of_contents': include_table_of_contents,
                           'user': user,
                           'title': 'Generate Report',
                           })
        elif report_format == 'PDF':
            if len(findings) <= 150:
                return render_to_pdf_response(request,
                                              'dojo/pdf_report.html',
                                              {'product_type': product_type,
                                               'product': product,
                                               'engagement': engagement,
                                               'test': test,
                                               'endpoint': endpoint,
                                               'findings': findings,
                                               'include_finding_notes': include_finding_notes,
                                               'include_executive_summary': include_executive_summary,
                                               'include_table_of_contents': include_table_of_contents,
                                               'user': user,
                                               'title': 'Generate Report'},
                                              filename=filename, )
            else:
                messages.add_message(request,
                                     messages.ERROR,
                                     'PDF reports are limited to finding counts of 150 or less. Please use the '
                                     'filters below to reduce the number of findings.',
                                     extra_tags='alert-danger')
        else:
            raise Http404()
    paged_findings = get_page_items(request, findings, 25)
    return render(request, 'dojo/request_report.html',
                  {'product_type': product_type,
                   'product': product,
                   'engagement': engagement,
                   'test': test,
                   'endpoint': endpoint,
                   'findings': findings,
                   'paged_findings': paged_findings,
                   'report_form': report_form,
                   })
Exemple #21
0
def product_endpoint_report(request, pid):
    from dojo.endpoint.views import get_endpoint_ids
    product = get_object_or_404(Product, id=pid)
    endpoints = Endpoint.objects.filter(product=product,
                                        finding__active=True,
                                        finding__verified=True,
                                        )

    if request.user.is_staff or request.user in product.authorized_users.all():
        pass  # user is authorized for this product
    else:
        raise PermissionDenied

    endpoints = EndpointReportFilter(request.GET, queryset=endpoints)
    ids = get_endpoint_ids(endpoints)
    endpoints = EndpointReportFilter(request.GET, queryset=Endpoint.objects.filter(product=product,
                                                                                   finding__active=True,
                                                                                   finding__verified=True,
                                                                                   finding__false_p=False,
                                                                                   finding__duplicate=False,
                                                                                   finding__out_of_scope=False,
                                                                                   id__in=ids).distinct())
    paged_endpoints = get_page_items(request, endpoints, 25)
    report_format = request.GET.get('report_type', 'AsciiDoc')
    include_finding_notes = int(request.GET.get('include_finding_notes', 0))
    include_executive_summary = int(request.GET.get('include_executive_summary', 0))
    include_table_of_contents = int(request.GET.get('include_table_of_contents', 0))
    generate = "_generate" in request.GET
    add_breadcrumb(parent=product, title="Vulnerable Product Endpoints Report", top_level=False, request=request)
    report_form = ReportOptionsForm()
    if len(endpoints) > 50:
        report_form.fields['report_type'].choices = (('AsciiDoc', 'AsciiDoc'),)

    if generate:
        report_form = ReportOptionsForm(request.GET)
        if report_format == 'AsciiDoc':
            return render(request,
                          'dojo/asciidoc_report.html',
                          {'product_type': None,
                           'product': product,
                           'engagement': None,
                           'test': None,
                           'endpoints': endpoints,
                           'endpoint': None,
                           'findings': None,
                           'include_finding_notes': include_finding_notes,
                           'include_executive_summary': include_executive_summary,
                           'include_table_of_contents': include_table_of_contents,
                           'user': request.user,
                           'title': 'Generate Report',
                           })
        elif report_format == 'PDF':
            if len(endpoints) <= 50:
                return render_to_pdf_response(request,
                                              'dojo/pdf_report.html',
                                              {'product_type': None,
                                               'product': product,
                                               'engagement': None,
                                               'test': None,
                                               'endpoints': endpoints,
                                               'endpoint': None,
                                               'findings': None,
                                               'include_finding_notes': include_finding_notes,
                                               'include_executive_summary': include_executive_summary,
                                               'include_table_of_contents': include_table_of_contents,
                                               'user': request.user,
                                               'title': 'Generate Report', },
                                              filename='product_endpoint_report', )
            else:
                messages.add_message(request,
                                     messages.ERROR,
                                     'PDF reports are limited to endpoint counts of 50 or less. Please use the '
                                     'filters below to reduce the number of endpoints.',
                                     extra_tags='alert-danger')
        else:
            raise Http404()

    return render(request,
                  'dojo/request_endpoint_report.html',
                  {"endpoints": paged_endpoints,
                   "filtered": endpoints,
                   'report_form': report_form,
                   "name": "Vulnerable Product Endpoints",
                   })
Exemple #22
0
def generateLiquidationApplication(request, pk=None):
	liquidation = get_object_or_404(Liquidation, pk=pk)
	entries = liquidation.entries.all()
	return render_to_pdf_response(request, 'liquidationApplicationPdf.html', { 'entries' : entries })
def pdf_report(request, id):
	if id:
		appform = AppForm.objects.get(id=id)
		appdetails = appform.app_details
		appsource = appdetails.appsource
		personaldata = appform.personal_data
		education = appform.education
		emergency = appform.emergency_contact
		backgroundinfo = appform.background_information
		certificatesdocuments = appform.certificates_documents
			
		cayman_islands = personaldata.flags.filter(flags='Cayman Islands')
		marshall_islands = personaldata.flags.filter(flags='Marshall Islands')
		liberia = personaldata.flags.filter(flags='Liberia')
		cyprus = personaldata.flags.filter(flags='Cyprus')
		singapore = personaldata.flags.filter(flags='Singapore')
		greek = personaldata.flags.filter(flags='Greek')

		cop_bt = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Basic Training')
		cop_btoc = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Basic Training for Oil and Chemical Tanker')
		cop_atot = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Advance Training for Oil Tanker')
		cop_atct = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Advance Training for Chemical Tanker')
		cop_pfrb = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Proficiency in Fast Rescue Boat')
		cop_aff = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Advance Fire Fighting')
		cop_mefa = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Medical Emergency First Aid')
		cop_meca = personaldata.training_certificates.filter(trainings_certificates='	Certificate of Proficiency / Meical Care')
		cop_sso = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Ship Security Officer')
		cop_pscrb = personaldata.training_certificates.filter(trainings_certificates='	Certificate of Proficiency / Proficiency in Survival Craft and Rescue Boat')
		cop_ssa_sdsd = personaldata.training_certificates.filter(trainings_certificates='Certificate of Proficiency / Ship Security Awareness / Seafarers with Designated Security Duties')
		bt = personaldata.training_certificates.filter(trainings_certificates='Basic Training')
		pscrb = personaldata.training_certificates.filter(trainings_certificates='Proficiency in Survival Craft and Recue Boat')
		aff = personaldata.training_certificates.filter(trainings_certificates='Advance Fire Fighting')
		mefa = personaldata.training_certificates.filter(trainings_certificates='Medical Emergency First Aid')
		meca = personaldata.training_certificates.filter(trainings_certificates='Medical Care')
		pfrb = personaldata.training_certificates.filter(trainings_certificates='Proficiency in Fast Rescue Boat')
		ssbt = personaldata.training_certificates.filter(trainings_certificates='Ship Simulator and Bridge Team Work')
		brm = personaldata.training_certificates.filter(trainings_certificates='Bridge Resource Management')
		btm = personaldata.training_certificates.filter(trainings_certificates='Bridge Team Management')
		btoc = personaldata.training_certificates.filter(trainings_certificates='Basic Training for Oil and Chemical Tanker Cargo Operations')
		sbff = personaldata.training_certificates.filter(trainings_certificates='Shore Based Fire Fighting')
		atot = personaldata.training_certificates.filter(trainings_certificates='Advance Training for Oil Tanker')
		atct = personaldata.training_certificates.filter(trainings_certificates='Advance Training for Chemical Tanker')
		inmarsat = personaldata.training_certificates.filter(trainings_certificates='International Maritime Satellite')
		gmdss = personaldata.training_certificates.filter(trainings_certificates='Global Maritime Distress and Safety System')
		padams = personaldata.training_certificates.filter(trainings_certificates='Prevention of Alcohol and Drug Abuse in the Maritime Sector')
		hazmat = personaldata.training_certificates.filter(trainings_certificates='Hazardous Material')
		cow_igs = personaldata.training_certificates.filter(trainings_certificates='Crude Oil Washing / Inert Gas System')
		ers_erm = personaldata.training_certificates.filter(trainings_certificates='Engine Room Simulator with Engine Room Management')
		srroc = personaldata.training_certificates.filter(trainings_certificates='Ship Restricted Radiotelephone Operator Course')
		framo = personaldata.training_certificates.filter(trainings_certificates='FRAMO')
		sos = personaldata.training_certificates.filter(trainings_certificates='Ship Security Officer')
		soc = personaldata.training_certificates.filter(trainings_certificates='Safety Officer Course')
		bwk_ewk = personaldata.training_certificates.filter(trainings_certificates='Deck Watch Keeping / Engine Watch Keeping')
		rsc = personaldata.training_certificates.filter(trainings_certificates='Radar Simulator Course')
		ism = personaldata.training_certificates.filter(trainings_certificates='International Safety Management')
		ssmep = personaldata.training_certificates.filter(trainings_certificates='Shipboard Managerial Skills Enhancement Program')
		acni = personaldata.training_certificates.filter(trainings_certificates='Accident and Near-miss Investigation')
		ssa_sdsd = personaldata.training_certificates.filter(trainings_certificates='Ship Security Awareness / Seafarers with Designated Security Duties')
		arpa_ropa = personaldata.training_certificates.filter(trainings_certificates='Radar Navigation / Radar Plotting and use of ARPA ROPA')
		ecdis_generic = personaldata.training_certificates.filter(trainings_certificates='Electronic Chart Display and Information System')
		mlc_deck = personaldata.training_certificates.filter(trainings_certificates='Management Level Course - Deck')
		marpol = personaldata.training_certificates.filter(trainings_certificates='Marine Pollution I-VI')
		mlc_engine = personaldata.training_certificates.filter(trainings_certificates='Management Level Course - Engine')
		ecdis_specific = personaldata.training_certificates.filter(trainings_certificates='Electronic Chart Display and Information System Specific')
		ship_vetting = personaldata.training_certificates.filter(trainings_certificates='Ship Vetting')
		ship_handling = personaldata.training_certificates.filter(trainings_certificates='Ship Handling')
		maritime_eng = personaldata.training_certificates.filter(trainings_certificates='Maritime Eng.')

		domain = request.scheme
		domain += "://"
		# returns domain name
		domain += request.META["HTTP_HOST"]
		media = domain+"/media/"
		picture = media+str(appdetails.picture)
		signature = media+str(appform.signatures)
		check = domain+"/static/img/check.jpg"
		uncheck = domain+"/static/img/uncheck.jpg"
		logo = domain+"/static/img/small_logo.png"

		# count essay words
		count_words = ''.join(c if c.isalnum() else ' ' for c in appform.essay).split()
		count_words = len(count_words)

		template = "application_form/pdf-report.html"
		context_dict = { "appform":appform, "appdetails":appdetails, "personaldata":personaldata, "education":education, "emergency":emergency, "backgroundinfo":backgroundinfo, "certificatesdocuments":certificatesdocuments, "domain":domain, "picture":picture , "signature":signature, "check":check, "uncheck":uncheck, "logo":logo, "appsource":appsource, "cayman_islands": cayman_islands, "marshall_islands": marshall_islands, "liberia":liberia, "cyprus":cyprus, "singapore":singapore, "greek":greek, "cop_bt":cop_bt, "cop_btoc":cop_btoc, "cop_atot":cop_atot, "cop_atct":cop_atct, "cop_pfrb":cop_pfrb, "cop_aff":cop_aff, "cop_mefa":cop_mefa, "cop_meca":cop_meca, "cop_sso":cop_sso, "cop_pscrb":cop_pscrb, "cop_ssa_sdsd":cop_ssa_sdsd, "bt":bt, "pscrb":pscrb, "aff":aff, "mefa":mefa, "meca":meca, "pfrb":pfrb, "ssbt":ssbt, "brm":brm, "btm":btm, "btoc":btoc, "sbff":sbff, "atot":atot, "atct":atct, "inmarsat":inmarsat, "gmdss":gmdss, "padams":padams, "hazmat":hazmat, "cow_igs":cow_igs, "ers_erm":ers_erm, "srroc":srroc, "framo":framo, "sos":sos, "soc":soc, "bwk_ewk":bwk_ewk, "rsc":rsc, "ism":ism, "ssmep":ssmep, "acni":acni, "ssa_sdsd":ssa_sdsd, "arpa_ropa":arpa_ropa, "ecdis_generic":ecdis_generic, "mlc_deck":mlc_deck, "marpol":marpol, "mlc_engine":mlc_engine, "ecdis_specific":ecdis_specific, "ship_vetting":ship_vetting, "ship_handling":ship_handling, "maritime_eng":maritime_eng, "count_words":count_words}
		return render_to_pdf_response(request, template, context_dict)
	else:
		raise Http404("System Error.")