Ejemplo n.º 1
0
 def get_study_day(self, time):
     day_service = DayService(user=self.__user)
     day = day_service.get_date_at(time)
     initialized_day = day_service.get_date_at(
         self.__configuration.service_initialized_date)
     difference = day - initialized_day
     return difference.days
Ejemplo n.º 2
0
def initialize_and_update(username):
    configuration = Configuration.objects.get(user__username = username)
    day_service = DayService(user=configuration.user)
    walking_suggestion_service = WalkingSuggestionService(configuration=configuration)
    
    date_joined = day_service.get_date_at(configuration.user.date_joined)
    today = day_service.get_current_date()
    days_to_go_back = (today - date_joined).days
    date_range = [today - timedelta(days=offset+1) for offset in range(days_to_go_back)]

    while len(date_range):
        initialize_date = date_range.pop()
        try:
            walking_suggestion_service.get_initialization_days(initialize_date)
            break
        except WalkingSuggestionService.UnableToInitialize:
            pass
    
    walking_suggestion_service.initialize(initialize_date)
    NightlyUpdate.objects.filter(user = configuration.user).delete()
    
    while len(date_range):
        update_date = date_range.pop()
        walking_suggestion_service.update(update_date)
        NightlyUpdate.objects.create(
            user = configuration.user,
            day = update_date,
            updated = True
        )
Ejemplo n.º 3
0
 def get_study_start_date(self):
     if self.user and self.user.date_joined:
         study_start_datetime = self.user.date_joined
     else:
         study_start_datetime = self.get_fitbit_start_datetime()
     if study_start_datetime:
         day_service = DayService(user=self.user)
         return day_service.get_date_at(study_start_datetime)
     else:
         return None
Ejemplo n.º 4
0
def export_firsts_csv(users, directory='./', filename='firsts_exports.csv'):
    headers = [[
        'HeartSteps ID', 'Enrolled Date', 'Baseline Complete Date',
        'First Anti-Sedentary Decision Date',
        'First Anti-Sedentary Decision Service Request Date',
        'First Anti-Sedentary Real-Time Sedentary Treated Decision Date'
    ]]
    rows = []
    for first in Configuration.objects.filter(user__in=users).get_firsts():
        day_service = DayService(username=first['username'])
        enroll_date = day_service.get_date_at(
            first['date_joined']) if first['date_joined'] else None
        baseline_complete_date = day_service.get_date_at(
            first['baseline_complete_date']
        ) if first['baseline_complete_date'] else None
        first_decision_date = day_service.get_date_at(
            first['first_decision'].time) if first['first_decision'] else None
        first_decision_service_request_date = day_service.get_date_at(
            first['first_decision_service_request'].request_time
        ) if first['first_decision_service_request'] else None
        first_real_time_sedentary_treated_decision_date = day_service.get_date_at(
            first['first_real_time_sedentary_treated_decision'].time
        ) if first['first_real_time_sedentary_treated_decision'] else None
        rows.append([
            first['username'],
            enroll_date.strftime('%Y-%m-%d') if enroll_date else '',
            baseline_complete_date.strftime('%Y-%m-%d')
            if baseline_complete_date else '',
            first_decision_date.strftime('%Y-%m-%d')
            if first_decision_date else '',
            first_decision_service_request_date.strftime('%Y-%m-%d')
            if first_decision_service_request_date else '',
            first_real_time_sedentary_treated_decision_date.strftime(
                '%Y-%m-%d')
            if first_real_time_sedentary_treated_decision_date else ''
        ])

    _file = open(os.path.join(directory, filename), 'w')
    writer = csv.writer(_file)
    writer.writerows(headers + rows)
    _file.close()
Ejemplo n.º 5
0
 def get_datetime_on(self, date):
     service = DayService(user = self.user)
     tz = service.get_timezone_at(date)
     local_date = service.get_date_at(date)
     dt = datetime(
         local_date.year,
         local_date.month,
         local_date.day,
         self.hour,
         self.minute
     )
     return tz.localize(dt)
