Beispiel #1
0
    def get_queryset(self):
        two_week_interval = int(self.request.GET.get('week', 0)) * 14

        cursor = connection.cursor()
        cursor.execute('SELECT DISTINCT(e.start::date) FROM "events_event" AS e INNER JOIN "events_recording" AS rec'
                       ' ON e.id=rec.event_id WHERE date_part(\'hour\', e.start) > 12 ORDER BY start DESC LIMIT 14 OFFSET %s', [two_week_interval])
        dates = [d[0] for d in cursor.fetchall()]
        date_range_start = datetime.combine(dates[-1], std_time(10, 0))
        self.date_start = date_range_start
        date_range_end = dates[0] + timedelta(days=1)
        date_range_end = datetime.combine(date_range_end, std_time(4, 0))
        events = Event.objects.exclude(recordings=None).filter(start__gte=date_range_start, start__lte=date_range_end).order_by('start')
        if not self.request.user.is_staff:
            events = events.exclude(state=Event.STATUS.Draft)

        events = events.annotate(product_count=Count('products')).extra(select={
            'video_count': "SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE "
                           "events_recording.event_id = events_event. ID AND "
                           "events_recording.media_file_id = multimedia_mediafile. ID AND "
                           " events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'"
                           " GROUP BY events_event.id",
            'audio_count': "SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE "
                           "events_recording.event_id = events_event. ID AND "
                           "events_recording.media_file_id = multimedia_mediafile. ID AND "
                           " events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'"
                           " GROUP BY events_event.id",
        })
        dates = {}
        for k, g in groupby(events, lambda e: e.listing_date()):
            dates[k] = list(g)
        sorted_dates = OrderedDict(sorted(dates.items(), key=lambda d: d[0])).items()
        return sorted_dates
Beispiel #2
0
    def validate_date(self, value):
        """
        validate the date field
            - the date must not have the duplicate for one host
            - Host cant register in date that host is service
            - Host cant register date in the past
        """
        host = Host.objects.get(account=self.context["request"].user)

        if value < date.today():
            raise serializers.ValidationError("Do you have a time machine?")

        if HostAvailableDate.objects.filter(date=value, host=host).exists():
            raise serializers.ValidationError(
                "This date has already been assigned for this host")

        min_time = datetime.min.time()
        in_progess_service = Services.objects.filter(
            host=host,
            service_start_time__lte=make_aware(
                datetime.combine(value, min_time)),
            service_end_time__gte=make_aware(datetime.combine(value,
                                                              min_time)),
            main_status__in=["in_progress", "wait_for_progress", "payment"],
        )
        if in_progess_service.exists():
            raise serializers.ValidationError(
                "This date in in your service date")

        return value
Beispiel #3
0
    def today(self):
        from django.utils import timezone
        from django.utils.timezone import datetime, timedelta

        today = timezone.now().date()
        tomorrow = today + timedelta(1)
        today_start = datetime.combine(today, timezone.now().time())
        today_end = datetime.combine(tomorrow, timezone.now().time())

        today_start = timezone.make_aware(today_start,
                                          timezone.get_current_timezone())
        today_end = timezone.make_aware(today_end,
                                        timezone.get_current_timezone())

        return self.filter(time__lte=today_end, time__gte=today_start)
def send_report_from_subscriptions():
    User = get_user_model()
    date_till = datetime.combine(date.today(),
                                 datetime.min.time()).replace(tzinfo=pytz.utc)
    date_from = date_till - timedelta(days=1)
    for user in User.objects.filter(state='active'):
        user.send_subscriptions_report(date_from, date_till)
    return {}
Beispiel #5
0
def aware_timedelta_days(to_move: datetime,
                         timedelta_days: timedelta) -> datetime:
    # This is to check for correct timezone/DST setting, see why we separate date and time here:
    # https://gist.github.com/codeinthehole/1ac10da7874033406f25f86df07b88ff
    to_move_date = localdate(to_move) + timedelta_days
    to_move_time = localtime(to_move).time()

    return make_aware(datetime.combine(to_move_date, to_move_time))
