def user_logged_out(sender, user, **kwargs): try: scout = user.scout scout.active = False scout.save() except Exception as E: sentry_debug_logger.debug('no scout found' + str(E), exc_info=True)
def func(*args, **kwargs): sentry_debug_logger.debug(str(attr) + " called with args=" + str(args) + " and kwargs=" + str(kwargs), exc_info=True) x = requests.post(config('HOMES_REDISAPI_EVENT_URL'), headers={'Content-type': 'application/json'}, data=json.dumps({ 'attr': attr, 'args': args, 'kwargs': kwargs }), auth=(config('HOMES_ADMIN_USERNAME'), config('HOMES_ADMIN_PASSWORD'))) response = x.json() if response[STATUS] == SUCCESS: result = response['result'] result_type = response['result_type'] if result_type == 'bytes': result = result.encode() response['result'] = result return response['result'] elif response[STATUS] == ERROR: message = response['message'] exception = response['exception'] print("error occurs with message" + str(message)) unpickled_exception = pickle.loads( codecs.decode(exception.encode(), "base64")) raise unpickled_exception
def update_tenant_lead_activity_status_in_affiliate_tool(tenant_lead_activity): request_data = { TASK_TYPE: UPDATE_TENANT_LEAD_ACTIVITY_STATUS, DATA: TenantLeadActivitySerializer(tenant_lead_activity).data, METADATA: { 'referral_status': get_appropriate_status_of_lead_activity_for_affiliate_tool( lead_activity=tenant_lead_activity) } } sentry_debug_logger.debug('data is ' + str(request_data)) print(request_data, 'updating tenant lead activity status') tenant_referral_id = None if tenant_lead_activity.lead.referral_id: tenant_referral_id = tenant_lead_activity.lead.referral_id if tenant_referral_id: req = requests.patch(TENANT_LEAD_REFERRAL_UPDATE_URL.format( **{'pk': tenant_referral_id}), data=json.dumps(request_data), headers={'Content-type': 'application/json'}, timeout=10, auth=(config('AFFILIATE_TOOL_ADMIN_USERNAME'), config('AFFILIATE_TOOL_ADMIN_PASSWORD'))) print(req.status_code) print(str(req.content)) if req.status_code == 200: if req.json()[STATUS] == SUCCESS: tenant_lead_activity.acknowledged_by_affiliate = True tenant_lead_activity.save()
def load_oauth_token_and_access_token_from_pickle(oauth_client): user_email = config('ZOHO_CURRENT_USER_EMAIL') try: x = open("zcrm_oauthtokens.pkl", "rb") oauth_tokens = pickle.load(x) refresh_token = oauth_tokens.refreshToken try: access_token = oauth_tokens.get_access_token() return oauth_tokens, access_token except ZohoOAuthException as err: if err.message == 'Access token got expired!': print("refreshing token") oauth_client.refresh_access_token(refresh_token, user_email) # access_token = oauth_tokens.get_access_token() access_token = oauth_client.get_access_token(user_email) return oauth_tokens, access_token else: print("error due to", err) except FileNotFoundError: from ZohoCrm.models import ZohoConstant try: grant_token = ZohoConstant.objects.get(name='GRANT_TOKEN').value oauth_tokens = oauth_client.generate_access_token(grant_token) access_token = oauth_client.get_access_token(user_email) return oauth_tokens, access_token except Exception as E: sentry_debug_logger.debug(E, exc_info=True)
def display_title(self): try: return str(self.bhk_count) + " BHK " + str( self.description) + ' in ' + str(self.address.city) except Exception as E: sentry_debug_logger.debug(str(E), exc_info=True) return str(self.bhk_count) + " BHK " + str(self.description)
def area_manager_house_visit_notify(house_visit_id): from Homes.Houses.models import HouseVisit sentry_debug_logger.debug('house visit id is ' + str(house_visit_id), exc_info=True) house_visit = HouseVisit.objects.get(id=house_visit_id) area_manager = house_visit.area_manager if area_manager: send_house_visit_sms_and_send_scout_task(house_visit, area_manager)
def booking_post_save_hook(sender, instance, created, **kwargs): if created: tenant = instance.tenant if instance.type == NEW_TENANT_BOOKING: # create token payment category, _ = PaymentCategory.objects.get_or_create( name=BOOKING_PAYMENT) TenantPayment(user=tenant.customer.user, wallet=tenant.wallet, booking=instance, original_amount=TOKEN_AMOUNT, description=BOOKING_PAYMENT_DESCRIPTION, status=PENDING, type=DEPOSIT, category=category, due_date=timezone.now() + timedelta(days=1)).save() # create 1st monthly rent (including move-in charges) MonthlyRent(booking=instance, start_date=instance.license_start_date).save() # send affiliate referral status to lead tool in case affiliate is involved try: update_affiliate_conversion_details_to_lead_tool.delay( booking_id=instance.id) except Exception as E: from utility.logging_utils import sentry_debug_logger sentry_debug_logger.debug( "error occured in updating affiliate conversion details", exc_info=True) elif instance.type == EXISTING_TENANT_BOOKING: # create token payment if int(instance.token_amount) != 0: category, _ = PaymentCategory.objects.get_or_create( name=BOOKING_PAYMENT) TenantPayment(user=tenant.customer.user, wallet=tenant.wallet, booking=instance, original_amount=instance.token_amount, description=BOOKING_PAYMENT_DESCRIPTION, status=PENDING, type=DEPOSIT, category=category, due_date=instance.license_start_date).save() # create 1st monthly rent (including move-in charges) if int(instance.movein_charges) != 0: MonthlyRent(booking=instance, start_date=instance.license_start_date).save() # set space as booked change_booked_space_status(instance)
def notify_scout_visit_cancelled(house_visit_id): try: from Homes.Houses.models import HouseVisit from Homes.Houses.utils import HOUSE_VISIT_CANCELLED house_visit = HouseVisit.objects.filter(id=house_visit_id).first() sentry_debug_logger.debug("house visit is " + str(house_visit)) if house_visit: data = {'house_id': house_visit.house.id, 'visit_id': house_visit.id} task_type = HOUSE_VISIT_CANCELLED send_scout_task_to_scout_backend(data=data, task_type=task_type) except Exception as E: sentry_debug_logger.debug('error occurred while sending scout_task_for_house_visit ' + str(E), exc_info=True)
def patch(self, request, *args, **kwargs): sentry_debug_logger.debug("tenant referral patch called with" + str(request.data)) if self.request.data[TASK_TYPE] == UPDATE_TENANT_LEAD_ACTIVITY_STATUS: try: instance = self.get_object() instance.status = self.request.data[METADATA]['referral_status'] instance.save() response_json = {STATUS: SUCCESS} return JsonResponse(response_json, status=200) except Exception as E: response_json = {STATUS: ERROR, 'message': str(E)} return JsonResponse(response_json, status=400)
def update_affiliate_conversion_details_to_lead_tool(booking_id=None): from utility.logging_utils import sentry_debug_logger try: if booking_id: from Homes.Bookings.models import Booking booking = Booking.objects.filter(id=booking_id).first() if booking: if booking.status == BOOKING_COMPLETE: tenant = booking.tenant if tenant: tenant_requirement = TenantRequirement.objects.filter( tenant=tenant).first() if tenant_requirement: if tenant_requirement.affiliate_code: print( "send booking details to affiliate tool via lead tool with code" + str(tenant_requirement.affiliate_code)) from Homes.Tenants.api.serializers import TenantRequirementSerializer request_data = { TASK_TYPE: UPDATE_LEAD_REFERRAL_STATUS, SUB_TASK: BOOKING, STATUS: BOOKING_COMPLETE, DATA: TenantRequirementSerializer( tenant_requirement).data } url = config( 'HALANX_LEAD_API_ENDPOINT' ) + config( 'HALANX_LEAD_UPDATE_TENANT_REFERRAL_API') resp = requests.post(url, data=request_data) sentry_debug_logger.debug( 'updating conversion url is ' + str(url) + 'data is' + str(request_data) + 'response is ' + str(resp.content)) except Exception as E: sentry_debug_logger.debug( 'error occured while updating affiliate converion due to ' + str(E), exc_info=True)
def get_appropriate_status_of_lead_activity_for_affiliate_tool(lead_activity): try: if lead_activity.post_status.name in [ STATUS_DISQUALIFIED, ]: return CANCELLED elif lead_activity.post_status.name in [ STATUS_CONVERTED, STATUS_VISIT_SCHEDULED ]: return SUCCESS else: return PENDING except Exception as E: print(E) sentry_debug_logger.debug("error due to " + str(E)) return PENDING
def scout_task_assignment_request_pre_save_hook(sender, instance, update_fields={'responded_at'}, **kwargs): old_request = ScoutTaskAssignmentRequest.objects.filter( id=instance.id).first() if not old_request: return if (old_request.status == REQUEST_AWAITED and instance.status in [REQUEST_ACCEPTED, REQUEST_REJECTED]) or \ (old_request.status == REQUEST_ACCEPTED and instance.status == REQUEST_REJECTED): instance.responded_at = timezone.now() task = instance.task if instance.status == REQUEST_ACCEPTED: task.scout = instance.scout task.status = ASSIGNED task.assigned_at = instance.responded_at task.save() elif instance.status == REQUEST_REJECTED and instance.pass_to_another_scout: # find some other scout to send notification to # create another scout task assignment request # sentry_debug_logger.debug('scout rejected the request') # find another scout for the visit task excluding this scout scout = get_appropriate_scout_for_the_task( task=task, scouts=Scout.objects.filter(active=True).exclude( id=instance.scout.id)) if scout: ScoutTaskAssignmentRequest.objects.create(task=task, scout=scout) else: sentry_debug_logger.debug("no more scout exists")
def tenant_booking_and_visit_referrals_status_update_view(request): sentry_debug_logger.debug('request received', exc_info=True) task_type = request.data[TASK_TYPE] # Different tasks to be performed from Halanx App if task_type == UPDATE_LEAD_REFERRAL_STATUS: if request.data[SUB_TASK] == BOOKING: if request.data[STATUS] == BOOKING_COMPLETE: ref_id = request.data[DATA]['affiliate_code'] phone_no = request.data[DATA]['phone_no'] affiliate = Affiliate.objects.using(settings.AFFILIATE_DB).filter(unique_code=ref_id) if affiliate: # Search the corresponding lead to add new lead activity # Getting the Tenant Referral tenant_referral = TenantReferral.objects.using(settings.AFFILIATE_DB).filter( affiliate=affiliate, phone_no=phone_no).first() if tenant_referral: # Getting the tenant lead from tenant referral id tenant_lead = TenantLead.objects.filter(referral_id=tenant_referral.id).first() if tenant_lead: # Creating Tenant Lead Activity lead_activity_category, _ = LeadActivityCategory.objects.get_or_create(name=BOOKED_HOUSE) TenantLeadActivity.objects.create( lead=tenant_lead, category=lead_activity_category, post_status=STATUS_HOME_BOOKED, remarks="Booking Completed by tenant registered via affiliate") return JsonResponse({STATUS: SUCCESS}) else: return JsonResponse({STATUS: ERROR, MESSAGE: 'No suitable task type provided'})
def add_affiliate_referral_task(tenant_requirement_id): """ Task to add tenant referral to affiliate referrals :param tenant_requirement_id: """ logger.info( 'Started add affiliate referral task for tenant requirement id {}'. format(tenant_requirement_id)) from Homes.Tenants.models import TenantRequirement tenant_requirement = TenantRequirement.objects.get( id=tenant_requirement_id) if not tenant_requirement.affiliate_code: tenant_requirement.affiliate_code = config( "HALANX_AFFILIATE_DEFAULT_REFERRAL_CODE") tenant_requirement.save() if tenant_requirement.affiliate_code is not None: # change affiliate code to default halanx code from Homes.Tenants.api.serializers import TenantRequirementSerializer data = TenantRequirementSerializer(tenant_requirement).data data['source'] = config('HALANX_AFFILIATE_SOURCE') url = (config('HALANX_AFFILIATE_API_ENDPOINT') if settings.ENVIRONMENT == PRODUCTION else config('HALANX_AFFILIATE_TEST_API_ENDPOINT') ) + config('HALANX_AFFILIATE_TENANT_REFERRAL_API') resp = requests.post(url, data=data) logger.info(resp.text) print(resp.text) from utility.logging_utils import sentry_debug_logger sentry_debug_logger.debug('url is ' + str(url) + 'data is' + str(data) + 'response is ' + str(resp.content)) logger.info( 'Finished add affiliate referral task for tenant requirement id {}'. format(tenant_requirement_id))
def add_affiliate_referral_task_owner_listing(owner_listing_id): """ Task to add owner listing to affiliate referrals """ logger.info( 'Started add affiliate referral task for owner listing id {}'.format( owner_listing_id)) from Homes.Owners.models import OwnerListing owner_listing = OwnerListing.objects.get(id=owner_listing_id) if not owner_listing.affiliate_code: # change affiliate code to default halanx code owner_listing.affiliate_code = config( "HALANX_AFFILIATE_DEFAULT_REFERRAL_CODE") owner_listing.save() if owner_listing.affiliate_code is not None: from Homes.Owners.api.serializers import OwnerListingSerializer from utility.logging_utils import sentry_debug_logger data = OwnerListingSerializer(owner_listing).data data['source'] = config('HALANX_AFFILIATE_SOURCE') url = (config('HALANX_AFFILIATE_API_ENDPOINT') if settings.ENVIRONMENT == PRODUCTION else config('HALANX_AFFILIATE_TEST_API_ENDPOINT') ) + config('HALANX_AFFILIATE_OWNER_REFERRAL_API') resp = requests.post(url, data=data) print(resp.text) sentry_debug_logger.debug('url is ' + str(url) + 'data is' + str(data) + 'response is ' + str(resp.content)) logger.info( 'Finished add affiliate referral task for owner listing id {}'.format( owner_listing_id))
def send_house_visit_sms_and_send_scout_task(house_visit, area_manager, new=True): customer = house_visit.customer house = house_visit.house logger.info("Sending house visit SMS to area manager @ {}".format( area_manager.phone_no)) if new: msg = AREA_MANAGER_NEW_HOUSE_VISIT_NOTIFY_MSG.format( name=customer.name, phone_no=customer.phone_no, time=house_visit.scheduled_visit_time.strftime("%d %b at " "%I %p"), house="{}, {}".format(house.name, house.address)) else: msg = AREA_MANAGER_HOUSE_VISIT_NOTIFY_MSG.format( name=customer.name, phone_no=customer.phone_no, time=house_visit.scheduled_visit_time.strftime("%I %p"), house="{}, {}".format(house.name, house.address)) try: send_sms(area_manager.phone_no, msg) logger.info("Sent house visit SMS to area manager @ {}".format( area_manager.phone_no)) except Exception as e: logger.error(e) try: data = {'house_id': house.id, 'visit_id': house_visit.id} task_type = HOUSE_VISIT send_scout_task_to_scout_backend(data=data, task_type=task_type) except Exception as E: sentry_debug_logger.debug( 'error occurred while sending scout_task_for_house_visit ' + str(E), exc_info=True)
def send_scout_task_to_scout_backend(data, task_type): request_data = {DATA: data, TASK_TYPE: task_type} sentry_debug_logger.debug('sending scout task with data as ' + str(request_data)) x = requests.post(SCOUT_TASK_URL, data=json.dumps(request_data), headers={'Content-type': 'application/json'}, timeout=10, auth=(config('SCOUT_BACKEND_ADMIN_USERNAME'), config('SCOUT_BACKEND_ADMIN_PASSWORD'))) sentry_debug_logger.debug('status code in sending task to scout ' + str(x.status_code)) sentry_debug_logger.debug('content is ' + str(x.content))
def update(self, request, *args, **kwargs): wallet = get_object_or_404(TenantWallet, tenant__customer__user=request.user) customer = wallet.tenant.customer payment_ids = request.data.get('payments') payment_gateway = request.data.get('payment_gateway') transaction_id = request.data.get('transaction_id') try: collection_time_start = datetime.strptime(request.data.get('collection_time_start'), CASH_COLLECTION_TIME_FORMAT) except TypeError: collection_time_start = None payments = TenantPayment.objects.prefetch_related('wallet__tenant__customer'). \ filter(wallet=wallet, id__in=payment_ids, status=PENDING) total_amount = payments.aggregate(Sum('amount'))['amount__sum'] if len(payments) is 0: return Response({'error': 'No payments found.'}, status=status.HTTP_400_BAD_REQUEST) if payment_gateway in [CASH, FUND_TRANSFER]: transaction = CustomerTransaction.objects.create(amount=total_amount, customer=customer, transaction_id=transaction_id, platform=ANDROID_PLATFORM, payment_gateway=payment_gateway) if payment_gateway == CASH: area_manager = payments.first().booking.space.house.area_managers.first() if area_manager: transaction.collector = area_manager.user transaction.collection_time_start = collection_time_start transaction.save() # save one by one to call signals for payment in payments: payment.transaction = transaction payment.save() if payment_gateway == CASH: area_manager_cash_collection_notify.delay(transaction.id) elif payment_gateway in [PAYTM, PAYU]: if verify_transaction(transaction_id, payment_gateway, total_amount, customer=customer): transaction = CustomerTransaction.objects.get(transaction_id=transaction_id, customer=customer, complete=True) # save one by one to call signals for payment in payments: payment.status = PAID payment.paid_on = timezone.now() payment.transaction = transaction payment.save() elif payment_gateway in [RAZORPAY, ]: sentry_debug_logger.debug("Razor pay gateway detected", exc_info=True, extra={'tags': {'TenantPaymentBatch': {}}}) razorpay_payment_id = request.data.get('razorpay_payment_id') razorpay_signature = request.data.get('razorpay_signature') razorpay_order_id = transaction_id # or order_id if razorpay_payment_id and razorpay_order_id and razorpay_signature: sentry_debug_logger.debug( "Received all three razor pay params, now verifying signature and capturing payment", exc_info=True, extra={'tags': {'TenantPaymentBatch': {}}}) verified = verify_razorpay_payment_signature(razorpay_order_id, razorpay_payment_id, razorpay_signature) if verified: sentry_debug_logger.debug("Signature verified, now capturing payment", exc_info=True, extra={'tags': {'TenantPaymentBatch': {}}}) # Capture amount when signature verified and amount matches customer_transaction = CustomerTransaction.objects.get(transaction_id=transaction_id, customer=customer, payment_gateway=RAZORPAY) if not customer_transaction.cancelled and not customer_transaction.complete: if round(customer_transaction.amount, 2) == round(total_amount, 2): razorpay_capture_payment(razorpay_payment_id, round((customer_transaction.amount * 100), 2)) sentry_debug_logger.debug('Amount captured Succesfully', exc_info=True, extra={'tags': {'TenantPaymentBatch': {}}}) else: sentry_debug_logger.debug('tenant payment amount mismatch with customer transaction amount', extra={'tags': {'TenantPaymentBatch': {}}}) else: sentry_debug_logger.debug("Signature not verified", extra={'tags': {'TenantPaymentBatch': {}}}) else: sentry_debug_logger.debug("Razorpay Params not found", exc_info=True, extra={'tags': {'TenantPaymentBatch': {}}}) if verify_transaction(transaction_id, payment_gateway, total_amount, customer=customer): sentry_debug_logger.debug("Transaction verified", exc_info=True, extra={'tags': {'TenantPaymentBatch': {}}}) transaction = CustomerTransaction.objects.get(transaction_id=transaction_id, customer=customer, complete=True) # save one by one to call signals for payment in payments: payment.status = PAID payment.paid_on = timezone.now() payment.transaction = transaction payment.save() return Response({STATUS: SUCCESS, 'message': 'Successfully paid'}) else: return Response({STATUS: ERROR, 'message': 'Payment not verified'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'error': 'Invalid transaction'}, status=status.HTTP_400_BAD_REQUEST) logger.debug(str(payments)) return Response({'result': 'Successfully patched!'})
def update(self, request, *args, **kwargs): payment = self.get_object() customer = payment.wallet.tenant.customer apply_cashback = request.data.get('apply_cashback') payment_gateway = request.data.get('payment_gateway') transaction_id = request.data.get('transaction_id') try: collection_time_start = datetime.strptime(request.data.get('collection_time_start'), CASH_COLLECTION_TIME_FORMAT) except TypeError: collection_time_start = None if apply_cashback is not None: payment.apply_cashback = apply_cashback payment.save() elif payment_gateway in [CASH, FUND_TRANSFER]: payment.transaction = CustomerTransaction.objects.create(amount=payment.amount, customer=customer, transaction_id=transaction_id, platform=ANDROID_PLATFORM, payment_gateway=payment_gateway) if payment_gateway == CASH: area_manager = payment.booking.space.house.area_managers.first() if area_manager: payment.transaction.collector = area_manager.user payment.transaction.collection_time_start = collection_time_start payment.transaction.save() payment.save() area_manager_cash_collection_notify.delay(payment.transaction.id) elif payment_gateway in [PAYTM, PAYU]: sentry_debug_logger.debug(payment_gateway + " gateway detected", exc_info=True) if verify_transaction(transaction_id, payment_gateway, payment.amount, customer=customer): payment.status = PAID payment.paid_on = timezone.now() payment.transaction = CustomerTransaction.objects.get(transaction_id=transaction_id, customer=customer, complete=True) elif payment_gateway in [RAZORPAY, ]: sentry_debug_logger.debug("Razor pay gateway detected", exc_info=True) razorpay_payment_id = request.data.get('razorpay_payment_id') razorpay_signature = request.data.get('razorpay_signature') razorpay_order_id = transaction_id # or order_id if razorpay_payment_id and razorpay_order_id and razorpay_signature: sentry_debug_logger.debug( "Received all three razor pay params, now verifying signature and capturing payment", exc_info=True) verified = verify_razorpay_payment_signature(razorpay_order_id, razorpay_payment_id, razorpay_signature) if verified: sentry_debug_logger.debug("Signature verified, now capturing payment", exc_info=True) # Capture amount when signature verified and amount matches customer_transaction = CustomerTransaction.objects.get(transaction_id=transaction_id, customer=customer, payment_gateway=RAZORPAY) if not customer_transaction.cancelled and not customer_transaction.complete: if round(customer_transaction.amount, 2) == round(payment.amount, 2): razorpay_capture_payment(razorpay_payment_id, round((customer_transaction.amount * 100), 2)) sentry_debug_logger.debug('Amount captured Successfully', exc_info=True) else: sentry_debug_logger.debug('tenant payment amount mismatch with customer transaction amount') else: sentry_debug_logger.debug("Signature not verifed") else: sentry_debug_logger.debug("Razorpay Params not found", exc_info=True) if verify_transaction(transaction_id, payment_gateway, payment.amount, customer=customer): payment.status = PAID payment.paid_on = timezone.now() payment.transaction = CustomerTransaction.objects.get(transaction_id=transaction_id, customer=customer, complete=True) payment.save() return Response({'status': 'success', 'message': 'Successfully paid'}) else: return Response({'status': 'error', 'message': 'Payment not verified'}, status=status.HTTP_400_BAD_REQUEST) # elif payment_gateway in [TOTAL_HCASH, ] and True: # UnTested # sentry_debug_logger.debug(payment_gateway + " gateway detected", exc_info=True) # sentry_debug_logger.debug(payment_gateway + "payment amount is " + str(payment.amount), exc_info=True) # # If Transaction amount is 0 then create a transaction and pay directly as soon as # # gateway detected is TOTAL_HCASH # if round(payment.amount, 2) == 0: # payment.status = PAID # payment.transaction = CustomerTransaction.objects.create(amount=payment.amount, customer=customer, # platform=ANDROID_PLATFORM, # payment_gateway=payment_gateway, # ) # # payment.transaction.complete = True # payment.transaction.save() # payment.save() # # else: # return Response({'error': 'Invalid Transaction, Cant pay completely with HCASH'}, # status=status.HTTP_400_BAD_REQUEST) else: return Response({'error': 'Invalid transaction'}, status=status.HTTP_400_BAD_REQUEST) payment.save() serializer = self.get_serializer(payment) return Response(serializer.data)
def create_zoho_lead_from_tenant_lead_task(tenant_lead_id): time.sleep(1) # added sleep so that related objects data is also received tenant_lead = TenantLead.objects.get(id=tenant_lead_id) if not tenant_lead.zoho_id: # send record only if it does not have zoho id initally try: tenant_lead = TenantLead.objects.get( id=tenant_lead.id) # updated instance print(tenant_lead.preferred_location) record_ins_list = list() record = ZCRMRecord.get_instance('Leads') full_name = tenant_lead.name last_name = str(full_name) if full_name: last_name = full_name.split()[-1] record.set_field_value('Last_Name', last_name) record.set_field_value('Lead_Type', 'Tenant') if tenant_lead.name: record.set_field_value('Name1', tenant_lead.name) if tenant_lead.gender: record.set_field_value('Gender', tenant_lead.gender) if tenant_lead.phone_no: record.set_field_value('Mobile', tenant_lead.phone_no) if tenant_lead.email: record.set_field_value('Email', tenant_lead.email) if tenant_lead.description: record.set_field_value('Description', tenant_lead.description) if tenant_lead.space_type: record.set_field_value('AccomodationType', tenant_lead.space_type) if tenant_lead.space_subtype: record.set_field_value('Space_Sub_Type', tenant_lead.space_subtype) if tenant_lead.accomodation_for: record.set_field_value('Accommodation_For', tenant_lead.accomodation_for) if tenant_lead.preferred_location: if tenant_lead.preferred_location.street_address: record.set_field_value( 'Street', tenant_lead.preferred_location.street_address) if tenant_lead.preferred_location.zone: record.set_field_value('Zone', tenant_lead.preferred_location.zone) if tenant_lead.created_by.zoho_id: user = ZCRMUser.get_instance(tenant_lead.created_by.zoho_id) record.set_field_value('Owner', user) # Demand Data demand_data = {} if tenant_lead.expected_rent_min: demand_data['Rental_Budget'] = int( tenant_lead.expected_rent_min) if tenant_lead.expected_rent_max: demand_data['Max_Rental_Budget'] = int( tenant_lead.expected_rent_max) if tenant_lead.expected_movein_start: demand_data[ 'Move_In_Date'] = tenant_lead.expected_movein_start.strftime( "%Y-%m-%d") if tenant_lead.expected_movein_end: demand_data[ 'TO_Move_in_date'] = tenant_lead.expected_movein_end.strftime( "%Y-%m-%d") if demand_data: record.set_field_value('Demand', [demand_data]) record_ins_list.append(record) resp = ZCRMModule.get_instance('Leads').create_records( record_ins_list) bulk_entity_response, bulk_status_code = resp.bulk_entity_response, resp.status_code single_record_data = bulk_entity_response[0] if bulk_status_code == 201: if single_record_data.status == SUCCESS: tenant_lead.zoho_id = single_record_data.response_json[ 'details']['id'] tenant_lead.save() else: sentry_debug_logger.debug( 'status code for single record is' + str(single_record_data.status) + 'and message is' + str(single_record_data.message)) else: print(single_record_data.details) sentry_debug_logger.debug('status code for bulk record is' + str(resp.status_code) + 'and message is' + str(resp.message) + "error due to" + str(single_record_data.details)) # print(resp.status_code) # entity_responses = resp.bulk_entity_response # for entity_response in entity_responses: # print(entity_response.details) # print(entity_response.status) # print(entity_response.message) except ZCRMException as ex: # print(ex.status_code) # print(ex.error_message) # print(ex.error_code) # print(ex.error_details) # print(ex.error_content) print(traceback.format_exc()) sentry_debug_logger.error(ex, exc_info=True) except Exception as E: print(traceback.format_exc()) sentry_debug_logger.error(E, exc_info=True)
def get_appropriate_scout_for_the_task(task, scouts=None): from scouts.models import ScoutTaskAssignmentRequest from scouts.models import Scout house = House.objects.using(settings.HOMES_DB).filter(id=task.house_id).first() scheduled_task_time = None if task.category.name == HOUSE_VISIT: house_visit = HouseVisit.objects.using(settings.HOMES_DB).filter(id=task.visit_id).first() scheduled_task_time = house_visit.scheduled_visit_time house_latitude = house.address.latitude house_longitude = house.address.longitude elif task.category.name == MOVE_OUT: scheduled_task_time = TenantMoveOutRequest.objects.using(settings.HOMES_DB).filter(id=task.move_out_request_id) \ .first().timing house_latitude = house.address.latitude house_longitude = house.address.longitude elif task.category.name == PROPERTY_ONBOARDING: from scouts.sub_tasks.models import PropertyOnBoardingDetail property_on_boarding_detail = PropertyOnBoardingDetail.objects.filter(id=task.onboarding_property_details_id) \ .first() scheduled_task_time = property_on_boarding_detail.scheduled_at house_latitude = property_on_boarding_detail.latitude house_longitude = property_on_boarding_detail.longitude else: raise Exception({'detail': 'Task category is not in the choices available'}) if scouts is None: scouts = Scout.objects.all() # Remove all those scouts from the task when request is rejected rejected_scouts_id = ScoutTaskAssignmentRequest.objects.filter(task=task, status=REQUEST_REJECTED). \ values_list('scout', flat=True) scouts = scouts.exclude(id__in=rejected_scouts_id) if scheduled_task_time: # filter the scouts whose scheduled availabilities lie between visit scheduled visit time scouts = scouts.filter(Q(scheduled_availabilities__start_time__lte=scheduled_task_time) & Q(scheduled_availabilities__end_time__gte=scheduled_task_time) & Q(scheduled_availabilities__cancelled=False)) sentry_debug_logger.debug("queryset is " + str(scouts)) sorted_scouts = get_sorted_scouts_nearby(house_latitude=house_latitude, house_longitude=house_longitude, distance_range=50, queryset=scouts) try: selected_scout = sorted_scouts[0][0] if len(sorted_scouts) == 1: # CHANGE ALL REQUEST_REJECTED to REQUEST_AWAITED ScoutTaskAssignmentRequest.objects.filter(task=task, status=REQUEST_REJECTED, auto_rejected=True).update( status=REQUEST_AWAITED, auto_rejected=False) except Exception as E: selected_scout = None # sentry_debug_logger.debug("received scout is " + str(selected_scout)) return selected_scout
def owner_listing_post_save_hook(sender, instance, created, **kwargs): if created: sentry_debug_logger.debug('created owner listing', exc_info=True) add_affiliate_referral_task_owner_listing.delay(instance.id)