Ejemplo n.º 6
0
 def get_start_of_day(self, day=None):
     if day:
         service = DayService(user=self.user)
         day = service.get_date_at(day)
     else:
         day = self.current_datetime
     return datetime(year=day.year,
                     month=day.month,
                     day=day.day,
                     hour=self.day_start_hour,
                     minute=self.day_start_minute,
                     tzinfo=self.timezone)
Ejemplo n.º 7
0
    def decide(self, decision):
        if not self.is_initialized():
            raise self.NotInitialized()

        pooling = False
        try:
            pooling_configuration = PoolingServiceConfiguration.objects.get(
                user=self.__configuration.user)
            pooling = pooling_configuration.use_pooling
        except PoolingServiceConfiguration.DoesNotExist:
            pass

        day_service = DayService(user=decision.user)
        date = day_service.get_date_at(decision.time)

        response = self.make_request(
            'decision',
            data={
                'date':
                date.strftime('%Y-%m-%d'),
                'studyDay':
                self.get_study_day(decision.time),
                'decisionTime':
                self.categorize_suggestion_time(decision),
                'availability':
                decision.available,
                'priorAnti':
                self.anti_sedentary_treated_since_previous_decision(decision),
                'lastActivity':
                self.previous_decision_was_received(decision),
                'location':
                self.get_location_type(decision),
                'pooling':
                pooling,
                'watch':
                self.has_watch_app_step_count(decision)
            })
        decision.treated = response['send']
        decision.treatment_probability = response['probability']
        decision.save()
Ejemplo n.º 8
0
def export_morning_messages(username,
                            filename=None,
                            directory=None,
                            start=None,
                            end=None):
    user = User.objects.get(username=username)
    if not directory:
        directory = './'
    if not filename:
        filename = '%s.morning_messages.csv' % (username)

    morning_message_query = MorningMessage.objects \
        .order_by('date') \
        .filter(
            user = user
        ) \
        .prefetch_decision() \
        .prefetch_message_template() \
        .prefetch_message() \
        .prefetch_timezone()
    if start:
        day_service = DayService(user=user)
        start_date = day_service.get_date_at(start)
        morning_message_query = morning_message_query.filter(
            date__gte=start_date)
    if end:
        day_service = DayService(user=user)
        end_date = day_service.get_date_at(end)
        morning_message_query = morning_message_query.filter(
            date__lte=end_date)

    morning_messages = morning_message_query.all()

    rows = []
    headers = [
        'Date', 'Time Sent', 'Time Received', 'Time Opened', 'Time Completed',
        'Notification', 'Morning Message ID', 'Morning Message',
        'Anchor Message', 'Gain Frame', 'Loss Frame', 'Active Frame',
        'Sedentary Frame'
    ]
    rows.append(headers)

    morning_messages_by_date = {}
    for morning_message in morning_messages:
        morning_messages_by_date[morning_message.date] = morning_message

    if not start:
        start_date = morning_messages[0].date
    if not end:
        end_date = morning_messages[len(morning_messages) - 1].date

    date_diff = end_date - start_date
    every_day = [
        start_date + timedelta(days=offset) for offset in range(date_diff.days)
    ]
    for _date in every_day:
        if _date in morning_messages_by_date:
            morning_message = morning_messages_by_date[_date]
            time_sent = None
            time_received = None
            time_opened = None
            time_completed = None
            if morning_message.message:
                _tz = morning_message.timezone
                if morning_message.message.sent:
                    time_sent = morning_message.message.sent.astimezone(
                        _tz).strftime('%Y-%m-%d %H:%M:%s')
                if morning_message.message.received:
                    time_received = morning_message.message.received.astimezone(
                        _tz).strftime('%Y-%m-%d %H:%M:%s')
                if morning_message.message.opened:
                    time_opened = morning_message.message.opened.astimezone(
                        _tz).strftime('%Y-%m-%d %H:%M:%s')
                if morning_message.message.engaged:
                    time_completed = morning_message.message.engaged.astimezone(
                        _tz).strftime('%Y-%m-%d %H:%M:%s')
            morning_message_template_id = None
            if morning_message.message_template:
                morning_message_template_id = morning_message.message_template.id
            rows.append([
                morning_message.date.strftime('%Y-%m-%d'), time_sent,
                time_received, time_opened, time_completed,
                morning_message.notification, morning_message_template_id,
                morning_message.text, morning_message.anchor,
                morning_message.is_gain_framed, morning_message.is_loss_framed,
                morning_message.is_active_framed,
                morning_message.is_sedentary_framed
            ])
        else:
            rows.append([_date.strftime('%Y-%m-%d')] +
                        [None for i in range(len(headers) - 1)])

    _file = open(path.join(directory, filename), 'w')
    writer = csv.writer(_file)
    writer.writerows(rows)
    _file.close()
