How to use order method in Pytest

Best Python code snippet using pytest

order_proposal_views.py

Source:order_proposal_views.py Github

copy

Full Screen

1import json2import os3from django.contrib import messages4from django.core.mail import send_mail5from django.db.models import Q6from django.http import HttpResponse, HttpResponseForbidden, HttpResponseBadRequest, HttpResponseNotFound7from django.shortcuts import redirect8from django.shortcuts import render9from django.template import defaultfilters10from django.template.loader import render_to_string11from django.urls import reverse12from django.views.decorators.csrf import csrf_exempt13from app import settings14from app.models import Operators, Orders, Attachments, Order_Proposals, Notifications15from app.utils import Utils16from backend.forms.order_forms import OrderUploadAttachmentForm17from backend.forms.order_proposal_forms import OrderProposalSearchIndexForm, OrderProposalCreateForm, \18 OrderProposalViewForm, OrderProposalEvaluateForm, OrderProposalSelectForm19from backend.tables.order_proposal_tables import Order_ProposalsTable20# noinspection PyUnusedLocal21def index(request, pk):22 template_url = 'order-proposals/index.html'23 operator = Operators.login_required(request)24 if operator is None:25 Operators.set_redirect_field_name(request, request.path)26 return redirect(reverse("operators_signin"))27 else:28 auth_permissions = Operators.get_auth_permissions(operator)29 if settings.ACCESS_PERMISSION_ORDER_VIEW in auth_permissions.values():30 try:31 model = Orders.objects.get(order_id=pk)32 search_form = OrderProposalSearchIndexForm(request.POST or None)33 objects = None34 objects = Order_Proposals.objects.filter(orders_order_id=model.order_id).exclude(35 order_proposal_supplier_rf_number='').all()36 if request.method == 'POST' and search_form.is_valid():37 display_search = True38 table = Order_ProposalsTable(objects)39 else:40 display_search = False41 table = Order_ProposalsTable(objects)42 table.set_auth_permissions(auth_permissions)43 return render(44 request, template_url,45 {46 'section': settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,47 'title': Order_Proposals.TITLE,48 'name': Order_Proposals.NAME,49 'operator': operator,50 'auth_permissions': auth_permissions,51 'table': table,52 'search_form': search_form,53 'display_search': display_search,54 'model': model,55 'index_url': reverse("orders_index"),56 'view_url': reverse("orders_view", kwargs={'pk': pk}),57 'reload_url': reverse("order_proposals_index", kwargs={'pk': pk}),58 'select_single_url': reverse("order_proposals_select_single"),59 'select_multiple_url': reverse("order_proposals_select_multiple"),60 }61 )62 except(TypeError, ValueError, OverflowError, Orders.DoesNotExist):63 return HttpResponseNotFound('Not Found', content_type='text/plain')64 else:65 return HttpResponseForbidden('Forbidden', content_type='text/plain')66@csrf_exempt67# noinspection PyUnusedLocal68def select_single(request):69 if request.is_ajax():70 operator = Operators.login_required(request)71 if operator is None:72 # Operators.set_redirect_field_name(request, request.path)73 # return redirect(reverse("operators_signin"))74 return HttpResponse('signin', content_type='text/plain')75 else:76 auth_permissions = Operators.get_auth_permissions(operator)77 action = request.POST['action']78 id = request.POST['id']79 if action != '' and id is not None:80 if action == 'order-proposal-approve':81 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():82 try:83 model = Order_Proposals.objects.get(order_proposal_id=id)84 model.order_proposal_approval_updated_at = Utils.get_current_datetime_utc()85 model.order_proposal_approval_updated_id = operator.operator_id86 model.order_proposal_approval_updated_by = operator.operator_name87 model.order_proposal_approval_updated_department = operator.operator_department88 model.order_proposal_approval_updated_role = operator.operator_role89 model.order_proposal_status = Order_Proposals.STATUS_APPROVED90 model.save()91 # sending notification to COP and OPM92 operators = Operators.objects.filter(93 Q(operator_role=Operators.ROLE_COP) |94 Q(operator_role=Operators.ROLE_OPM))95 for item in operators:96 Notifications.add_notification(97 Notifications.TYPE_OPERATOR,98 operator.operator_id,99 Notifications.TYPE_OPERATOR,100 item.operator_id,101 Notifications.TYPE_ORDER_PROPOSAL,102 model.order_proposal_id,103 "Some vendors are selected to review.",104 "/backend/order-proposals/index/" + str(model.orders_order_id) + "/"105 )106 messages.success(request, 'Updated successfully.')107 except(TypeError, ValueError, OverflowError, Order_Proposals.DoesNotExist):108 return HttpResponseBadRequest('Bad Request', content_type='text/plain')109 else:110 return HttpResponseForbidden('Forbidden', content_type='text/plain')111 if action == 'order-proposal-reject':112 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():113 try:114 model = Order_Proposals.objects.get(order_proposal_id=id)115 model.order_proposal_approval_updated_at = Utils.get_current_datetime_utc()116 model.order_proposal_approval_updated_id = operator.operator_id117 model.order_proposal_approval_updated_by = operator.operator_name118 model.order_proposal_approval_updated_department = operator.operator_department119 model.order_proposal_approval_updated_role = operator.operator_role120 model.order_proposal_status = Order_Proposals.STATUS_REJECTED121 model.save()122 messages.success(request, 'Updated successfully.')123 except(TypeError, ValueError, OverflowError, Order_Proposals.DoesNotExist):124 return HttpResponseBadRequest('Bad Request', content_type='text/plain')125 else:126 return HttpResponseForbidden('Forbidden', content_type='text/plain')127 return HttpResponse('success', content_type='text/plain')128 else:129 return HttpResponseBadRequest('Bad Request', content_type='text/plain')130 else:131 return HttpResponseForbidden('Forbidden', content_type='text/plain')132@csrf_exempt133# noinspection PyUnusedLocal134def select_multiple(request):135 if request.is_ajax():136 operator = Operators.login_required(request)137 if operator is None:138 # Operators.set_redirect_field_name(request, request.path)139 # return redirect(reverse("operators_signin"))140 return HttpResponse('signin', content_type='text/plain')141 else:142 auth_permissions = Operators.get_auth_permissions(operator)143 action = request.POST['action']144 ids = request.POST['ids']145 try:146 ids = ids.split(",")147 except(TypeError, ValueError, OverflowError):148 ids = None149 if action != '' and ids is not None:150 return HttpResponse('success', content_type='text/plain')151 else:152 return HttpResponseBadRequest('Bad Request', content_type='text/plain')153 else:154 return HttpResponseForbidden('Forbidden', content_type='text/plain')155# noinspection PyUnusedLocal, PyShadowingBuiltins156def create(request, pk, code):157 template_url = 'order-proposals/create.html'158 try:159 order = Orders.objects.get(order_id=pk)160 if code == str(0):161 model = Order_Proposals()162 model.order_proposal_code = Order_Proposals.generate_random_number('order_proposal_code', 8)163 model.orders_order_id = order.order_id164 model.order_proposal_supplier_category = order.order_supplier_category165 model.order_proposal_supplier_company_type = ''166 model.order_proposal_supplier_title = ''167 model.order_proposal_supplier_details = ''168 model.order_proposal_supplier_rf_number = ''169 model.order_proposal_supplier_proposal_title = ''170 model.order_proposal_supplier_legal_representatives = ''171 model.order_proposal_supplier_address_plot_no = ''172 model.order_proposal_supplier_address_street = ''173 model.order_proposal_supplier_address_av_no = ''174 model.order_proposal_supplier_address_sector = ''175 model.order_proposal_supplier_address_district = ''176 model.order_proposal_supplier_address_country = ''177 model.order_proposal_supplier_contact_phone_number = ''178 model.order_proposal_supplier_contact_email_id = ''179 model.order_proposal_supplier_tin_number = ''180 model.order_proposal_supplier_bank_account_details = ''181 model.order_proposal_supplier_previous_reference1_name = ''182 model.order_proposal_supplier_previous_reference1_contact_person = ''183 model.order_proposal_supplier_previous_reference1_contact_number = ''184 model.order_proposal_supplier_previous_reference1_contact_email_id = ''185 model.order_proposal_supplier_previous_reference2_name = ''186 model.order_proposal_supplier_previous_reference2_contact_person = ''187 model.order_proposal_supplier_previous_reference2_contact_number = ''188 model.order_proposal_supplier_previous_reference2_contact_email_id = ''189 model.order_proposal_supplier_previous_reference3_name = ''190 model.order_proposal_supplier_previous_reference3_contact_person = ''191 model.order_proposal_supplier_previous_reference3_contact_number = ''192 model.order_proposal_supplier_previous_reference3_contact_email_id = ''193 model.order_proposal_cost = 0194 model.order_proposal_evaluated_score = 0195 model.order_proposal_evaluation_details = ''196 model.order_proposal_created_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE197 model.order_proposal_created_id = 0198 model.order_proposal_created_by = ''199 model.order_proposal_created_department = ''200 model.order_proposal_created_role = ''201 model.order_proposal_updated_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE202 model.order_proposal_updated_id = 0203 model.order_proposal_updated_by = ''204 model.order_proposal_updated_department = ''205 model.order_proposal_updated_role = ''206 model.order_proposal_evaluated_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE207 model.order_proposal_evaluated_id = ''208 model.order_proposal_evaluated_by = ''209 model.order_proposal_evaluated_department = ''210 model.order_proposal_evaluated_role = ''211 model.order_proposal_approval_updated_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE212 model.order_proposal_approval_updated_id = ''213 model.order_proposal_approval_updated_by = ''214 model.order_proposal_approval_updated_department = ''215 model.order_proposal_approval_updated_role = ''216 model.order_proposal_selected_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE217 model.order_proposal_selected_id = 0218 model.order_proposal_selected_by = ''219 model.order_proposal_selected_department = ''220 model.order_proposal_selected_role = ''221 model.order_proposal_acknowledged_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE222 model.order_proposal_acknowledged_id = ''223 model.order_proposal_acknowledged_by = ''224 model.order_proposal_acknowledged_department = ''225 model.order_proposal_acknowledged_role = ''226 model.order_proposal_status = Order_Proposals.STATUS_PENDING227 # noinspection PyCallByClass,PyTypeChecker228 model.save('Created')229 else:230 model = Order_Proposals.objects.get(order_proposal_code=code)231 attachments = Attachments.objects.filter(232 attachment_model=Attachments.MODEL_ORDERS,233 attachment_model_id=order.order_id,234 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_BUSINESS_LICENSE,235 ).order_by('-attachment_id').all()236 attachment1 = ''237 if attachments.count() != 0:238 attachment1 = attachments[0]239 attachments = Attachments.objects.filter(240 attachment_model=Attachments.MODEL_ORDERS,241 attachment_model_id=order.order_id,242 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_OFFER_LETTER,243 ).order_by('-attachment_id').all()244 attachment2 = ''245 if attachments.count() != 0:246 attachment2 = attachments[0]247 attachments = Attachments.objects.filter(248 attachment_model=Attachments.MODEL_ORDERS,249 attachment_model_id=order.order_id,250 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_QUOTATION,251 ).order_by('-attachment_id').all()252 attachment3 = ''253 if attachments.count() != 0:254 attachment3 = attachments[0]255 attachments = Attachments.objects.filter(256 attachment_model=Attachments.MODEL_ORDERS,257 attachment_model_id=order.order_id,258 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_VAT_REGISTRATION,259 ).order_by('-attachment_id').all()260 attachment4 = ''261 if attachments.count() != 0:262 attachment4 = attachments[0]263 attachments = Attachments.objects.filter(264 attachment_model=Attachments.MODEL_ORDERS,265 attachment_model_id=order.order_id,266 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_OTHER_DOCUMENT,267 attachment_number=1,268 ).order_by('-attachment_id').all()269 attachment5 = ''270 if attachments.count() != 0:271 attachment5 = attachments[0]272 attachments = Attachments.objects.filter(273 attachment_model=Attachments.MODEL_ORDERS,274 attachment_model_id=order.order_id,275 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_OTHER_DOCUMENT,276 attachment_number=2,277 ).order_by('-attachment_id').all()278 attachment6 = ''279 if attachments.count() != 0:280 attachment6 = attachments[0]281 attachments = Attachments.objects.filter(282 attachment_model=Attachments.MODEL_ORDERS,283 attachment_model_id=order.order_id,284 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_REFERENCE_DOCUMENT,285 attachment_number=1,286 ).order_by('-attachment_id').all()287 attachment7 = ''288 if attachments.count() != 0:289 attachment7 = attachments[0]290 attachments = Attachments.objects.filter(291 attachment_model=Attachments.MODEL_ORDERS,292 attachment_model_id=order.order_id,293 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_REFERENCE_DOCUMENT,294 attachment_number=2,295 ).order_by('-attachment_id').all()296 attachment8 = ''297 if attachments.count() != 0:298 attachment8 = attachments[0]299 attachments = Attachments.objects.filter(300 attachment_model=Attachments.MODEL_ORDERS,301 attachment_model_id=order.order_id,302 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_REFERENCE_DOCUMENT,303 attachment_number=3,304 ).order_by('-attachment_id').all()305 attachment9 = ''306 if attachments.count() != 0:307 attachment9 = attachments[0]308 if request.method == 'POST':309 form = OrderProposalCreateForm(request.POST)310 # noinspection PyArgumentList311 if form.is_valid():312 model.order_proposal_supplier_company_type = form.cleaned_data['company_type']313 model.order_proposal_supplier_title = form.cleaned_data['title']314 model.order_proposal_supplier_details = form.cleaned_data['details']315 model.order_proposal_supplier_rf_number = form.cleaned_data['rf_number']316 model.order_proposal_supplier_proposal_title = form.cleaned_data['proposal_title']317 model.order_proposal_supplier_legal_representatives = form.cleaned_data['legal_representatives']318 model.order_proposal_supplier_address_plot_no = form.cleaned_data['address_plot_no']319 model.order_proposal_supplier_address_street = form.cleaned_data['address_street']320 model.order_proposal_supplier_address_av_no = form.cleaned_data['address_av_no']321 model.order_proposal_supplier_address_sector = form.cleaned_data['address_sector']322 model.order_proposal_supplier_address_district = form.cleaned_data['address_district']323 model.order_proposal_supplier_address_country = form.cleaned_data['address_country']324 model.order_proposal_supplier_contact_phone_number = form.cleaned_data['contact_phone_number']325 model.order_proposal_supplier_contact_email_id = form.cleaned_data['contact_email_id']326 model.order_proposal_supplier_tin_number = form.cleaned_data['tin_number']327 model.order_proposal_supplier_bank_account_details = form.cleaned_data['bank_account_details']328 model.order_proposal_supplier_previous_reference1_name = form.cleaned_data['previous_reference1_name']329 model.order_proposal_supplier_previous_reference1_contact_person = form.cleaned_data[330 'previous_reference1_contact_person']331 model.order_proposal_supplier_previous_reference1_contact_number = form.cleaned_data[332 'previous_reference1_contact_number']333 model.order_proposal_supplier_previous_reference1_contact_email_id = form.cleaned_data[334 'previous_reference1_contact_email_id']335 model.order_proposal_supplier_previous_reference2_name = form.cleaned_data['previous_reference2_name']336 model.order_proposal_supplier_previous_reference2_contact_person = form.cleaned_data[337 'previous_reference2_contact_person']338 model.order_proposal_supplier_previous_reference2_contact_number = form.cleaned_data[339 'previous_reference2_contact_number']340 model.order_proposal_supplier_previous_reference2_contact_email_id = form.cleaned_data[341 'previous_reference2_contact_email_id']342 model.order_proposal_supplier_previous_reference3_name = form.cleaned_data['previous_reference3_name']343 model.order_proposal_supplier_previous_reference3_contact_person = form.cleaned_data[344 'previous_reference3_contact_person']345 model.order_proposal_supplier_previous_reference3_contact_number = form.cleaned_data[346 'previous_reference3_contact_number']347 model.order_proposal_supplier_previous_reference3_contact_email_id = form.cleaned_data[348 'previous_reference3_contact_email_id']349 if model.order_proposal_created_at == settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE:350 model.order_proposal_created_at = Utils.get_current_datetime_utc()351 model.order_proposal_created_id = 0352 model.order_proposal_created_by = ''353 model.order_proposal_created_department = ''354 model.order_proposal_created_role = ''355 model.order_proposal_updated_at = Utils.get_current_datetime_utc()356 model.order_proposal_updated_id = 0357 model.order_proposal_updated_by = ''358 model.order_proposal_updated_department = ''359 model.order_proposal_updated_role = ''360 model.order_proposal_evaluated_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE361 model.order_proposal_evaluated_id = ''362 model.order_proposal_evaluated_by = ''363 model.order_proposal_evaluated_department = ''364 model.order_proposal_evaluated_role = ''365 model.order_proposal_approval_updated_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE366 model.order_proposal_approval_updated_id = ''367 model.order_proposal_approval_updated_by = ''368 model.order_proposal_approval_updated_department = ''369 model.order_proposal_approval_updated_role = ''370 model.order_proposal_acknowledged_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE371 model.order_proposal_acknowledged_id = ''372 model.order_proposal_acknowledged_by = ''373 model.order_proposal_acknowledged_department = ''374 model.order_proposal_acknowledged_role = ''375 model.order_proposal_status = Order_Proposals.STATUS_PENDING376 # noinspection PyCallByClass,PyTypeChecker377 model.save()378 # sending notification to Officer379 if order.order_assigned_to_id != str(0):380 operators = Operators.objects.all().filter(381 Q(operator_id=order.order_assigned_to_id)382 )383 else:384 operators = Operators.objects.all().filter(385 Q(operator_department=Operators.DEPARTMENT_DAF) &386 Q(operator_role=order.order_assigned_to_role)387 )388 for item in operators:389 Notifications.add_notification(390 Notifications.TYPE_SUPPLIER,391 model.order_proposal_id,392 Notifications.TYPE_OPERATOR,393 item.operator_id,394 Notifications.TYPE_ORDER_PROPOSAL,395 model.order_proposal_id,396 "Submitted a proposal to evaluate.",397 "/backend/order-proposals/view/internal/" + str(model.order_proposal_id) + "/"398 )399 # sending email confirmation mail400 if settings.IS_LOCAL:401 domain = settings.BACKEND_DOMAIN_LOCAL402 logo_url = settings.STATIC_LOCAL + "app/logo-transparent-white.png"403 else:404 domain = settings.BACKEND_DOMAIN_PROD405 logo_url = settings.STATIC_PROD + "app/logo-transparent-white.png"406 # contact_url = '{domain}/{path}'.format(domain=domain, path=settings.CONTACT_URL)407 contact_url = settings.APP_CONSTANT_COMPANY_WEBSITE408 link_url = '{domain}/{path}'.format(409 domain=domain,410 path="order-proposals/create/" + str(model.orders_order_id) + "/" + str(411 model.order_proposal_code) + "/"412 )413 link_name = "View Details"414 html_content = render_to_string(415 'email/email-info-with-link.html',416 {417 'logo_url': logo_url,418 'contact_url': contact_url,419 'link_url': link_url,420 'link_name': link_name,421 'name': model.order_proposal_supplier_title,422 'message': 'Thank you for submitting your proposal, we will review your proposal and get back to you soon.',423 }424 )425 send_mail(426 settings.EMAIL_NOTIFICATION_SUBJECT,427 settings.EMAIL_NOTIFICATION_MESSAGE,428 settings.APP_CONSTANT_ADMIN_SUPPORT_EMAIL_ID,429 [model.order_proposal_supplier_contact_email_id],430 fail_silently=False,431 html_message=html_content,432 )433 messages.info(request,434 'Your proposal request has been submitted successfully.')435 return redirect(436 reverse("order_proposals_create", args=[model.orders_order_id, model.order_proposal_code]))437 else:438 messages.error(request, str(form.errors))439 return render(440 request, template_url,441 {442 'section': settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,443 'title': Orders.TITLE,444 'name': Orders.NAME,445 'form': form,446 'model': model,447 'order': order,448 'select_single_url': reverse("orders_select_single_external"),449 'attachment1': attachment1,450 'attachment2': attachment2,451 'attachment3': attachment3,452 'attachment4': attachment4,453 'attachment5': attachment5,454 'attachment6': attachment6,455 'attachment7': attachment7,456 'attachment8': attachment8,457 'attachment9': attachment9,458 }459 )460 else:461 if model.order_proposal_status == Order_Proposals.STATUS_PENDING:462 form = OrderProposalCreateForm(463 initial={464 'company_type': model.order_proposal_supplier_company_type,465 'title': model.order_proposal_supplier_title,466 'details': model.order_proposal_supplier_details,467 'rf_number': model.order_proposal_supplier_rf_number,468 'proposal_title': model.order_proposal_supplier_proposal_title,469 'legal_representatives': model.order_proposal_supplier_legal_representatives,470 'address_plot_no': model.order_proposal_supplier_address_plot_no,471 'address_street': model.order_proposal_supplier_address_street,472 'address_av_no': model.order_proposal_supplier_address_av_no,473 'address_sector': model.order_proposal_supplier_address_sector,474 'address_district': model.order_proposal_supplier_address_district,475 'address_country': model.order_proposal_supplier_address_country,476 'contact_phone_number': model.order_proposal_supplier_contact_phone_number,477 'contact_email_id': model.order_proposal_supplier_contact_email_id,478 'tin_number': model.order_proposal_supplier_tin_number,479 'bank_account_details': model.order_proposal_supplier_bank_account_details,480 'previous_reference1_name': model.order_proposal_supplier_previous_reference1_name,481 'previous_reference1_contact_person': model.order_proposal_supplier_previous_reference1_contact_person,482 'previous_reference1_contact_number': model.order_proposal_supplier_previous_reference1_contact_number,483 'previous_reference1_contact_email_id': model.order_proposal_supplier_previous_reference1_contact_email_id,484 'previous_reference2_name': model.order_proposal_supplier_previous_reference2_name,485 'previous_reference2_contact_person': model.order_proposal_supplier_previous_reference2_contact_person,486 'previous_reference2_contact_number': model.order_proposal_supplier_previous_reference2_contact_number,487 'previous_reference2_contact_email_id': model.order_proposal_supplier_previous_reference2_contact_email_id,488 'previous_reference3_name': model.order_proposal_supplier_previous_reference3_name,489 'previous_reference3_contact_person': model.order_proposal_supplier_previous_reference3_contact_person,490 'previous_reference3_contact_number': model.order_proposal_supplier_previous_reference3_contact_number,491 'previous_reference3_contact_email_id': model.order_proposal_supplier_previous_reference3_contact_email_id,492 }493 )494 else:495 template_url = 'order-proposals/view.html'496 form = OrderProposalViewForm(497 initial={498 'company_type': model.order_proposal_supplier_company_type,499 'title': model.order_proposal_supplier_title,500 'details': model.order_proposal_supplier_details,501 'rf_number': model.order_proposal_supplier_rf_number,502 'proposal_title': model.order_proposal_supplier_proposal_title,503 'legal_representatives': model.order_proposal_supplier_legal_representatives,504 'address_plot_no': model.order_proposal_supplier_address_plot_no,505 'address_street': model.order_proposal_supplier_address_street,506 'address_av_no': model.order_proposal_supplier_address_av_no,507 'address_sector': model.order_proposal_supplier_address_sector,508 'address_district': model.order_proposal_supplier_address_district,509 'address_country': model.order_proposal_supplier_address_country,510 'contact_phone_number': model.order_proposal_supplier_contact_phone_number,511 'contact_email_id': model.order_proposal_supplier_contact_email_id,512 'tin_number': model.order_proposal_supplier_tin_number,513 'bank_account_details': model.order_proposal_supplier_bank_account_details,514 'previous_reference1_name': model.order_proposal_supplier_previous_reference1_name,515 'previous_reference1_contact_person': model.order_proposal_supplier_previous_reference1_contact_person,516 'previous_reference1_contact_number': model.order_proposal_supplier_previous_reference1_contact_number,517 'previous_reference1_contact_email_id': model.order_proposal_supplier_previous_reference1_contact_email_id,518 'previous_reference2_name': model.order_proposal_supplier_previous_reference2_name,519 'previous_reference2_contact_person': model.order_proposal_supplier_previous_reference2_contact_person,520 'previous_reference2_contact_number': model.order_proposal_supplier_previous_reference2_contact_number,521 'previous_reference2_contact_email_id': model.order_proposal_supplier_previous_reference2_contact_email_id,522 'previous_reference3_name': model.order_proposal_supplier_previous_reference3_name,523 'previous_reference3_contact_person': model.order_proposal_supplier_previous_reference3_contact_person,524 'previous_reference3_contact_number': model.order_proposal_supplier_previous_reference3_contact_number,525 'previous_reference3_contact_email_id': model.order_proposal_supplier_previous_reference3_contact_email_id,526 }527 )528 return render(529 request, template_url,530 {531 'section': settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,532 'title': Orders.TITLE,533 'name': Orders.NAME,534 'form': form,535 'model': model,536 'order': order,537 'select_single_url': reverse("orders_select_single_external"),538 'attachment1': attachment1,539 'attachment2': attachment2,540 'attachment3': attachment3,541 'attachment4': attachment4,542 'attachment5': attachment5,543 'attachment6': attachment6,544 'attachment7': attachment7,545 'attachment8': attachment8,546 'attachment9': attachment9,547 }548 )549 except(TypeError, ValueError, OverflowError, Orders.DoesNotExist, Order_Proposals.DoesNotExist):550 return HttpResponseNotFound('Not Found', content_type='text/plain')551# noinspection PyUnusedLocal, PyShadowingBuiltins552def view_internal(request, pk):553 template_url = 'order-proposals/view-internal.html'554 operator = Operators.login_required(request)555 if operator is None:556 Operators.set_redirect_field_name(request, request.path)557 return redirect(reverse("operators_signin"))558 else:559 auth_permissions = Operators.get_auth_permissions(operator)560 if settings.ACCESS_PERMISSION_ORDER_VIEW in auth_permissions.values():561 try:562 model = Order_Proposals.objects.get(order_proposal_id=pk)563 order = Orders.objects.get(order_id=model.orders_order_id)564 attachments = Attachments.objects.filter(565 attachment_model=Attachments.MODEL_ORDERS,566 attachment_model_id=order.order_id,567 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_BUSINESS_LICENSE,568 ).order_by('-attachment_id').all()569 attachment1 = ''570 if attachments.count() != 0:571 attachment1 = attachments[0]572 attachments = Attachments.objects.filter(573 attachment_model=Attachments.MODEL_ORDERS,574 attachment_model_id=order.order_id,575 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_OFFER_LETTER,576 ).order_by('-attachment_id').all()577 attachment2 = ''578 if attachments.count() != 0:579 attachment2 = attachments[0]580 attachments = Attachments.objects.filter(581 attachment_model=Attachments.MODEL_ORDERS,582 attachment_model_id=order.order_id,583 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_QUOTATION,584 ).order_by('-attachment_id').all()585 attachment3 = ''586 if attachments.count() != 0:587 attachment3 = attachments[0]588 attachments = Attachments.objects.filter(589 attachment_model=Attachments.MODEL_ORDERS,590 attachment_model_id=order.order_id,591 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_VAT_REGISTRATION,592 ).order_by('-attachment_id').all()593 attachment4 = ''594 if attachments.count() != 0:595 attachment4 = attachments[0]596 attachments = Attachments.objects.filter(597 attachment_model=Attachments.MODEL_ORDERS,598 attachment_model_id=order.order_id,599 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_OTHER_DOCUMENT,600 attachment_number=1,601 ).order_by('-attachment_id').all()602 attachment5 = ''603 if attachments.count() != 0:604 attachment5 = attachments[0]605 attachments = Attachments.objects.filter(606 attachment_model=Attachments.MODEL_ORDERS,607 attachment_model_id=order.order_id,608 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_OTHER_DOCUMENT,609 attachment_number=2,610 ).order_by('-attachment_id').all()611 attachment6 = ''612 if attachments.count() != 0:613 attachment6 = attachments[0]614 attachments = Attachments.objects.filter(615 attachment_model=Attachments.MODEL_ORDERS,616 attachment_model_id=order.order_id,617 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_REFERENCE_DOCUMENT,618 attachment_number=1,619 ).order_by('-attachment_id').all()620 attachment7 = ''621 if attachments.count() != 0:622 attachment7 = attachments[0]623 attachments = Attachments.objects.filter(624 attachment_model=Attachments.MODEL_ORDERS,625 attachment_model_id=order.order_id,626 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_REFERENCE_DOCUMENT,627 attachment_number=2,628 ).order_by('-attachment_id').all()629 attachment8 = ''630 if attachments.count() != 0:631 attachment8 = attachments[0]632 attachments = Attachments.objects.filter(633 attachment_model=Attachments.MODEL_ORDERS,634 attachment_model_id=order.order_id,635 attachment_type=Attachments.TYPE_ORDER_PROPOSAL_REFERENCE_DOCUMENT,636 attachment_number=3,637 ).order_by('-attachment_id').all()638 attachment9 = ''639 if attachments.count() != 0:640 attachment9 = attachments[0]641 form = OrderProposalViewForm(642 initial={643 'company_type': model.order_proposal_supplier_company_type,644 'title': model.order_proposal_supplier_title,645 'details': model.order_proposal_supplier_details,646 'rf_number': model.order_proposal_supplier_rf_number,647 'proposal_title': model.order_proposal_supplier_proposal_title,648 'legal_representatives': model.order_proposal_supplier_legal_representatives,649 'address_plot_no': model.order_proposal_supplier_address_plot_no,650 'address_street': model.order_proposal_supplier_address_street,651 'address_av_no': model.order_proposal_supplier_address_av_no,652 'address_sector': model.order_proposal_supplier_address_sector,653 'address_district': model.order_proposal_supplier_address_district,654 'address_country': model.order_proposal_supplier_address_country,655 'contact_phone_number': model.order_proposal_supplier_contact_phone_number,656 'contact_email_id': model.order_proposal_supplier_contact_email_id,657 'tin_number': model.order_proposal_supplier_tin_number,658 'bank_account_details': model.order_proposal_supplier_bank_account_details,659 'previous_reference1_name': model.order_proposal_supplier_previous_reference1_name,660 'previous_reference1_contact_person': model.order_proposal_supplier_previous_reference1_contact_person,661 'previous_reference1_contact_number': model.order_proposal_supplier_previous_reference1_contact_number,662 'previous_reference1_contact_email_id': model.order_proposal_supplier_previous_reference1_contact_email_id,663 'previous_reference2_name': model.order_proposal_supplier_previous_reference2_name,664 'previous_reference2_contact_person': model.order_proposal_supplier_previous_reference2_contact_person,665 'previous_reference2_contact_number': model.order_proposal_supplier_previous_reference2_contact_number,666 'previous_reference2_contact_email_id': model.order_proposal_supplier_previous_reference2_contact_email_id,667 'previous_reference3_name': model.order_proposal_supplier_previous_reference3_name,668 'previous_reference3_contact_person': model.order_proposal_supplier_previous_reference3_contact_person,669 'previous_reference3_contact_number': model.order_proposal_supplier_previous_reference3_contact_number,670 'previous_reference3_contact_email_id': model.order_proposal_supplier_previous_reference3_contact_email_id,671 }672 )673 return render(674 request, template_url,675 {676 'section': settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,677 'title': Orders.TITLE,678 'name': Orders.NAME,679 'operator': operator,680 'auth_permissions': auth_permissions,681 'form': form,682 'model': model,683 'order': order,684 'index_url': reverse("order_proposals_index", kwargs={'pk': order.order_id}),685 'select_single_url': reverse("order_proposals_select_single"),686 'attachment1': attachment1,687 'attachment2': attachment2,688 'attachment3': attachment3,689 'attachment4': attachment4,690 'attachment5': attachment5,691 'attachment6': attachment6,692 'attachment7': attachment7,693 'attachment8': attachment8,694 'attachment9': attachment9,695 }696 )697 except(TypeError, ValueError, OverflowError, Orders.DoesNotExist, Order_Proposals.DoesNotExist):698 return HttpResponseNotFound('Not Found', content_type='text/plain')699 else:700 return HttpResponseForbidden('Forbidden', content_type='text/plain')701@csrf_exempt702# noinspection PyUnusedLocal, PyShadowingBuiltins703def upload_attachments_external(request):704 action = request.POST['action']705 id = request.POST['id']706 if action != '' and id is not None:707 if action == 'upload-order-proposal-business-license' or \708 action == 'upload-order-proposal-offer-letter' or \709 action == 'upload-order-proposal-quotation' or \710 action == 'upload-order-proposal-vat-registration' or \711 action == 'upload-order-proposal-other-document' or \712 action == 'upload-order-proposal-reference-document':713 order = Orders.objects.get(order_id=id)714 if order is not None:715 model = Attachments()716 model.UPLOAD_PATH = model.ORDERS_UPLOAD_PATH717 model.attachment_model = Attachments.MODEL_ORDERS718 model.attachment_model_id = order.order_id719 model.attachment_type_id = 0720 model.attachment_number = 0721 new_filename_prefix = 'order_email_'722 if action == 'upload-order-proposal-business-license':723 model.attachment_type = Attachments.TYPE_ORDER_PROPOSAL_BUSINESS_LICENSE724 new_filename_prefix = 'order_proposal_business_license_'725 if action == 'upload-order-proposal-offer-letter':726 model.attachment_type = Attachments.TYPE_ORDER_PROPOSAL_OFFER_LETTER727 new_filename_prefix = 'order_proposal_offer_letter_'728 if action == 'upload-order-proposal-quotation':729 model.attachment_type = Attachments.TYPE_ORDER_PROPOSAL_QUOTATION730 new_filename_prefix = 'order_proposal_quotation_'731 if action == 'upload-order-proposal-vat-registration':732 model.attachment_type = Attachments.TYPE_ORDER_PROPOSAL_VAT_REGISTRATION733 new_filename_prefix = 'order_proposal_vat_registration_'734 if action == 'upload-order-proposal-other-document':735 model.attachment_type = Attachments.TYPE_ORDER_PROPOSAL_OTHER_DOCUMENT736 new_filename_prefix = 'order_proposal_other_document_'737 if action == 'upload-order-proposal-reference-document':738 model.attachment_type = Attachments.TYPE_ORDER_PROPOSAL_REFERENCE_DOCUMENT739 new_filename_prefix = 'order_proposal_reference_document_'740 if action == 'upload-order-proposal-business-license' or \741 action == 'upload-order-proposal-offer-letter' or \742 action == 'upload-order-proposal-quotation' or \743 action == 'upload-order-proposal-vat-registration' or \744 action == 'upload-order-proposal-other-document' or \745 action == 'upload-order-proposal-reference-document':746 code = request.POST['code']747 model.attachment_type_id = code748 if action == 'upload-order-proposal-other-document' or \749 action == 'upload-order-proposal-reference-document':750 number = request.POST['number']751 model.attachment_number = number752 model.attachment_file_uploaded_at = Utils.get_current_datetime_utc()753 model.attachment_file_uploaded_id = ''754 model.attachment_file_uploaded_by = ''755 model.attachment_file_uploaded_department = ''756 model.attachment_file_uploaded_role = ''757 import magic758 mime = magic.Magic(mime=True)759 # for file in request.FILES.getlist('attachment_file_path'):760 form = OrderUploadAttachmentForm(request.POST, request.FILES)761 if form.is_valid():762 try:763 original_filename = form.cleaned_data['attachment_file_path']764 ext = original_filename.split('.')[-1]765 new_filename = new_filename_prefix + str(order.order_code) + '_' + str(766 Utils.get_epochtime_ms()) + '.' + str(ext)767 temp_file_path = settings.MEDIA_ROOT + 'temp/' + str(original_filename)768 attachment_file_path = settings.MEDIA_ROOT + model.UPLOAD_PATH + str(769 new_filename)770 os.rename(temp_file_path, attachment_file_path)771 url = model.UPLOAD_PATH + new_filename772 size = str(os.path.getsize(attachment_file_path))773 model.attachment_file_name = original_filename774 model.attachment_file_path = url775 model.attachment_file_type = str(mime.from_file(attachment_file_path))776 model.attachment_file_size = size777 model.save()778 # return HttpResponse('success', content_type='text/plain')779 response = json.dumps({780 'error': False,781 'message': 'success',782 'name': original_filename,783 'url': model.attachment_file_path.url,784 'size': defaultfilters.filesizeformat(size),785 'id': model.attachment_id,786 })787 return HttpResponse(str(response), content_type='text/plain')788 except Exception as e:789 print('Exception: ' + str(e))790 response = json.dumps({791 'error': True,792 'message': str(e),793 })794 return HttpResponse(str(response), content_type='text/plain')795 else:796 print(form.errors)797 response = json.dumps({798 'error': True,799 'message': str(form.errors),800 })801 return HttpResponse(str(response), content_type='text/plain')802 else:803 return HttpResponseNotFound('Not Found', content_type='text/plain')804 response = json.dumps({805 'error': True,806 'message': 'Invalid action',807 })808 return HttpResponse(str(response), content_type='text/plain')809 else:810 return HttpResponseBadRequest('Bad Request', content_type='text/plain')811# noinspection PyUnusedLocal, PyShadowingBuiltins812def evaluate_proposal(request, pk):813 template_url = 'order-proposals/proposal-evaluate.html'814 operator = Operators.login_required(request)815 if operator is None:816 Operators.set_redirect_field_name(request, request.path)817 return redirect(reverse("operators_signin"))818 else:819 auth_permissions = Operators.get_auth_permissions(operator)820 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():821 try:822 model = Order_Proposals.objects.get(order_proposal_id=pk)823 if request.method == 'POST':824 form = OrderProposalEvaluateForm(request.POST)825 # noinspection PyArgumentList826 if form.is_valid():827 model.order_proposal_cost = form.cleaned_data['order_proposal_cost']828 model.order_proposal_cost_currency = form.cleaned_data['order_proposal_cost_currency']829 model.order_proposal_evaluated_score = form.cleaned_data['order_proposal_evaluated_score']830 model.order_proposal_evaluation_details = form.cleaned_data['order_proposal_evaluation_details']831 model.order_proposal_evaluated_at = Utils.get_current_datetime_utc()832 model.order_proposal_evaluated_id = operator.operator_id833 model.order_proposal_evaluated_by = operator.operator_name834 model.order_proposal_evaluated_department = operator.operator_department835 model.order_proposal_evaluated_role = operator.operator_role836 model.order_proposal_status = Order_Proposals.STATUS_EVALUATED837 model.save()838 messages.success(request, 'Updated successfully.')839 return redirect(reverse("order_proposals_view_internal", args=[model.order_proposal_id]))840 else:841 error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])842 messages.error(request, '' + error_string)843 return redirect(reverse("order_proposals_view_internal", args=[model.order_proposal_id]))844 else:845 form = OrderProposalEvaluateForm(846 initial={847 'order_proposal_code': model.order_proposal_code,848 'order_proposal_supplier_title': model.order_proposal_supplier_title,849 'order_proposal_cost': model.order_proposal_cost,850 'order_proposal_cost_currency': model.order_proposal_cost_currency,851 'order_proposal_evaluated_score': model.order_proposal_evaluated_score,852 'order_proposal_evaluation_details': model.order_proposal_evaluation_details,853 }854 )855 return render(856 request, template_url,857 {858 'section': settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,859 'title': Order_Proposals.TITLE,860 'name': Order_Proposals.NAME,861 'operator': operator,862 'auth_permissions': auth_permissions,863 'form': form,864 'model': model,865 }866 )867 except(TypeError, ValueError, OverflowError, Order_Proposals.DoesNotExist):868 return HttpResponseNotFound('Not Found', content_type='text/plain')869 else:870 return HttpResponseForbidden('Forbidden', content_type='text/plain')871# noinspection PyUnusedLocal872def api_dropdown_approved_proposals(request, code):873 operator = Operators.login_required(request)874 if operator is None:875 Operators.set_redirect_field_name(request, request.path)876 return redirect(reverse("operators_signin"))877 else:878 auth_permissions = Operators.get_auth_permissions(operator)879 proposals = ""880 proposals += "<option value=''>--select--</option>"881 order = Orders.objects.get(order_code=code)882 objects = Order_Proposals.objects.filter(883 Q(orders_order_id=order.order_id) &884 (Q(order_proposal_status=Order_Proposals.STATUS_APPROVED) |885 Q(order_proposal_status=Order_Proposals.STATUS_SELECTED))886 )887 for item in objects:888 proposals += "<option value='" + str(889 item.order_proposal_id) + "'>" + str(item.order_proposal_code) + " (" + str(890 item.order_proposal_supplier_title) + ")</option>"891 return HttpResponse(proposals, content_type="text/plain")892# noinspection PyUnusedLocal, PyShadowingBuiltins893def select_proposal(request, pk):894 template_url = 'order-proposals/proposal-select.html'895 operator = Operators.login_required(request)896 if operator is None:897 Operators.set_redirect_field_name(request, request.path)898 return redirect(reverse("operators_signin"))899 else:900 auth_permissions = Operators.get_auth_permissions(operator)901 if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():902 try:903 order = Orders.objects.get(order_id=pk)904 if request.method == 'POST':905 form = OrderProposalSelectForm(request.POST)906 # noinspection PyArgumentList907 if form.is_valid():908 order_proposals = Order_Proposals.objects.filter(orders_order_id=pk,909 order_proposal_status=Order_Proposals.STATUS_SELECTED)910 for order_proposal in order_proposals:911 order_proposal.order_proposal_selected_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE912 order_proposal.order_proposal_selected_id = ''913 order_proposal.order_proposal_selected_by = ''914 order_proposal.order_proposal_selected_department = ''915 order_proposal.order_proposal_selected_role = ''916 order_proposal.order_proposal_status = Order_Proposals.STATUS_APPROVED917 order_proposal.save()918 order_proposal_id = form.cleaned_data['order_proposal_id']919 model = Order_Proposals.objects.get(order_proposal_id=order_proposal_id)920 model.order_proposal_selected_at = Utils.get_current_datetime_utc()921 model.order_proposal_selected_id = operator.operator_id922 model.order_proposal_selected_by = operator.operator_name923 model.order_proposal_selected_department = operator.operator_department924 model.order_proposal_selected_role = operator.operator_role925 model.order_proposal_status = Order_Proposals.STATUS_SELECTED926 model.save()927 order.order_proposal_id = model.order_proposal_id928 order.order_proposal_selected_at = Utils.get_current_datetime_utc()929 order.order_proposal_selected_id = operator.operator_id930 order.order_proposal_selected_by = operator.operator_name931 order.order_proposal_selected_department = operator.operator_department932 order.order_proposal_selected_role = operator.operator_role933 order.order_status = Orders.STATUS_PROPOSAL_SELECTED934 order.save()935 # sending email confirmation mail936 if settings.IS_LOCAL:937 domain = settings.BACKEND_DOMAIN_LOCAL938 logo_url = settings.STATIC_LOCAL + "app/logo-transparent-white.png"939 else:940 domain = settings.BACKEND_DOMAIN_PROD941 logo_url = settings.STATIC_PROD + "app/logo-transparent-white.png"942 contact_url = settings.APP_CONSTANT_COMPANY_WEBSITE943 link_url = '{domain}/{path}'.format(944 domain=domain,945 path="order-proposals/create/" + str(model.orders_order_id) + "/" + str(946 model.order_proposal_code) + "/"947 )948 link_name = "View Details"949 acknowledge_url = '/order-proposals/update/acknowledge/' + str(pk) + '/'950 acknowledge_url = "<a title=\"link\" href=\"" + str(951 domain) + acknowledge_url + "\" target=\"_blank\" rel=\"noopener\">link</a>"952 message = "Congratulations your proposal has been approved. Please acknowledge by clicking on this " + acknowledge_url + "."953 html_content = render_to_string(954 'email/email-info-with-link.html',955 {956 'logo_url': logo_url,957 'contact_url': contact_url,958 'link_url': link_url,959 'link_name': link_name,960 'name': model.order_proposal_supplier_title,961 'message': defaultfilters.safe(message),962 }963 )964 send_mail(965 settings.EMAIL_NOTIFICATION_SUBJECT,966 settings.EMAIL_NOTIFICATION_MESSAGE,967 settings.APP_CONSTANT_ADMIN_SUPPORT_EMAIL_ID,968 [model.order_proposal_supplier_contact_email_id],969 fail_silently=False,970 html_message=html_content,971 )972 order_proposals = Order_Proposals.objects.filter(orders_order_id=pk).exclude(973 order_proposal_status=Order_Proposals.STATUS_SELECTED)974 for model in order_proposals:975 # sending email confirmation mail976 if settings.IS_LOCAL:977 domain = settings.BACKEND_DOMAIN_LOCAL978 logo_url = settings.STATIC_LOCAL + "app/logo-transparent-white.png"979 else:980 domain = settings.BACKEND_DOMAIN_PROD981 logo_url = settings.STATIC_PROD + "app/logo-transparent-white.png"982 contact_url = settings.APP_CONSTANT_COMPANY_WEBSITE983 link_url = '{domain}/{path}'.format(984 domain=domain,985 path="order-proposals/create/" + str(model.orders_order_id) + "/" + str(986 model.order_proposal_code) + "/"987 )988 link_name = "View Details"989 message = "Sorry, your proposal has been rejected."990 html_content = render_to_string(991 'email/email-info-with-link.html',992 {993 'logo_url': logo_url,994 'contact_url': contact_url,995 'link_url': link_url,996 'link_name': link_name,997 'name': model.order_proposal_supplier_title,998 'message': defaultfilters.safe(message),999 }1000 )1001 send_mail(1002 settings.EMAIL_NOTIFICATION_SUBJECT,1003 settings.EMAIL_NOTIFICATION_MESSAGE,1004 settings.APP_CONSTANT_ADMIN_SUPPORT_EMAIL_ID,1005 [model.order_proposal_supplier_contact_email_id],1006 fail_silently=False,1007 html_message=html_content,1008 )1009 messages.success(request, 'Updated successfully.')1010 return redirect(reverse("order_proposals_index", args=[pk]))1011 else:1012 error_string = ' '.join([' '.join(x for x in l) for l in list(form.errors.values())])1013 messages.error(request, '' + error_string)1014 return redirect(reverse("order_proposals_index", args=[pk]))1015 else:1016 form = OrderProposalSelectForm(1017 initial={1018 'order_id': order.order_code,1019 'order_proposal_id': '',1020 }1021 )1022 return render(1023 request, template_url,1024 {1025 'section': settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,1026 'title': Order_Proposals.TITLE,1027 'name': Order_Proposals.NAME,1028 'operator': operator,1029 'auth_permissions': auth_permissions,1030 'form': form,1031 }1032 )1033 except(TypeError, ValueError, OverflowError, Orders.DoesNotExist, Order_Proposals.DoesNotExist):1034 return HttpResponseNotFound('Not Found', content_type='text/plain')1035 else:1036 return HttpResponseForbidden('Forbidden', content_type='text/plain')1037@csrf_exempt1038# noinspection PyUnusedLocal, PyShadowingBuiltins1039def acknowledge_proposal_external(request, pk):1040 try:1041 model = Order_Proposals.objects.get(order_proposal_id=pk)1042 order = Orders.objects.get(order_id=model.orders_order_id)1043 if model.order_proposal_status == Order_Proposals.STATUS_SELECTED:1044 model.order_proposal_acknowledged_at = Utils.get_current_datetime_utc()1045 model.order_proposal_acknowledged_id = ''1046 model.order_proposal_acknowledged_by = ''1047 model.order_proposal_acknowledged_department = ''1048 model.order_proposal_acknowledged_role = ''1049 model.order_proposal_status = Order_Proposals.STATUS_ACKNOWLEDGED1050 model.save()1051 # sending notification to Officer1052 if order.order_assigned_to_id != str(0):1053 operators = Operators.objects.all().filter(1054 Q(operator_id=order.order_assigned_to_id)1055 )1056 else:1057 operators = Operators.objects.all().filter(1058 Q(operator_department=Operators.DEPARTMENT_DAF) &1059 Q(operator_role=order.order_assigned_to_role)1060 )1061 for item in operators:1062 Notifications.add_notification(1063 Notifications.TYPE_SUPPLIER,1064 model.order_proposal_id,1065 Notifications.TYPE_OPERATOR,1066 item.operator_id,1067 Notifications.TYPE_ORDER_PROPOSAL,1068 model.order_proposal_id,1069 "Acknowledged proposal to generate purchase order.",1070 "/backend/order-proposals/view/internal/" + str(model.order_proposal_id) + "/"1071 )1072 messages.success(request, 'Acknowledged successfully.')1073 return redirect(reverse("order_proposals_create", args=[pk, model.order_proposal_code]))1074 except(TypeError, ValueError, OverflowError, Orders.DoesNotExist, Order_Proposals.DoesNotExist):...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