Beispiel #6
0
def count(users, hour, day):
    count = 0
    start_time = datetime.time(second=0, hour=hour, minute=0)
    end_time = datetime.time(hour=hour + 2, minute=0, second=0)
    start = dt.combine(day, start_time)
    end = dt.combine(day, end_time)
    print start
    for user in users:
        tasks_start = Task.objects.filter(user=user,
                                          start_time__range=(start, end))
        tasks_end = \
            Task.objects.exclude(user=user,
                                 start_time__range=(start, end)).filter(user=user,
                                                                        end_time__range=(start, end))
        print tasks_end
        count += tasks_start.count() + tasks_end.count()
    return count
Beispiel #7
0
    def get_current_scheduling_block(self) -> (datetime, datetime):
        tz = self.get_timezone()
        rn = tz.normalize(now())
        start = max(rn, tz.localize(datetime.combine(rn.date(), self.start_day_at)))
        end = tz.localize(datetime.combine(rn.date(), self.end_day_at))
        if rn.time() >= self.end_day_at:
            # The end time has passed; time to schedule tomorrow
            start = tz.localize(
                datetime.combine(rn.date(), self.start_day_at)
            ) + timedelta(days=1)
            end = tz.localize(datetime.combine(rn.date(), self.end_day_at)) + timedelta(
                days=1
            )

        if not str(start.isoweekday()) in self.days_of_week.split():
            return None

        return (start, end)
Beispiel #8
0
class TaskWeekAPIView(APIView):
    """ api for task in a week"""

    first_day = timezone.make_aware(
        dt.combine(datetime.date.today(), datetime.time()),
        timezone.get_current_timezone())
    second_day = timezone.make_aware(
        dt.combine(datetime.date.today() + datetime.timedelta(days=1),
                   datetime.time()), timezone.get_current_timezone())
    third_day = timezone.make_aware(
        dt.combine(datetime.date.today() + datetime.timedelta(days=2),
                   datetime.time()), timezone.get_current_timezone())
    fourth_day = timezone.make_aware(
        dt.combine(datetime.date.today() + datetime.timedelta(days=3),
                   datetime.time()), timezone.get_current_timezone())
    fifth_day = timezone.make_aware(
        dt.combine(datetime.date.today() + datetime.timedelta(days=4),
                   datetime.time()), timezone.get_current_timezone())
    sixth_day = timezone.make_aware(
        dt.combine(datetime.date.today() + datetime.timedelta(days=5),
                   datetime.time()), timezone.get_current_timezone())
    seventh_day = timezone.make_aware(
        dt.combine(datetime.date.today() + datetime.timedelta(days=6),
                   datetime.time()), timezone.get_current_timezone())
    eighth_day = timezone.make_aware(
        dt.combine(datetime.date.today() + datetime.timedelta(days=7),
                   datetime.time()), timezone.get_current_timezone())

    def get_queryset(self, day1, day2):
        user = self.request.user
        queryset = Task.objects.filter(user=user,
                                       start_time__range=(day1, day2))
        return queryset

    def get_serializer(self, day1, day2):
        queryset = self.get_queryset(day1=day1, day2=day2)
        serializer = TaskListSerializer(queryset,
                                        context={'request': self.request},
                                        many=True)
        return serializer.data

    def get(self, request, *args, **kwargs):
        week_dict = {
            'first_day': self.get_serializer(self.first_day, self.second_day),
            'second_day': self.get_serializer(self.second_day, self.third_day),
            'third_day': self.get_serializer(self.third_day, self.fourth_day),
            'fourth_day': self.get_serializer(self.fourth_day, self.fifth_day),
            'fifth_day': self.get_serializer(self.fifth_day, self.sixth_day),
            'sixth_day': self.get_serializer(self.sixth_day, self.seventh_day),
            'seventh_day': self.get_serializer(self.seventh_day,
                                               self.eighth_day)
        }
        return Response(week_dict, status=HTTP_200_OK)
 def get_context_data(self, **kwargs):
     context = super(
         AgendaContactoDetailView, self).get_context_data(**kwargs)
     agente_profile = self.request.user.get_agente_profile()
     fechas_agendas = AgendaContacto.objects.proximas(agente_profile).values_list(
         'fecha', 'hora')
     fechas_agendas = [
         make_aware(datetime.combine(x[0], x[1])).isoformat() for x in fechas_agendas]
     context['fechas_agendas_json'] = json.dumps(fechas_agendas)
     return context
