def queryset(self, request, queryset): if self.value() == 'plan': return queryset.filter( users__in=User.get_user_ids_with_active_plan()) elif self.value() == 'ppk': return queryset.filter( users__in=User.get_user_ids_with_active_ppk()).distinct() elif self.value() == 'plan_ppk': ids = set(User.get_user_ids_with_active_plan()) | set( User.get_user_ids_with_active_ppk()) return queryset.filter(users__in=ids).distinct() return queryset
def queryset(self): return super(Krysha, self).queryset().filter( addr_street__gt='', user__in=User.objects.filter( id__in=User.get_user_ids_with_active_ppk(), region__slug__in=[ 'kievskaya-oblast', 'odesskaya-oblast', 'hersonskaya-oblast', 'hmelnitskaya-oblast' ]), ).prefetch_related('phones')
def handle(self, *args, **options): print '--> Start Facebook autoposting process' # Внимание!!! Нельзя публиковать чаще чем 1 раз в 90 минут, иначе Facebook забанит allow_date = datetime.datetime.now() - datetime.timedelta(minutes=91) facebook_autoposting = FacebookAutoposting.objects.filter( (Q(last_posting_at__lt=allow_date) | Q(last_posting_at__isnull=True)) & Q(access_token_expires_at__gt=datetime.datetime.now(), is_active=True)).exclude(access_token__isnull=True) if facebook_autoposting.exists(): for fb_autoposting in facebook_autoposting: translation.activate(fb_autoposting.language) print ' --> choose ad for Facebook autoposting #%d' % fb_autoposting.id # Выбираем одно объявление по заданным параметрам, которое еще ни разу не публиковали ads = Ad.objects.filter( deal_type=fb_autoposting.deal_type, region__id__in=fb_autoposting.region.get_children_ids(), is_published=True, status=1, facebook_autoposting_ads__isnull=True, has_photos=True, price_uah__gte=fb_autoposting.min_price).order_by( '-created') ad = ads.filter(user__in=User.get_user_ids_with_active_ppk() ).first() or ads.first() if ad: print ' --> chosen ad #%d' % ad.pk graph = GraphAPI(access_token=fb_autoposting.access_token) try: object_id = graph.put_object( parent_object=fb_autoposting.page_id, connection_name='feed', link=ad.get_absolute_url(), message=ad.get_absolute_url(), published=True) except GraphAPIError as e: print ' --> error while posting ad', e continue fb_autoposting.last_posting_at = datetime.datetime.now() fb_autoposting.save() FacebookAutopostingAd.objects.create( facebook_autoposting=fb_autoposting, basead=ad.basead_ptr, page_id=object_id) print ' --> success posting to Facebook and mark Ad' print '<-- Finish Facebook autoposting process'
def filter_user_by_plan(queryset, parameter): from custom_user.models import User if parameter == 'w-plan': return queryset.filter(pk__in=User.get_user_ids_with_active_plan()) elif parameter == 'w-money-wo-plan': users_with_money = [ transaction['user'] for transaction in Transaction.objects.values('user').annotate( balance=models.Sum('amount')).order_by('user') if transaction['balance'] > 0 ] return queryset.filter(pk__in=users_with_money).exclude( pk__in=User.get_user_ids_with_active_plan()) elif parameter == 'wo-ads-w-plan': return queryset.filter(pk__in=User.get_user_ids_with_active_plan(), ads_count=0) elif parameter == 'w-ads-wo-plan': return queryset.filter(ads_count__gt=0).exclude( pk__in=User.get_user_ids_with_active_plan()) elif parameter == 'w-overlimit': users_with_overlimit = UserPlan.objects.filter( end__gt=datetime.datetime.now(), user__ads_count__gt=models.F('plan__ads_limit')).values_list( 'user', flat=True).order_by('user') return queryset.filter(pk__in=users_with_overlimit) elif parameter == 'w-expired-plan': prev_month_end = datetime.date.today().replace( day=1) - datetime.timedelta(days=1) prev_month_start = prev_month_end.replace(day=1) users_with_plan_in_prev_month = UserPlan.objects.filter( start__lt=prev_month_end, end__gt=prev_month_start).exclude( transactions__amount=0).values_list('user', flat=True) user_ids_w_expired_plan = set(users_with_plan_in_prev_month) - set( User.get_user_ids_with_active_plan()) return queryset.filter(pk__in=user_ids_w_expired_plan) elif parameter == 'w-plan-first-time': user_ids_w_plan_first_time = set( UserPlan.objects.filter( plan__is_active=True, user__in=User.get_user_ids_with_active_plan()).values( 'user').annotate(cnt=models.Count('user')).filter( cnt=1).values_list('user', flat=True)) return queryset.filter(pk__in=user_ids_w_plan_first_time) elif parameter == 'wo-any': return queryset.filter(transactions__isnull=True, ads__isnull=True) elif parameter == 'w-ppk': return queryset.filter(pk__in=User.get_user_ids_with_active_ppk())
def handle(self, **options): # translation.activate('uk') translation.activate('ru') if 'test_users' in options and options['test_users']: users_query = User.objects.filter(id__in=options['test_users']) else: # regions_id = Region.objects.get(id=55).get_children_ids() users_id = User.get_user_ids_with_active_plan() | set( User.get_user_ids_with_active_ppk()) users_query = User.objects.filter( # email__gt='', subscribe_news=True, ads__region__in=regions_id # email__gt='', subscribe_news=True, ads_count__gt=0 email__gt='', subscribe_news=True, id__in=users_id).distinct().order_by('id') if options['start_from_user']: users_query = users_query.filter( id__gte=options['start_from_user']) # pynliner - тормоз, лучше внутрь цикла его не класть content = render_to_string( 'mail/mailing/mail_about_new_services.jinja.html', {}) content_with_inline_css = pynliner.fromString(content) for user in users_query: print 'user #%d' % user.id message = EmailMessage( u'Обновленный раздел "Услуги" + мобильные номера телефонов', content_with_inline_css, settings.DEFAULT_FROM_EMAIL, [user.email]) message.content_subtype = 'html' message.send()
def handle(self, *args, **options): users_id = LeadGeneration.objects.filter( dedicated_numbers=True, user__in=User.get_user_ids_with_active_ppk()).values_list( 'user', flat=True) # Уведомляем об окончании услуги Выделенный номер за день до окончания service_will_end_for_users = User.objects.filter( Q(transactions__type=80, receive_sms=True, id__in=users_id) & (Q(transactions__time__range=( datetime.datetime.now() - datetime.timedelta(days=29), datetime.datetime.now() - datetime.timedelta(days=28))))).distinct().order_by('id') print '--> Start beforehand notification by sms', datetime.datetime.now( ) text = u'Завтра заканчивается срок действия услуги "Выделенный номер". Пополните баланс на 100 грн' for user in service_will_end_for_users: # если на балансе есть 100 грн, то за номер выделенный нлмер автоматически спишется if user.get_balance() < 100: print ' --> user #%d' % user.id user.send_notification(text) # Уведомляем об окончании услуги Выделенный номер за 7, 3 и в день окончания предоставления услуги service_will_end_for_users = User.objects.filter( Q(transactions__type=80, subscribe_info=True, id__in=users_id) & (Q(transactions__time__range=( datetime.datetime.now() - datetime.timedelta(days=23), datetime.datetime.now() - datetime.timedelta(days=22))) | Q(transactions__time__range=( datetime.datetime.now() - datetime.timedelta(days=27), datetime.datetime.now() - datetime.timedelta(days=26))) | Q(transactions__time__range=( datetime.datetime.now() - datetime.timedelta(days=30), datetime.datetime.now() - datetime.timedelta(days=29))))).distinct().order_by('id') print '--> Start beforehand notification', datetime.datetime.now() utm = make_utm_dict(utm_campaign='ppc_notification') for user in service_will_end_for_users: print ' --> user #%d' % user.id translation.activate(user.language) # Количество дней до окончания тарифа days = 30 - (datetime.datetime.now() - user.transactions.filter(type=80).first().time).days content = render_to_string( 'ppc/mail/ppc-notification-beforehand.jinja.html', { 'utm': utm, 'ga_pixel': make_ga_pixel_dict(user, utm), 'days': days }) content_with_inline_css = pynliner.fromString(content) message = EmailMessage( _('Заканчивается срок действия абон.платы услуги "Выделенный номер"' ), content_with_inline_css, settings.DEFAULT_FROM_EMAIL, [user.email]) message.content_subtype = 'html' message.send() # Уведомляем пользователей о неактивной услуге Выделенный номер # на следующий день после окончания услуги и через неделю print '--> Start afterward notification', datetime.datetime.now() service_ended_for_users = User.objects.filter( Q(transactions__type=80, subscribe_info=True) & (Q(transactions__time__range=( datetime.datetime.now() - datetime.timedelta(days=32), datetime.datetime.now() - datetime.timedelta(days=31))) | Q(transactions__time__range=( datetime.datetime.now() - datetime.timedelta(days=39), datetime.datetime.now() - datetime.timedelta(days=38))))).distinct().order_by('id') for user in service_ended_for_users: # Если у пользователя не было транзакций за Выделенный номер за последние 7 дней if not user.transactions.filter( type=80, time__gte=(datetime.datetime.now() - datetime.timedelta(days=7))).exists(): print ' --> user #%d' % user.id translation.activate(user.language) content = render_to_string( 'ppc/mail/ppc-notification-afterward.jinja.html', { 'utm': utm, 'ga_pixel': make_ga_pixel_dict(user, utm) }) content_with_inline_css = pynliner.fromString(content) message = EmailMessage( _('Закончился срок действия абон.платы услуги "Выделенный номер"' ), content_with_inline_css, settings.DEFAULT_FROM_EMAIL, [user.email]) message.content_subtype = 'html' message.send()
def handle(self, *args, **options): print '--> Start Vk autoposting process' # Внимание!!! Нельзя публиковать чаще чем 1 раз в 90 минут, иначе Vk забанит allow_date = datetime.datetime.now() - datetime.timedelta(minutes=91) vkontakte_autoposting = VkAutoposting.objects.filter( (Q(last_posting_at__lt=allow_date) | Q(last_posting_at__isnull=True)) & Q(is_active=True)) # access token response = requests.get('https://oauth.vk.com/access_token', params={ 'client_id': settings.VK_APP_ID, 'client_secret': settings.VK_APP_SECRET_KEY, 'v': 5.62, 'grant_type': 'client_credentials' }) access_token = response.json()['access_token'] if vkontakte_autoposting.exists(): for vk_autoposting in vkontakte_autoposting: translation.activate(vk_autoposting.language) print ' --> choose ad for Vk autoposting #%d' % vk_autoposting.id # Выбираем одно объявление по заданным параметрам, которое еще ни разу не публиковали ads = Ad.objects.filter( deal_type=vk_autoposting.deal_type, region__id__in=vk_autoposting.region.get_children_ids(), is_published=True, status=1, vk_autoposting_ads__isnull=True, has_photos=True).order_by('-created') ad = ads.filter(user__in=User.get_user_ids_with_active_ppk() ).first() or ads.first() if ad: print ' --> chosen ad #%d' % ad.pk vk_session = vk_api.VkApi( login=settings.VK_APP_LOGIN, password=settings.VK_APP_PASSWORD, token=access_token, config_filename=os.path.join(settings.VAR_ROOT, 'vk_config.json')) try: vk_session.authorization() except vk_api.AuthorizationError as e: print ' --> error while posting ad', e.message continue vk = vk_session.get_api() response = vk.wall.post(owner_id='-%s' % vk_autoposting.page_id, attachments=ad.get_absolute_url(), signed=0, from_group=1, guid=ad.pk, message=ad.get_absolute_url()) vk_autoposting.last_posting_at = datetime.datetime.now() vk_autoposting.save() VkAutopostingAd.objects.create( vk_autoposting=vk_autoposting, basead=ad.basead_ptr, page_id=response['post_id']) print ' --> success posting to Vk and mark Ad' print '<-- Finish Vk autoposting process'
def create_call_from_ringostat_json(data): from django.utils.dateparse import parse_datetime print ' call from %s to proxy %s at %s:' % ( data['caller'], data['n_alias'], data['calldate'][:19]), call_time = parse_datetime(data['calldate']).replace(tzinfo=None) call = Call.objects.filter(uniqueid1=data['uniqueid'], call_time=call_time).first() if call: print 'already existed: Call #%d' % call.pk return call numbers = [data['n_alias']] if data['n_alias'][0] == '0': numbers.append('38%s' % data['n_alias']) try: proxynumber = ProxyNumber.objects.get(number__in=numbers) except ProxyNumber.DoesNotExist: print 'proxynumber not found' return else: user = proxynumber.user object_id = cache.get('additional_number_for_call_%s' % data['uniqueid']) deal_type = proxynumber.deal_type # для создания звонка, даже если не определили куда переадресовывать # Иногда номер звонившего в формате '7908578862079085788620;79085788620', а иногда anonymous call = Call(proxynumber=proxynumber, uniqueid1=data['uniqueid'], call_time=call_time, callerid1='38000000000' if 'anonymous' in data['caller'] else data['caller'].split(';')[-1]) # определяем пользователя и тип сделки if object_id: print 'object id: %s |' % object_id, try: if proxynumber.deal_type == 'newhomes': user = Newhome.objects.get(pk=object_id).user deal_type = proxynumber.deal_type else: ad = Ad.objects.get(pk=object_id) deal_type = ad.deal_type user = ad.user except (Newhome.DoesNotExist, Ad.DoesNotExist): print '%s %s not found |' % (proxynumber.deal_type or 'ad', object_id), elif not user and proxynumber.is_shared and data['connected_with']: ''' Попытка найти пользователя по номеру с которым соединили, наприммер когда модератор вручную переадресовал А так же берем тип сделки судя по большинству объявлений пользователя ''' from custom_user.models import User from collections import Counter connected_with = data['connected_with'].split('@')[0] user = User.objects.filter( phones=connected_with, id__in=User.get_user_ids_with_active_ppk()).first() if user: deal_type = Counter( user.ads.filter(is_published=True).values_list( 'deal_type', flat=True)).most_common(1)[0][0] if not user: if proxynumber.is_shared: print 'no object id for shared number |', else: print 'dedicated number doesnt have attached user |', elif not user.has_active_leadgeneration(): print 'user doesnt have active leadgeneration |', else: call.user2 = user call.deal_type = deal_type call.object_id = object_id call.callerid2 = data['connected_with'].split('@')[ 0] # номер в формате '79068701187@billing/n' if data['disposition'] not in [ 'NO ANSWER', 'BUSY' ] and call.callerid2 and data['billsec']: call.duration = data['billsec'] call.save() print 'call #%s created' % call.pk, if call.duration and data.get('recording'): if call.download_record(data['recording']): print '| call record download sucessfully' else: print '| save url of call record in cache:', data['recording'] cache.set('call%d-record' % call.pk, data['recording'], 60 * 30) else: print return call