from .models import * from datetime import datetime, timedelta from django.utils.translation import gettext as _ from django.template.loader import render_to_string from GeneralApp.funcs_options import get_options_by_opt_types, get_mail_send_options from BaseModels.mailSender import admin_send_mail_by_SMTPlib, techSendMail from SubscribesApp.funcs import check_option_in_cur_user_subscribe def get_Dict_for_send_msgs(kwargs, search_owner_type): print('get_Dict_for_send_msgs') Dict = { 'search_owner_type': search_owner_type } sets = get_options_by_opt_types(['domain', 'project_name'], only_vals=True) Dict.update(sets) Dict.update({'logo': f'{sets["domain"]}/static/img/svg/LogoMobile.svg', }) find_routes_page_url = f'{sets["domain"]}/routes/route_search_results/?' kwargs_list = [f'{key}={value}' for key, value in kwargs.items()] kwargs_list.append(f'owner_type={search_owner_type}') find_routes_page_url += f'{"&".join(kwargs_list)}' Dict.update({'find_routes_page_url': find_routes_page_url}) return Dict def send_push_message_for_found_matches_routes(route, data_Dict): print(f'send_push_message_for_found_matches_routes to route id = {route.id}') if not route.owner.is_authenticated: return None if not check_option_in_cur_user_subscribe(route.owner, 'push уведомления'): return False from PushMessages.views import send_push title = 'Мы нашли исполнителя по Вашему объявлению!' text = 'Для просмотра результата нажмите на кнопку ниже' send_push(route.owner, title, text, url=data_Dict['find_routes_page_url'], button_name=_('Перейти к найденному')) return None def send_mail_found_matches_routes(route, matched_route, data_Dict): print(f'send_mail_found_matches_routes to route id = {route.id}') Dict = { 'route': route, } Dict.update(data_Dict) html = render_to_string('mail/m_found_matched_routes.html', Dict) mail_sets = get_mail_send_options() to = [route.owner.email] subject = _('Мы нашли исполнителя по Вашему объявлению!') res = admin_send_mail_by_SMTPlib( mail_sets, subject=subject, from_email=mail_sets['sender_email'], to=to, html_content=html ) subject = f'route matches {route.id} <> {matched_route.id} send to {route.owner.email}' to = ['web@syncsystems.net', 'sa@a3-global.com'] res = admin_send_mail_by_SMTPlib( mail_sets, subject=subject, from_email=mail_sets['sender_email'], to=to, html_content=html ) return res def user_notify_by_result_search_matches(route_for_send, founded_route, params): log = '' data_Dict = None try: data_Dict = get_Dict_for_send_msgs(params, founded_route.owner_type) except Exception as e: msg = f'
\n! search_matches Error get_Dict_for_send_msgs = {str(e)}' print(msg) log += msg if data_Dict and check_option_in_cur_user_subscribe( route_for_send.owner, 'push уведомления' ): try: msg = send_push_message_for_found_matches_routes(route_for_send, data_Dict) if msg: log += msg except Exception as e: msg = f'
\n! search_matches Error send_push_message_for_found_matches_routes = {str(e)}' print(msg) log += msg if data_Dict and check_option_in_cur_user_subscribe( route_for_send.owner, 'уведомление на e-mail о появлении перевозчика по заданным критериям' ): try: msg = send_mail_found_matches_routes(route_for_send, founded_route, data_Dict) if msg: log += msg except Exception as e: msg = f'
\n! search_matches Error send_mail_found_matches_routes = {str(e)}' print(msg) log += msg return log def users_notify_by_result_search_matches(source_route, found_routes, params): log = '' log += user_notify_by_result_search_matches(source_route, found_routes[0], params) for route in found_routes: log += user_notify_by_result_search_matches(route, source_route, params) return log def search_matches(for_routes=None): print('search_matches') log = '' try: if not for_routes: for_routes = Route.objects.filter( createDT__gte=datetime.now() - timedelta(hours=1), receive_msg_by_email=True ) check_fields = [ 'type_transport', 'departure_DT', 'arrival_DT', # 'from_address_point', 'to_address_point', 'from_place', 'to_place', 'cargo_type', 'weight', 'from_city', 'to_city', ] if for_routes: msg = f'last hour create routes count = {for_routes.count()}' else: msg = f'last hour not create routes' print(msg) for route in for_routes: kwargs = {} params = {} for field_name in check_fields: field_val = getattr(route, field_name, None) if field_val: if type(field_val) == datetime: params.update({f"{field_name}": f'{field_val.strftime("%d.%m.%Y")} - {field_val.strftime("%d.%m.%Y")}'}) kwargs.update({f"{field_name}__date": field_val.date()}) elif field_name == 'weight': # print(field_name) if route.owner_type == 'mover': # params.update({f"{field_name}__lte": field_val}) kwargs.update({f"{field_name}__lte": field_val}) else: # params.update({f"{field_name}__gte": field_val}) kwargs.update({f"{field_name}__gte": field_val}) elif field_name == 'from_city': params.update({'from_address_point': field_val.id}) kwargs.update({field_name: field_val}) elif field_name == 'to_city': params.update({'to_address_point': field_val.id}) kwargs.update({field_name: field_val}) # elif field_name in ['from_address_point', 'to_address_point']: # kwargs.update({field_name: field_val}) else: kwargs.update({field_name: field_val}) params.update({field_name: field_val}) found_routes = Route.objects.exclude( id=route.id, ).exclude( owner=route.owner ).exclude( owner_type=route.owner_type ).filter( **kwargs # ).count( ) if found_routes: msg = f'found routes for send messages = {found_routes.count()}' print(msg) log += users_notify_by_result_search_matches(route, found_routes, params) except Exception as e: msg = f'
\n! search_matches Error = {str(e)}' print(msg) log += msg mail_sets = get_mail_send_options() techSendMail(mail_sets, log, title='search_matches fail') return log