Beispiel #10
0
    def get_queryset(self):
        two_week_interval = int(self.request.GET.get('week', 0)) * 14

        cursor = connection.cursor()
        cursor.execute(
            'SELECT DISTINCT(e.start::date) FROM "events_event" AS e INNER JOIN "events_recording" AS rec'
            ' ON e.id=rec.event_id WHERE date_part(\'hour\', e.start) > 12 ORDER BY start DESC LIMIT 14 OFFSET %s',
            [two_week_interval])
        dates = [d[0] for d in cursor.fetchall()]
        date_range_start = datetime.combine(dates[-1], std_time(10, 0))
        self.date_start = date_range_start
        date_range_end = dates[0] + timedelta(days=1)
        date_range_end = datetime.combine(date_range_end, std_time(4, 0))
        events = Event.objects.exclude(recordings=None).filter(
            start__gte=date_range_start,
            start__lte=date_range_end).order_by('start')
        if not self.request.user.is_staff:
            events = events.exclude(state=Event.STATUS.Draft)

        events = events.annotate(product_count=Count('products')).extra(
            select={
                'video_count':
                "SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE "
                "events_recording.event_id = events_event. ID AND "
                "events_recording.media_file_id = multimedia_mediafile. ID AND "
                " events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'"
                " GROUP BY events_event.id",
                'audio_count':
                "SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE "
                "events_recording.event_id = events_event. ID AND "
                "events_recording.media_file_id = multimedia_mediafile. ID AND "
                " events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'"
                " GROUP BY events_event.id",
            })
        dates = {}
        for k, g in groupby(events, lambda e: e.listing_date()):
            dates[k] = list(g)
        sorted_dates = OrderedDict(sorted(dates.items(),
                                          key=lambda d: d[0])).items()
        return sorted_dates
Beispiel #11
0
def to_step_start(time, offset=0):
    """Calculate the exact time (midnight) of the previous timestep as
    defined by the project settings. The optional offset parameter
    increments or decrements the provided number of weeks
    """

    return datetime.combine(
        time.date() - timedelta(days=(
            (time.weekday() - DAYS.index(settings.DISTRIBUTION_DAY)) %
            len(DAYS)) - offset * len(DAYS)),
        datetime.min.time(),
        tzinfo=time.tzinfo,
    )
Beispiel #12
0
    def create_slot_times(self):
        try:
            days = get_week_map_by_weekday(
                get_range_days(self.start_date, self.end_date))
        except Exception as e:
            raise e

        if self.booking_type.dailyslottimepattern_set.count() == 0:
            raise ValueError("{title} has no related DailySlotTimePattern "
                             "objects".format(title=self.booking_type.title))

        count = 0
        for pattern in self.booking_type.dailyslottimepattern_set.all():
            for day in days[str(pattern.day)]:
                cache_start_datetime = make_aware(
                    datetime.combine(day, pattern.start_time),
                    get_current_timezone())
                end_datetime = make_aware(
                    datetime.combine(day, pattern.end_time),
                    get_current_timezone())
                while (((end_datetime - cache_start_datetime).seconds / 60)
                        >= pattern.booking_type.slot_length):
                    start_slot = cache_start_datetime
                    end_slot = cache_start_datetime + timedelta(
                        minutes=pattern.booking_type.slot_length)
                    try:
                        slot, created = (
                            self.slottime_set.get_or_create(
                                booking_type=pattern.booking_type,
                                start=start_slot,
                                end=end_slot,
                                user=self.user))
                        if created:
                            count += 1
                    except ValidationError:
                        pass
                    cache_start_datetime = end_slot
        return count,