1from django.shortcuts import render, get_object_or_404, reverse, redirect2from django.core.exceptions import ObjectDoesNotExist3from django.db.models.functions import Extract4from django.contrib.auth.mixins import LoginRequiredMixin5from django.views import View6from django.utils import timezone7from .models import Item, OrderItem, Order, Sale8from cars.models import Car9from django.db.models import Q10# Create your views here.11class HomePageView(LoginRequiredMixin, View):12 def get(self, request, *args, **kwargs):13 spares = Item.objects.all()14 paginate_by = 115 cars = Car.objects.all()16 template_name = 'spares/index.html'17 context = {18 'spares': spares,19 'cars': cars20 }21 return render(request, template_name, context)22 # def get(self, request, *args, **kwargs):23 # spares = None24 # cars = Car.objects.all()25 # carId = request.GET.get('car_id')26 # if carId:27 # print("Your in Bmw cars")28 # spares = Item.objects.filter(carId)29 # else:30 # print("you in all products")31 # spares = Item.objects.all()32 # template_name = 'spares/index.html'33 # context = {34 # 'spares': spares,35 # 'cars':cars36 # }37 # return render(request, template_name, context)38 def get_seccuss_url(self):39 return reverse("spares:product-order")40class CarView(View):41 def get(self, request, id, *args, **kwargs):42 car_item = Car.objects.all()43 cars = Car.objects.get(id=id)44 spares = Item.objects.filter(car=cars)45 template_name = 'spares/car_category.html'46 context = {47 'spares': spares,48 'cars': 'cars',49 'car_item': car_item50 }51 return render(request, template_name, context)52class OrderPageView(View):53 def get(self, request, pk, *args, **kwargs):54 products = Item.objects.get(pk=pk)55 orders = get_object_or_404(Order, user=request.user, ordered=False)56 order_items = OrderItem.objects.filter(order=orders)57 template_name = 'spares/order_page.html'58 context = {59 'products': products,60 'order_items': order_items,61 'orders': orders62 }63 return render(request, template_name, context)64 def get_seccuss_url(self):65 return reverse("spares:product-order")66class OrderSummaryView(LoginRequiredMixin, View):67 def get(self, request, *args, **kwargs):68 try:69 orders = get_object_or_404(Order, user=request.user, ordered=False)70 order_items = OrderItem.objects.filter(order=orders)71 template_name = 'spares/order_summary.html'72 context = {73 'order_items': order_items,74 'orders': orders75 }76 return render(request, template_name, context)77 except ObjectDoesNotExist:78 return redirect('/')79class OrderView(View):80 def get(self, request, pk, *args, **kwargs):81 item = get_object_or_404(Item, pk=pk)82 order_item, created = OrderItem.objects.get_or_create(83 item=item,84 user=request.user,85 ordered=False86 )87 order_qs = Order.objects.filter(user=request.user, ordered=False)88 if order_qs.exists():89 order = order_qs[0]90 if order.items.filter(item__pk=item.pk).exists():91 order_item.quantity += 192 order_item.save()93 else:94 order.items.add(order_item)95 else:96 ordered_date = timezone.now()97 order = Order.objects.create(98 user=request.user, ordered_date=ordered_date)99 order.items.add(order_item)100 order.save()101 return redirect("spares:products", pk=pk)102class SalesView(View):103 def get(self, request, *args, **kwargs):104 return render(request, "spares/sale_summary.html")105 def get(self, request, pk, *args, **kwargs):106 order = Order.objects.get(user=request.user, ordered=False)107 try:108 amount = order.get_total()109 # create sales110 sales = Sale()111 sales.user = self.request.user112 sales.amount = amount113 sales.save()114 # asseign sale to order115 order_items = order.items.all()116 order_items.update(ordered=True)117 for item in order_items:118 item.save()119 order.ordered = True120 order.sale = sales121 order.save()122 return redirect('spares:sale-summary')123 except ObjectDoesNotExist:124 print("item saled successefully")125 return redirect('spares:sale-summary')126class SalesSummaryView(View):127 def get(self, request, *args, **kwargs):128 template_name = 'spares/sale_summary.html'129 sales = Sale.objects.all()130 orders = Order.objects.exclude(user=request.user, ordered=False)131 paginate_by = 1132 context = {133 'orders': orders,134 'sales': sales,135 }136 return render(request, template_name, context)137def add_to_cart(request, pk):138 item = get_object_or_404(Item, pk=pk)139 order_item, created = OrderItem.objects.get_or_create(140 item=item,141 user=request.user,142 ordered=False143 )144 order_qs = Order.objects.filter(user=request.user, ordered=False)145 if order_qs.exists():146 order = order_qs[0]147 if order.items.filter(item__pk=item.pk).exists():148 order_item.quantity += 1149 order_item.save()150 else:151 order.items.add(order_item)152 else:153 ordered_date = timezone.now()154 order = Order.objects.create(155 user=request.user, ordered_date=ordered_date)156 order.items.add(order_item)157 return redirect("spares:products", pk=pk)158def remove_from_cart(request, pk):159 item = get_object_or_404(Item, pk=pk)160 order_qs = Order.objects.filter(user=request.user, ordered=False)161 if order_qs.exists():162 order = order_qs[0]163 if order.items.filter(item__pk=item.pk).exists():164 order_item = OrderItem.objects.filter(165 item=item,166 ordered=False,167 user=request.user168 )[0]169 order.items.remove(order_item)170 else:171 return redirect("spares:products")172 else:173 return redirect("spares:products")174 return redirect("/")175def remove_single_item_from_cart(request, pk):176 item = get_object_or_404(Item, pk=pk)177 order_qs = Order.objects.filter(user=request.user, ordered=False)178 if order_qs.exists():179 order = order_qs[0]180 if order.items.filter(item__pk=item.pk).exists():181 order_item = OrderItem.objects.filter(182 item=item,183 ordered=False,184 user=request.user185 )[0]186 if order_item.quantity > 1:187 order_item.quantity -= 1188 order_item.save()189 else:190 order.items.remove(order_item)191 return redirect('/')192 else:193 return redirect("spares:products")...

