def handle(self, *args, **options): current_time = timezone.now() logger.info("Script:: retarget_user_inquiry:: Script started - current_time: %s" % current_time) try: user_ids_to_send_to = set() user_inquiries = UserInquiry.objects.filter(city_id=1, user__email__isnull=False, status__in=[6, 7, 10, 11]).exclude(user__email='') for ui in user_inquiries: # this user does not have any completed booking. if Booking.objects.filter(status_id__gte=9, user=ui.user, return_reason__isnull=True).exclude( status_id=24).exists(): logger.info("Script:: retarget_user_inquiry:: Skipping user as booking converted: %s", ui.user.id) continue else: user_ids_to_send_to.add(ui.user.id) try: logger.info("Script:: retarget_user_inquiry:: Sending mail to: %s", list(user_ids_to_send_to)) users = BumperUser.objects.filter(id__in=list(user_ids_to_send_to)) for user in users: try: email_service = NewEmailService([user.email], [], context={'name': user.name}, analytic_info={'sent_for_account_id': user.id}) email_service.send(template_folder_name='retargetting-inquiry-booking-cancelled') sleep(0.100) logger.info("Script:: retarget_user_inquiry:: Processed :%s", user.id) except: logger.info("Script:: retarget_user_inquiry:: Email send failure: %s", user.id) except: logger.exception("Script:: retarget_user_inquiry:: Failed") except: logger.exception("Script:: retarget_user_inquiry:: Failed to process to bookings")
def handle(self, *args, **options): current_time = timezone.now() logger.info( "Script:: retarget_booking_completed:: Script started - current_time: %s" % current_time) try: user_ids_to_send_to = set() bookings = Booking.objects.filter( city_id=1, user__email__isnull=False, status_id=23).exclude(user__email='') for ui in bookings: if InternalAccounts.objects.filter( phone=ui.user.phone).exclude( phone=8800165656).exists(): logger.info( "Script:: retarget_booking_completed:: Skipping As Internal Account: %s", ui.user.id) continue elif Booking.objects.filter( user=ui.user, return_reason__isnull=False).exists(): logger.info( "Script:: retarget_booking_completed:: Skipping As booking returned: %s", ui.user.id) continue else: user_ids_to_send_to.add(ui.user.id) try: logger.info( "Script:: retarget_booking_completed:: Sending mail to: %s", list(user_ids_to_send_to)) users = BumperUser.objects.filter( id__in=list(user_ids_to_send_to)) for user in users: try: email_service = NewEmailService( [user.email], [], context={'name': user.name}, analytic_info={'sent_for_account_id': user.id}) email_service.send(template_folder_name= 'retargetting-booking-completed') pass except: logger.info( "Script:: retarget_booking_completed:: Email send failure: %s", user.id) logger.info("Script:: retarget_booking_completed:: Processed") except: logger.exception( "Script:: retarget_booking_completed:: Failed") except: logger.exception( "Script:: retarget_booking_completed:: Failed to process to bookings" )
def capture_razor_pay_payment(razor_payment_id, amount_in_paise, booking_id, bumper_payment_id): logger.debug('Razor_payment_id=%s, Booking_id=%s, bumper_payment_id=%s' % (razor_payment_id,booking_id,bumper_payment_id)) response_from_razor = None try: url = 'https://api.razorpay.com/v1/payments/%s/capture' % razor_payment_id resp = requests.post(url, data={'amount': amount_in_paise}, auth=(settings.RAZOR_PAY_API_KEY, settings.RAZOR_PAY_API_SECRET)) if resp and resp.status_code == 200: # Payment captured. from core.models.payment import Payment payment = Payment.objects.filter(id=bumper_payment_id).first() if payment: payment.payment_vendor_id = razor_payment_id payment.tx_status = Payment.TX_STATUS_SUCCESS payment.vendor_status = resp.json().get('status') payment.save() return True else: response_from_razor = resp.json() logger.error('Failed to capture payment.booking_id=%s, Payment_id=%s, amount=%s, resp=%s' % (booking_id, bumper_payment_id, amount_in_paise, response_from_razor)) raise Exception('unable to capture response from Razor pay. %s' % response_from_razor) except: logger.exception('Failed to capture payment. Payment_id=%s, amount=%s' % (bumper_payment_id, amount_in_paise)) from services.email_service import NewEmailService from core.models.message import Messages email_service = NewEmailService( to_list=settings.ALERT_EMAIL_PAYMENT_FAILURE_TO_LIST, cc_list=settings.ALERT_EMAIL_PAYMENT_FAILURE_CC_LIST, bcc_list=[], context={}, email_format='html', analytic_info={ 'booking_id': booking_id }, message_direction=Messages.MESSAGE_DIRECTION_BUMPER_TO_OPS) email_service.send( email_body='Failed to capture payment.booking_id=%s, Payment_id=%s, amount=%s, response from Razor=%s' % (booking_id, bumper_payment_id, amount_in_paise, response_from_razor), subject='Bumper: Razor Pay, unable to capture payment [BookingID:%s]' % booking_id, template_folder_name=None)
def send_inquiry_to_ops(item, message): from core.models.master import Notifications from core.models.message import Messages notices = Notifications.objects.filter(name='OPS_MESSAGE_FROM_CUSTOMER') for notice in notices: if notice.type == Notifications.NOTIFICATION_TYPE_EMAIL: context = { 'name': item.user.name if item.user.name else '', 'email': item.user.email if item.user.email else '', 'mobile': item.user.phone if item.user.phone else '', 'city': item.city.name if item.city else '', 'message': message, 'utm_source': item.user.utm_source if item.user.utm_source else '', 'utm_medium': item.user.utm_medium if item.user.utm_medium else '', 'utm_campaign': item.user.utm_campaign if item.user.utm_campaign else '', 'source': item.source.source_desc if item.source else '', } # body = notice.template % context # subject = notice.subject % context logger.debug('Send Email for inquiry id=%s' % item.id) from services.email_service import NewEmailService email_service = NewEmailService( to_list=notice.get_to_list(), cc_list=notice.get_cc_list(), email_format='html', context=context, message_direction=Messages.MESSAGE_DIRECTION_BUMPER_TO_OPS, analytic_info={ 'notification_id': notice.id, 'sent_for_account_id': item.user.id }) email_service.send(email_body=notice.template, subject=notice.subject)
def handle(self, *args, **options): current_time = timezone.now() logger.info( "Script:: OPS_ALERTS_DAILY_SUMMARY:: Script started - current_time: %s" % current_time) current_context_time = _convert_to_given_timezone( timezone.now(), settings.TIME_ZONE) start_time = make_datetime_timezone_aware_convert_to_utc( str(current_context_time.date()) + " 00:00:00", "+0530") end_time = make_datetime_timezone_aware_convert_to_utc( str(current_context_time.date()) + " 23:59:59", "+0530") logger.info( "Script:: OPS_ALERTS_DAILY_SUMMARY:: start_time: %s - end_Time: %s" % (start_time, end_time)) try: ops_alerts_raised = BookingAlertTriggerStatus.objects.select_related('alert_type')\ .filter(created_at__range =[start_time, end_time]).exclude(alert_type_id__in=[1, 2]) logger.debug( 'Script:: OPS_ALERTS_DAILY_SUMMARY:: Bookings sent in notification: %s' % ops_alerts_raised) notification = Notifications.objects.get( name='OPS_ALERTS_DAILY_SUMMARY') cc_address_list = notification.get_cc_list() to_address_list = notification.get_to_list() email_service = NewEmailService( to_address_list, cc_address_list, context={'ops_alerts_raised': ops_alerts_raised}, analytic_info={'notification_id': notification.id}) email_service.send( template_folder_name=notification.template_folder_name) except: logger.exception( "Script:: OPS_ALERTS_DAILY_SUMMARY:: Failed to get bookings to process" )
def handle(self, *args, **options): current_time = timezone.now() logger.info( "Script:: retarget_booking_cancelled:: Script started - current_time: %s" % current_time) try: user_ids_to_send_to = set() bookings = Booking.objects.filter( city_id=1, user__email__isnull=False, status_id=24, ops_status_id=28, created_at__gt=(current_time - timezone.timedelta(days=180))).exclude( user__email='') for ui in bookings: # this user does not have any completed booking. if MessageUser.objects.filter( user=ui.user, message__subject= "Repair your car now before you will have to replace\n" ).exists(): logger.info( "Script:: retarget_booking_cancelled:: Skipping yesterday's mistake : %s", ui.user.id) continue elif Booking.objects.filter( status_id__gte=9, user=ui.user, return_reason__isnull=True).exclude( status_id=24).exists(): logger.info( "Script:: retarget_booking_cancelled:: Skipping user as booking converted: %s", ui.user.id) continue else: user_ids_to_send_to.add(ui.user.id) try: logger.info( "Script:: retarget_booking_cancelled:: Sending mail to: %s", list(user_ids_to_send_to)) users = BumperUser.objects.filter( id__in=list(user_ids_to_send_to)) for user in users: try: email_service = NewEmailService( [user.email], [], context={'name': user.name}, analytic_info={'sent_for_account_id': user.id}) email_service.send(template_folder_name= 'retargetting-booking-cancelled') sleep(0.100) except: logger.info( "Script:: retarget_booking_cancelled:: Email send failure: %s", user.id) logger.info("Script:: retarget_booking_cancelled:: Processed") except: logger.exception( "Script:: retarget_booking_cancelled:: Failed") except: logger.exception( "Script:: retarget_booking_cancelled:: Failed to process to bookings" )
def handle(self, *args, **options): current_time = timezone.now() logger.info( "Script:: retarget_booking_added_to_cart:: Script started - current_time: %s" % current_time) try: notification = Notifications.objects.get(id=154) booking_ids_to_send_to = set() bookings = Booking.objects.select_related('user').filter( user__email__isnull=False, status_id=1, created_at__lte=(current_time - timezone.timedelta(minutes=10))).exclude( user__email='') for booking in bookings: # this user does not have any completed booking. if not MessageUser.objects.filter( user=booking.user, message__notification=notification).exists(): booking_ids_to_send_to.add(booking.id) try: logger.info( "Script:: retarget_booking_added_to_cart:: Sending mail to: %s", list(booking_ids_to_send_to)) bookings = Booking.objects.select_related('user').filter( id__in=list(booking_ids_to_send_to)) for booking in bookings: try: template_vars = { 'name': booking.user.name, 'booking_id': booking.id } booking_data = BookingSerializer(booking).data template_vars['booking_data'] = booking_data logger.info( "Script:: retarget_booking_added_to_cart:: sending for: %s", booking.id) new_service = NewEmailService( to_list=[booking.user.email], cc_list=[], context=template_vars, sender='*****@*****.**', from_name='Shonalee', analytic_info={ 'booking_id': booking.id, 'notification_id': notification.id, 'sent_for_account_id': booking.user.id, 'action': 1, 'sent_by_id': booking.user.id, 'label': Messages.LABEL_ADDED_TO_CART_RETARGET, }) new_service.send(template_folder_name=notification. template_folder_name, attachments=[]) except: logger.info( "Script:: retarget_booking_added_to_cart:: Email send failure: %s", booking.id) logger.info( "Script:: retarget_booking_added_to_cart:: Processed") except: logger.exception( "Script:: retarget_booking_added_to_cart:: Failed") except: logger.exception( "Script:: retarget_booking_added_to_cart:: Failed to process to bookings" )
def handle(self, *args, **options): current_time = timezone.now() logger.info("Script:: retarget_booking_open:: Script started - current_time: %s" % current_time) try: user_ids_to_send_to = set() users_to_consider = list(Booking.objects.values_list('user', flat=True).filter(city_id=1, user__email__isnull=False, user__date_joined__gt=current_time - timezone.timedelta( weeks=2), status_id=1).exclude( user__email='')) users_to_consider += list(UserInquiry.objects.values_list('user', flat=True).filter(city_id=1, user__email__isnull=False, user__date_joined__gt=current_time - timezone.timedelta( weeks=2), status__in=[1, 2, 3, 5]).exclude( user__email='')) users = BumperUser.objects.filter(id__in=users_to_consider) for u in users: if InternalAccounts.objects.filter(phone=u.phone).exclude(phone=8800165656).exists(): logger.info("Script:: retarget_booking_open:: Skipping As Internal Account: %s", u.id) continue elif Booking.objects.filter(user=u, status_id__gte=3, status_id__lte=23).exists(): logger.info("Script:: retarget_booking_open:: Skipping As active booking there: %s", u.id) continue else: user_ids_to_send_to.add(u.id) try: logger.info("Script:: retarget_booking_open:: Sending mail to: %s - %s" % (len(list(user_ids_to_send_to)), list(user_ids_to_send_to))) send_to_users = BumperUser.objects.filter(id__in=list(user_ids_to_send_to)) for user in send_to_users: try: email_service = NewEmailService([user.email], [], context={'name': user.name}, analytic_info={'sent_for_account_id': user.id}) email_service.send(template_folder_name='retargetting-gst-change') except: logger.info("Script:: retarget_booking_open:: Email send failure: %s", user.id) extra_dict={} extra_dict['title'] = "Get your car repaired before 28th Aug to avoid GST price rise by 18%" extra_dict['ticker'] = '' extra_dict['type'] = 'app' extra_dict['label'] = Messages.LABEL_OFFER analytic_info = { } push_service = PushService(send_to_users) push_service.send_push_notice_to_users("We're adjusting our price from tomorrow, 25th Aug. But you can avail our services at the existing price if you get your car repaired before 28th August. *Exclusively for you*.", extra_dict, analytic_info=analytic_info) logger.info("Script:: retarget_booking_open:: Processed") except: logger.exception("Script:: retarget_booking_open:: Failed") except: logger.exception("Script:: retarget_booking_open:: Failed to process to bookings")
def send_custom_notification(notif_name, template_vars, params_dict=None, user=None, message_direction=None, attachments=None): """ Send Notification in general. :param notif_name: This is the notification name from the Notification Table. :param template_vars: This is the parameters dictionary required for populating subject and body. :param params_dict: This is the parameters dictionary required for analytic info or any other information. :param user: Optional: This is required only if notification is for user. :return: NOTE: This is only being tested for Email notification. For others use after testing. """ from core.models.master import Notifications from core.models.message import Messages from core.models.users import NotificationSubscriber try: if not params_dict: params_dict = {} logger.debug('Processing Notification notif_name=%s params_dict=%s' % (notif_name, params_dict)) notices = Notifications.objects.filter(name=notif_name) for notification in notices: if notification.type == Notifications.NOTIFICATION_TYPE_EMAIL: to_list = notification.get_to_list() cc_list = notification.get_cc_list() if notification.send_notice_to == Notifications.SEND_NOTICE_TO_CUSTOMER: to_list = [user.email] cc_list = [] new_service = NewEmailService( to_list=to_list, cc_list=cc_list, context=template_vars, message_direction=message_direction, analytic_info={ 'booking_id': params_dict.get('booking_id'), 'notification_id': notification.id, 'action': params_dict.get('action'), 'sent_for_account_id': params_dict.get('sent_for_account_id'), 'sent_by_id': params_dict.get('sent_by_id'), }) if notification.use_file_template: new_service.send( template_folder_name=notification.template_folder_name) else: new_service.send(email_body=notification.template, subject=notification.subject, attachments=attachments) elif notification.type == Notifications.NOTIFICATION_TYPE_SMS: # This is only for User for now. Will be modified when required to send SMS to ops team as well. sms_service = SMSService(user, is_promo=notification.is_promo) sms_text = notification.template try: sms_text = sms_text % template_vars if notification.send_notice_to in [ Notifications.SEND_NOTICE_TO_CUSTOMER, Notifications.SEND_NOTICE_TO_CUSTOM ]: analytic_info = { 'action': params_dict.get('action'), 'notification_id': notification.id, 'sent_by_id': params_dict.get('sent_by_id'), 'booking_id': params_dict.get('booking_id'), } recipient = params_dict.get('phone') if user and user.phone: recipient = user.phone if recipient: logger.info('Sending SMS to=%s content=%s' % (recipient, sms_text)) sms_service.send_sms(recipient, sms_text, analytic_info=analytic_info) else: logger.error( 'Sending SMS failed because no recipient, content=%s' % sms_text) except KeyError: logger.exception( 'SMS template using variable that is not in data. template=%s' % sms_text) elif notification.type == Notifications.NOTIFICATION_TYPE_PUSH: body = notification.template subject = notification.subject try: from pushNotificationManager import send_notification body = body % template_vars subject = subject % template_vars push_data = { 'message': body, 'notice_type': 'app', 'label': notification.push_level, 'title': subject, 'booking_id': params_dict.get('booking_id'), } send_to_user = [user] if notification.send_notice_to == Notifications.SEND_NOTICE_TO_OPS: notification_subscribers = NotificationSubscriber.objects.filter( notification=notification) for item in notification_subscribers: send_to_user.append(item.user) send_notification(send_to_user, push_data, sent_by_id=params_dict.get('sent_by_id'), notification_id=notification.id) except KeyError: logger.exception( 'Push notice template using variable that is not in data. template=%s' % body) except: logger.exception('Failed to Process Notification.')
def process_hooks(booking_id, action_taken, extra_info_for_template={}, sent_by_id=None, notice_for='flow'): """ :param booking_id: :param action_taken: :param notice_for: options flow/eod :return: """ logger.debug('Processing hook for booking_id=%s' % str(booking_id)) from core.models.booking import Booking, BookingPackage, BookingAddress from core.models.master import Hooks, Notifications from core.models.message import Messages from core.managers.bookingManager import get_bill_details_new from api.custom_auth import get_booking_token from core.managers.pushNotificationManager import send_notification_for_booking from core.managers.userManager import get_user_active_devices from core.models.users import NotificationSubscriber from api.serializers.bookingSerializers import BookingSerializer booking = Booking.objects.select_related( 'user', 'usercar', 'usercar__car_model').get(id=booking_id) hooks = Hooks.objects.select_related('notification').filter( action_taken=action_taken, notification__notice_for=notice_for) # TODO Refine this code. bill_amt = '' payable_amt = '' attachment = {} booking_token = get_booking_token(booking) app_redirect_link = get_short_url( settings.BUMPER_APP_URL_THROUGH_APP_REDIRECT_URL % str(booking_id)) direct_payment_url = get_short_url(settings.DIRECT_PAYMENT_URL_BASE % booking_token) payment_url = get_short_url(settings.PAYMENT_URL % str(booking_id)) bill_details = get_bill_details_new(booking) if bill_details and bill_details.get('total_amt'): bill_amt = bill_details.get('total_amt') if bill_details and bill_details.get('payable_amt'): payable_amt = bill_details.get('payable_amt') booking_packages = BookingPackage.objects.filter(booking=booking) package_taken = [] for item in booking_packages: package_taken.append(item.package.package.name) pickup_time = format_datetime_for_grid(booking.pickup_time) if pickup_time and format_datetime_for_grid(booking.pickup_slot_end_time): pickup_time = pickup_time + ' - ' + format_datetime_for_msg( booking.pickup_slot_end_time) customer_eta_dt = format_date_for_grid(booking.estimate_complete_time) customer_eta_datetime = format_datetime_for_grid( booking.estimate_complete_time) pickup_address = booking.booking_address.filter( type=BookingAddress.ADDRESS_TYPE_PICKUP).first() drop_address = booking.booking_address.filter( type=BookingAddress.ADDRESS_TYPE_DROP).first() user_has_app = False if get_user_active_devices(booking.user): user_has_app = True template_vars = { 'booking_id': booking_id, 'city': booking.city.name if booking.city else '', 'car_model': booking.usercar.car_model, 'car_reg_no': booking.usercar.registration_number if booking.usercar.registration_number else '', 'pickup_driver_name': booking.pickup_driver.name if booking.pickup_driver else '', 'pickup_driver_phone': booking.pickup_driver.ops_phone if booking.pickup_driver else '', 'drop_driver_name': booking.drop_driver.name if booking.drop_driver else '', 'drop_driver_phone': booking.drop_driver.ops_phone if booking.drop_driver else '', 'cc_num': settings.BUMPER_SUPPORT_NUM, # customer care bumper 'cc_email': settings.BUMPER_SUPPORT_EMAIL, # customer care bumper 'bill_amount': bill_amt, 'payable_amt': payable_amt, 'package_list': booking_packages, 'package_details': ', '.join(package_taken), 'pickup_details': pickup_time if pickup_time else '', 'customer_name': booking.user.name, 'customer_phone': booking.user.phone, 'current_status': booking.status.status_desc if booking.status else '', 'current_ops_status': booking.ops_status.ops_status_desc if booking.ops_status else '', 'pickup_address': "%s %s %s %s" % (pickup_address.address.address1, pickup_address.address.address2 if pickup_address.address.address2 else '', pickup_address.address.city if pickup_address.address.city else '', pickup_address.address.pin_code if pickup_address.address.pin_code else '') if pickup_address else '', 'user_has_app': user_has_app, 'amt_paid': extra_info_for_template.get('amt_paid'), 'app_redirect_url': app_redirect_link, 'utm_source': booking.user.utm_source if booking.user.utm_source else '', 'utm_medium': booking.user.utm_medium if booking.user.utm_medium else '', 'utm_campaign': booking.user.utm_campaign if booking.user.utm_campaign else '', 'user_source': booking.user.source if booking.user.source else '', 'booking_source': booking.source if booking.source else '', 'delivery_datetime': customer_eta_datetime, 'delivery_dt': customer_eta_dt, "payment_link": payment_url, "direct_payment_link": direct_payment_url, "feedback_link": settings.FEEDBACK_BASE_URL % booking_token, "base_url": settings.BASE_URL_WEB, "booking_token": booking_token, } for hook in hooks: try: logger.debug('Processing hook for booking_id=%s hook_id=%s' % (booking_id, hook.id)) if hook.notification.type == Notifications.NOTIFICATION_TYPE_EMAIL: booking_data = BookingSerializer(booking).data template_vars['booking_data'] = booking_data to_list = hook.notification.get_to_list() cc_list = hook.notification.get_cc_list() if hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_CUSTOMER: to_list = [booking.user.email] cc_list = [] new_service = NewEmailService( to_list=to_list, cc_list=cc_list, context=template_vars, analytic_info={ 'booking_id': booking.id, 'notification_id': hook.notification.id, 'sent_for_account_id': booking.user.id, 'action': action_taken, 'sent_by_id': sent_by_id, 'label': Messages.LABEL_EOD if notice_for == Notifications.NOTICE_FOR_EOD else None, }) if action_taken == 16: attachment = { 'content': base64.b64encode( pdf('invoice.html', template_vars).read()), 'name': 'invoice_pdf', 'type': 'application/pdf' } if hook.notification.use_file_template: new_service.send(template_folder_name=hook.notification. template_folder_name, attachments=[attachment]) else: new_service.send(email_body=hook.notification.template, subject=hook.notification.subject) elif hook.notification.type == Notifications.NOTIFICATION_TYPE_SMS: sms_service = SMSService(booking.user, is_promo=hook.notification.is_promo) sms_text = hook.notification.template try: sms_text = sms_text % template_vars send_to_phone = None if hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_CUSTOMER: send_to_phone = booking.user.phone elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_OPS: send_to_phone = hook.notification.to elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_PICKUP_DRIVER: send_to_phone = booking.pickup_driver.ops_phone if booking.pickup_driver else None elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_DROP_DRIVER: send_to_phone = booking.drop_driver.ops_phone if booking.drop_driver else None elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_WORKSHOP_EXECUTIVE: send_to_phone = booking.workshop_executive.ops_phone if booking.workshop_executive else None if send_to_phone: analytic_info = { 'action': action_taken, 'notification_id': hook.notification.id, 'sent_by_id': sent_by_id, 'booking_id': booking.id, 'label': Messages.LABEL_EOD if notice_for == Notifications.NOTICE_FOR_EOD else None, } logger.info('Sending SMS to=%s content=%s' % (send_to_phone, sms_text)) sms_service.send_sms(send_to_phone, sms_text, analytic_info=analytic_info) except KeyError: logger.exception( 'SMS template using variable that is not in data. template=%s' % sms_text) elif hook.notification.type == Notifications.NOTIFICATION_TYPE_PUSH: body = hook.notification.template subject = hook.notification.subject try: body = body % template_vars subject = subject % template_vars send_to_user = [] if hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_CUSTOMER: send_to_user = [booking.user] elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_PICKUP_DRIVER: send_to_user = [booking.pickup_driver] elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_DROP_DRIVER: send_to_user = [booking.drop_driver] elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_WORKSHOP_EXECUTIVE: from core.models.users import WorkshopUser list_of_users = [] for item in WorkshopUser.objects.filter( workshop=booking.workshop, role=WorkshopUser.ROLE_BUMPER_EXECUTIVE): list_of_users.append(item.user) send_to_user = list_of_users elif hook.notification.send_notice_to == Notifications.SEND_NOTICE_TO_OPS: notification_subscribers = NotificationSubscriber.objects.filter( notification=hook.notification) for item in notification_subscribers: send_to_user.append(item.user) if send_to_user: send_notification_for_booking( send_to_user, booking, body, subject, action_taken, notification_id=hook.notification.id, sent_by_id=sent_by_id, notice_push_level=hook.notification.push_level) except KeyError: logger.exception( 'Push notice template using variable that is not in data. template=%s' % body) except: logger.exception('Failed to Process Hook=%s' % hook)
def send_async_new_email_service(to_list, cc_list=[], subject=None, body=None, template_folder_name=None, bcc_list=[], context={},email_format='text', analytic_info={}, message_direction=1): from services.email_service import NewEmailService email_service = NewEmailService(to_list, cc_list, bcc_list=bcc_list, context=context, email_format=email_format, analytic_info=analytic_info, message_direction=message_direction) email_service.send(email_body=body, subject=subject,template_folder_name=template_folder_name)
def handle(self, *args, **options): current_time = timezone.now() logger.info("Script:: PICKUP_SUMMARY:: Script started - current_time: %s" % current_time) override_subject = None if options['reminder']: override_subject = "Reminder to set Tomorrow's Pickup" # pickup time in next day current_context_time = _convert_to_given_timezone(timezone.now(), settings.TIME_ZONE) date_for_tomorrow_in_current_context = current_context_time + timezone.timedelta(days=1) start_time = make_datetime_timezone_aware_convert_to_utc(str(date_for_tomorrow_in_current_context.date())+" 00:00:00", "+0530") end_time = start_time + timezone.timedelta(hours=24) logger.info("Script:: PICKUP_SUMMARY:: start_time: %s - end_Time: %s" % (start_time, end_time)) try: pickup_in_next_day_bookings = Booking.objects.select_related('user', 'usercar', 'usercar__car_model')\ .filter(status_id__lt=9, pickup_time__range =[start_time, end_time])\ .exclude(ops_status_id=8) pickup_data = [] for booking in pickup_in_next_day_bookings: booking_packages = BookingPackage.objects.filter(booking=booking) package_taken = [] panels = 0 for item in booking_packages: package_taken.append(item.package.package.name) if item.package.package.category == Package.CATEGORY_DENT: for panel_item in BookingPackagePanel.objects.filter(booking_package=item): # Not using count here as full body will be counted as 14 panels. panels += 1 if item.package.package.category == Package.CATEGORY_FULL_BODY: panels += 14 pickup_address = booking.booking_address.filter(type=BookingAddress.ADDRESS_TYPE_PICKUP).first() pickup_data.append({ 'bookingId': booking.id, 'name': booking.user.name, 'phone': booking.user.phone, 'time': format_datetime_for_grid(booking.pickup_time), 'address': "%s, %s" % (pickup_address.address.address1, pickup_address.address.address2), 'packages': ', '.join(package_taken), 'panels': panels, 'car': str(booking.usercar.car_model), 'driver': booking.pickup_driver.name if booking.pickup_driver else '', }) try: logger.info("Script:: PICKUP_SUMMARY:: pickup data: %s" % (pickup_data)) notification = Notifications.objects.get(name='OPS_ALERT_PICKUP_FOR_TOMORROW') cc_address_list = notification.get_cc_list() to_address_list = notification.get_to_list() email_service = NewEmailService(to_address_list, cc_address_list, context={'pickup_data': pickup_data}, analytic_info={'notification_id': notification.id}) email_service.send(template_folder_name=notification.template_folder_name, subject=override_subject) logger.info("Script:: PICKUP_SUMMARY:: Sent") except: logger.exception("Script:: PICKUP_SUMMARY:: Failed") except: logger.exception("Script:: PICKUP_SUMMARY:: Failed to process to bookings")