Ejemplo n.º 9
0
def export_morning_message_survey(username,
                                  filename=None,
                                  directory=None,
                                  start=None,
                                  end=None):
    user = User.objects.get(username=username)
    if not directory:
        directory = './'
    if not filename:
        filename = '%s.morning-survey.csv' % (username)

    morning_message_query = MorningMessage.objects \
        .order_by('date') \
        .filter(
            user = user
        ) \
        .prefetch_decision() \
        .prefetch_message() \
        .prefetch_survey() \
        .prefetch_timezone()
    if start:
        day_service = DayService(user=user)
        start_date = day_service.get_date_at(start)
        morning_message_query = morning_message_query.filter(
            date__gte=start_date)
    if end:
        day_service = DayService(user=user)
        end_date = day_service.get_date_at(end)
        morning_message_query = morning_message_query.filter(
            date__lte=end_date)
    morning_messages = morning_message_query.all()

    question_names = []
    serialized_morning_messages_by_date = {}
    for morning_message in morning_messages:
        time_sent = None
        time_received = None
        time_opened = None
        time_completed = None
        if morning_message.message:
            _tz = morning_message.timezone
            if morning_message.message.sent:
                time_sent = morning_message.message.sent.astimezone(
                    _tz).strftime('%Y-%m-%d %H:%M:%s')
            if morning_message.message.received:
                time_received = morning_message.message.received.astimezone(
                    _tz).strftime('%Y-%m-%d %H:%M:%s')
            if morning_message.message.opened:
                time_opened = morning_message.message.opened.astimezone(
                    _tz).strftime('%Y-%m-%d %H:%M:%s')
            if morning_message.message.engaged:
                time_completed = morning_message.message.engaged.astimezone(
                    _tz).strftime('%Y-%m-%d %H:%M:%s')
        _mm_serialized = {
            'time_sent': time_sent,
            'time_received': time_received,
            'time_opened': time_opened,
            'time_completed': time_completed
        }
        if morning_message.survey and morning_message.survey._questions:
            for question in morning_message.survey._questions:
                if question.name not in question_names:
                    question_names.append(question.name)
                if hasattr(
                        morning_message.survey, '_answers'
                ) and question.id in morning_message.survey._answers:
                    answer = morning_message.survey._answers[question.id]
                    _mm_serialized[question.name] = answer.value
            _mm_serialized['mood'] = morning_message.survey.selected_word
        serialized_morning_messages_by_date[
            morning_message.date] = _mm_serialized

    sorted_question_names = sorted(question_names)

    rows = []
    headers = [
        'Date',
        'Time Sent',
        'Time Received',
        'Time Opened',
        'Time Completed',
    ] + [_name.title() for _name in sorted_question_names] + ['Mood']
    rows.append(headers)

    date_diff = end_date - start_date
    for _date in [
            start_date + timedelta(days=offset)
            for offset in range(date_diff.days)
    ]:
        if _date in serialized_morning_messages_by_date:
            _mm = serialized_morning_messages_by_date[_date]
            row = [
                _date.strftime('%Y-%m-%d'), _mm['time_sent'],
                _mm['time_received'], _mm['time_opened'], _mm['time_completed']
            ]
            for name in sorted_question_names:
                if name in _mm:
                    row.append(_mm[name])
                else:
                    row.append(None)
            if 'mood' in _mm:
                row.append(_mm['mood'])
            else:
                row.append(None)
            rows.append(row)
        else:
            rows.append([_date.strftime('%Y-%m-%d')] +
                        [None for i in range(len(headers) - 1)])

    _file = open(path.join(directory, filename), 'w')
    writer = csv.writer(_file)
    writer.writerows(rows)
    _file.close()