Full Screen

Full Screen

pos_order.py

Source:pos_order.py Github

copy

Full Screen

...84 del payment_line['id']85 extended_payment_lines.append([0, 0, payment_line])86 for order_id, payment_lines in groupby(extended_payment_lines, key=lambda x:x[2]['pos_order_id']):87 next(order for order in orders if order['id'] == order_id[0])['statement_ids'] = list(payment_lines)88 def _get_fields_for_draft_order(self):89 return [90 'id',91 'pricelist_id',92 'partner_id',93 'sequence_number',94 'session_id',95 'pos_reference',96 'create_uid',97 'create_date',98 'customer_count',99 'fiscal_position_id',100 'table_id',101 'to_invoice',102 ]103 @api.model104 def get_table_draft_orders(self, table_id):105 """Generate an object of all draft orders for the given table.106 Generate and return an JSON object with all draft orders for the given table, to send to the 107 front end application.108 :param table_id: Id of the selected table.109 :type table_id: int.110 :returns: list -- list of dict representing the table orders111 """112 table_orders = self.search_read(113 domain = [('state', '=', 'draft'), ('table_id', '=', table_id)],114 fields = self._get_fields_for_draft_order())115 self._get_order_lines(table_orders)116 self._get_payment_lines(table_orders)117 for order in table_orders:118 order['pos_session_id'] = order['session_id'][0]119 order['uid'] = search(r"\d{5,}-\d{3,}-\d{4,}", order['pos_reference']).group(0)120 order['name'] = order['pos_reference']121 order['creation_date'] = order['create_date']122 order['server_id'] = order['id']123 if order['fiscal_position_id']:124 order['fiscal_position_id'] = order['fiscal_position_id'][0]125 if order['pricelist_id']:126 order['pricelist_id'] = order['pricelist_id'][0]127 if order['partner_id']:128 order['partner_id'] = order['partner_id'][0]...