Beispiel #13
0
def add_business_days(days, from_datetime=datetime.now()):
    """Increment the passed from_date by the passed number of business days
    (excluding weekends and holidays)"""
    try:
        from_datetime.date()
    except AttributeError:
        from_datetime = datetime.combine(from_datetime, datetime.min.time())

    tx_holidays = holidays.US(state='TX')

    while days > 0:
        from_datetime += timedelta(days=1)
        if from_datetime.weekday() >= 5 or from_datetime.date() in tx_holidays:
            continue
        days -= 1
    return from_datetime
Beispiel #14
0
    def calculate_price(self):
        dog_feeding_time_object = DogFeedingTime.objects.filter(dog=self.dog)
        service_delta = (localtime(self.service_end_time).date() -
                         localtime(self.service_start_time).date())
        meal_weight = self.service_meal_weight
        meal_price_per_gram = self.service_meal_type.meal_price_per_gram
        all_date_within_interval = [
            localtime(self.service_start_time).date() + timedelta(days=i)
            for i in range(service_delta.days + 1)
        ]
        meal_per_service = 0
        for date in all_date_within_interval:
            for feedingtime in dog_feeding_time_object:
                date_feeding = datetime.combine(date, feedingtime.time)
                if (localtime(self.service_start_time) <
                        make_aware(date_feeding) < localtime(
                            self.service_end_time)):
                    meal_per_service += 1

        total_meal_price = meal_per_service * meal_price_per_gram * meal_weight / 100
        days_for_deposit = len(all_date_within_interval)

        total_price = (self.additional_service.deposit_price *
                       days_for_deposit) + total_meal_price

        host_service_price = [
            self.additional_service.price_dog_walk,
            self.additional_service.price_get_dog,
            self.additional_service.price_deliver_dog,
            self.additional_service.price_bath_dog,
        ]

        enable_service = [
            self.is_dog_walk,
            self.is_get_dog,
            self.is_delivery_dog,
            self.is_bath_dog,
        ]
        print("enable_service")
        print(enable_service)
        for i in range(len(enable_service)):
            if enable_service[i]:
                total_price += host_service_price[i]
        return total_price
Beispiel #15
0
    def get_context_data(self, **kwargs):
        context = super(ConsolaAgenteView, self).get_context_data(**kwargs)
        campanas_preview_activas = []
        usuario_agente = self.request.user
        agente_profile = usuario_agente.get_agente_profile()
        kamailio_service = KamailioService()
        sip_usuario = kamailio_service.generar_sip_user(
            agente_profile.sip_extension)
        sip_password = kamailio_service.generar_sip_password(sip_usuario)
        video_domain = ''
        if 'WEBPHONE_VIDEO_DOMAIN' in settings.CONSTANCE_CONFIG:
            video_domain = config_constance.WEBPHONE_VIDEO_DOMAIN
        fechas_agendas = AgendaContacto.objects.proximas(
            agente_profile).values_list('fecha', 'hora')
        fechas_agendas = [
            make_aware(datetime.combine(x[0], x[1])).isoformat()
            for x in fechas_agendas
        ]

        hoy = fecha_local(now())
        registros = LlamadaLog.objects.obtener_llamadas_finalizadas_del_dia(
            agente_profile.id, hoy)
        campanas_preview_activas = \
            agente_profile.has_campanas_preview_activas_miembro()
        context['pausas'] = Pausa.objects.activas
        context['registros'] = registros
        context['tipos_salientes'] = LlamadaLog.TIPOS_LLAMADAS_SALIENTES
        context['campanas_preview_activas'] = campanas_preview_activas
        context['agente_profile'] = agente_profile
        context['sip_usuario'] = sip_usuario
        context['sip_password'] = sip_password
        context['agentes'] = AgenteProfile.objects.obtener_activos().exclude(
            id=agente_profile.id)
        context['max_session_age'] = settings.SESSION_COOKIE_AGE
        context['video_domain'] = video_domain
        context['fechas_agendas_json'] = json.dumps(fechas_agendas)
        context['listas_rapidas'] = ContactoListaRapida.objects.all()

        return context
Beispiel #16
0
def manual_attendance(request):
    if request.method == 'GET':
        users = Device_user.objects.all()

        context = {

            'users': users
        }
        return redirect(request, 'manual-attendance', context)

    if request.POST:
        manual_entry = ApprovalTable()
        entry_date = datetime.strptime(request.POST.get("date"), '%Y/%m/%d').date()
        print(entry_date)
        entry_time = datetime.strptime(request.POST.get("time"), '%H:%M:%S').time()
        combined = datetime.combine(entry_date, entry_time)
        combined = make_aware(combined)
        manual_entry.datetime = combined
        manual_entry.user_id = Device_user.objects.get(user_id=int(request.POST.get('user_id')))
        manual_entry.reason = request.POST.get('reason')

        manual_entry.save()

    return redirect('/')
Beispiel #17
0
 def set_aware_appointment_datetime_utc(self, user_timezone):
     nieve_dt = datetime.combine(self.appointment_date, self.appointment_time)
     appointment_datetime_utc = make_aware(nieve_dt, timezone=pytz.timezone(user_timezone))
     self.appointment_datetime_utc = appointment_datetime_utc
Beispiel #18
0
 def to_datetime(self):
     return datetime.combine(self.chrono_date.date, self.chrono_time.time)
Beispiel #19
0
    def delete(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.client != self.request.user and \
                (instance.professional != self.request.user and instance.status != PENDING):
            return Response(status=status.HTTP_403_FORBIDDEN)

        if self.request.user.profile.type == PROFESSIONAL:
            if instance.status == PENDING:
                new_status = PENDING
            else:
                new_status = REJECT
        else:
            new_status = CANCEL

        services_datetime = datetime.combine(
            instance.date, instance.time).replace(tzinfo=None)

        if instance.status == ACCEPT and new_status == REJECT:
            if services_datetime < now().replace(tzinfo=None):
                return Response(
                    {
                        'error':
                        _('Services can\'t be cancel. Service date has passed.'
                          )
                    },
                    status=status.HTTP_400_BAD_REQUEST)
            else:
                instance.status = new_status

        elif instance.status == ACCEPT and new_status == CANCEL:
            cancel_amount = instance.calc_cancelability_cost()
            if cancel_amount > 0:
                try:
                    services = instance.services.all()
                    services_message = ''
                    for service in services:
                        services_message += str(service.name) + ', '

                    description = _(
                        'Service cancel. Order id: %(id)s. Services: %(services)s'
                    ) % {
                        'id': instance.id,
                        'services': services_message
                    }
                    instance.charge(amount=cancel_amount,
                                    description=description)
                except Exception as e:
                    return Response({'non_field_errors': str(e)},
                                    status=status.HTTP_400_BAD_REQUEST)

            instance.status = new_status

        elif instance.status in [COMPLETE, REJECT, CANCEL]:
            return Response(
                {
                    'error':
                    _('Services can\'t be cancel. Service status is %(status)s.'
                      ) % {
                          'status': instance.status
                      }
                },
                status=status.HTTP_400_BAD_REQUEST)

        else:  # status == PENDING
            if self.request.user.profile.type == PROFESSIONAL:
                HireServiceRefuse.objects.create(user=self.request.user,
                                                 service=instance)
            instance.status = new_status
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)