Full Screen

Full Screen

future_order.py

Source:future_order.py Github

copy

Full Screen

1# -*- coding: UTF-8 -*-2#載入相關套件3import subprocess,time,haohaninfo4#下單子程式放置位置5ExecPath="C:/OrderCmd/GOrder/"6#送出交易委託7def Order(BrokerID,Product,BS,Price,Qty,OrderMethod,OrderType):8 OrderNo=subprocess.check_output([ExecPath+"Order.exe",BrokerID,Product,BS,Price,Qty,OrderMethod,OrderType,'0']).decode('cp950').strip('\r\n')9 return OrderNo10#取得下單帳務11def MatchAccount(BrokerID,OrderNo):12 OrderInfo=subprocess.check_output([ExecPath+"MatchAccount.exe",BrokerID,OrderNo]).decode('cp950').split('\r\n')13 if OrderInfo[0]=='over':14 return False15 else:16 OrderInfo = [ i.split(',') for i in OrderInfo ]17 return OrderInfo18#下單並取得帳務回傳19def OrderAndMatchAccount(BrokerID,Product,BS,Price,Qty,OrderMethod,OrderType):20 OrderNo=Order(BrokerID,Product,BS,Price,Qty,OrderMethod,OrderType)21 if OrderNo != '委託失敗':22 while 1:23 OrderInfo=MatchAccount(BrokerID,OrderNo)24 if OrderInfo != False:25 return OrderInfo26 else:27 print('尚未成交')28 time.sleep(2)29 else:30 print('下單失敗')31 return False32#下單並取得帳務回傳(package)33def OrderAndMatchAccountByhaohaninfo(BrokerID,Product,BS,Price,Qty,OrderMethod,OrderType):34 Go = haohaninfo.GOrder.GOCommand()35 OrderNo=Go.Order(BrokerID,Product,BS,Price,Qty,OrderMethod,OrderType)36 if OrderNo != '委託失敗':37 while 1:38 OrderInfo=Go.MatchAccount(BrokerID,OrderNo)39 if len(OrderInfo) != 0:40 return OrderInfo41 else:42 print('尚未成交')43 time.sleep(2)44 else:45 print('下單失敗')46 return False47#取消委託48def CancelOrder(BrokerID,OrderNo):49 CancelInfo=subprocess.check_output([ExecPath+"Order.exe",BrokerID,'Delete',OrderNo]).decode('cp950').split('\n')50 if CancelInfo[0] == '1':51 return True52 else:53 return False54#取得總帳務 55def GetAllAccount(BrokerID):56 AccInfo=subprocess.check_output([ExecPath+"GetAccount.exe",BrokerID,'All']).decode('cp950').split('\r\n')57 return AccInfo58 59#取得未平倉資訊60def GetStock(BrokerID):61 StockInfo=subprocess.check_output([ExecPath+"GetInStock.exe",BrokerID]).decode('cp950').split('\r\n')62 return StockInfo63#委託到期刪單64def LMT2DEL(BrokerID,Product,BS,Price,Qty,Sec):65 OrderNo=Order(BrokerID,Product,BS,Price,Qty,'ROD','LMT')66 StartTime=time.time()67 if OrderNo != '委託失敗':68 while time.time()-StartTime<Sec:69 time.sleep(2)70 OrderInfo=MatchAccount(BrokerID,OrderNo)71 if OrderInfo != False:72 return OrderInfo 73 else:74 print('尚未成交')75 CancelOrder(BrokerID,OrderNo) 76 return False77 else:78 print('下單失敗')79 return False 80#委託到期刪單(package)81def LMT2DELByhaohaninfo(BrokerID,Product,BS,Price,Qty,Sec):82 Go = haohaninfo.GOrder.GOCommand()83 OrderNo=Go.Order(BrokerID,Product,BS,Price,Qty,'ROD','LMT')84 StartTime=time.time()85 if OrderNo != '委託失敗':86 while time.time()-StartTime<Sec:87 time.sleep(2)88 OrderInfo=Go.MatchAccount(BrokerID,OrderNo)89 if len(OrderInfo) != 0:90 return OrderInfo91 else:92 print('尚未成交')93 Go.Delete(BrokerID,OrderNo)94 return False95 else:96 print('下單失敗')97 return False98#委託到期轉市價單99def LMT2MKT(BrokerID,Product,BS,Price,Qty,Sec):100 OrderNo=Order(BrokerID,Product,BS,Price,Qty,'ROD','LMT')101 StartTime=time.time()102 if OrderNo != '委託失敗':103 while time.time()-StartTime<Sec:104 time.sleep(2)105 OrderInfo=MatchAccount(BrokerID,OrderNo)106 if OrderInfo != False:107 return OrderInfo 108 else:109 print('尚未成交')110 CancelOrder(BrokerID,OrderNo) 111 OrderInfo = OrderAndMatchAccount(BrokerID,Product,BS,Price,Qty,'IOC','MKT')112 return OrderInfo113 else:114 print('下單失敗')115 return False 116 117#委託到期轉市價單(package)118def LMT2MKTByhaohaninfo(BrokerID,Product,BS,Price,Qty,Sec):119 Go = haohaninfo.GOrder.GOCommand()120 OrderNo=Go.Order(BrokerID,Product,BS,Price,Qty,'ROD','LMT')121 StartTime=time.time()122 if OrderNo != '委託失敗':123 while time.time()-StartTime<Sec:124 time.sleep(2)125 OrderInfo=Go.MatchAccount(BrokerID,OrderNo)126 if len(OrderInfo) != 0:127 return OrderInfo128 else:129 print('尚未成交')130 Go.Delete(BrokerID,OrderNo)131 OrderInfo = OrderAndMatchAccountByhaohaninfo(BrokerID,Product,BS,Price,Qty,'IOC','MKT') 132 return OrderInfo133 else:134 print('下單失敗')135 return False...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful