Beispiel #1
0
    def prepare_evening_context(cls, profile):
        _lists = PersonalTodoList.objects.filter(
            user=profile).order_by('priority')
        users_today = user_time_now(profile.utc_offset).date()
        urgent_list, important_list, extra_list = PersonalListExtractorMixin.extract_personal_lists(
            _lists, users_today)

        profile_time = user_time_now(profile.utc_offset)
        finished, not_finished = HabitAction.get_habits_today(
            profile_time.date(), profile)

        base_url = "https://{0}".format(settings.MY_HOSTNAME)
        journal = Journal.objects.get(user=profile)
        journal_messages = cls.journal_messages(journal, profile_time)
        context = {
            'name': profile.name or 'friend',
            'journal_link': '{}{}'.format(base_url, '/journal/'),
            'journal_messages': journal_messages,
            'journal_messages_count': len(journal_messages),
            'important': important_list,
            'urgent': urgent_list,
            'finished_habits': finished,
            'not_finished_habits': not_finished,
            'finished_habits_count': len(finished),
            'total_habits_count': len(finished) + len(not_finished),
            'todos_link': '{}{}'.format(base_url, '/master/todo/'),
            'habits_link': '{}{}'.format(base_url, '/habits/'),
            'plan_link': '{}{}'.format(base_url, '/master/todo#plan'),
        }
        return context
Beispiel #2
0
 def get_profile_today_tasks(cls, profile):
     profile_today = user_time_now(profile.utc_offset).date()
     today_datetime = datetime.datetime.combine(profile_today,
                                                datetime.time())
     return cls.objects.filter(user=profile,
                               due_date=today_datetime,
                               completed=False)
Beispiel #3
0
 def get_today_list(cls, profile):
     DAY = "%A"
     users_today = user_time_now(profile.utc_offset)
     day_name = users_today.strftime(DAY)
     return cls.objects.filter(user=profile,
                               priority=cls.DAY_LIST_PRIORITY,
                               title=day_name).first()
Beispiel #4
0
 def handle(self, *args, **options):
     for profile in Profile.objects.all():
         if profile.is_plan_valid():
             profile_time = user_time_now(profile.utc_offset)
             if profile_time.hour == 0:
                 for project in profile.projects.all():
                     self.store_project_tasks(profile, project)
                 self.store_personal_tasks(profile)
Beispiel #5
0
    def create_week_actions(self,
                            profile_utc_offset=None,
                            _week_start=None,
                            past_action_default=None):
        """
        :param profile_utc_offset: if there is _week_start and not past_action_default this is not necessary
        :param _week_start: when the week starts for the user
        :param past_action_default: Should it fill past days
        :return:
        """
        new_actions = list()
        action_map = {
            0: HabitActionStatus.YES,
            1: HabitActionStatus.HALF,
            2: HabitActionStatus.NO,
        }
        if not _week_start:
            week_start = calc_week_start(profile_utc_offset)
        else:
            week_start = _week_start

        today = None
        if past_action_default:
            today = user_time_now(profile_utc_offset).date()

        toggle = 0
        for i in self.schedule:
            if past_action_default:
                if week_start < today:
                    status_index = toggle % 3
                    h_action = HabitAction.objects.create(
                        habit=self,
                        action_date=week_start,
                        status=action_map[status_index])
                    toggle += 1
                elif week_start == today:
                    h_action = HabitAction.objects.create(
                        habit=self,
                        action_date=week_start,
                        status=HabitActionStatus.YES)
                else:
                    h_action = HabitAction.objects.create(
                        habit=self, action_date=week_start)
            else:
                if i == "1":
                    h_action = HabitAction.objects.create(
                        habit=self, action_date=week_start)
                else:
                    h_action = None

            week_start += datetime.timedelta(days=1)
            if h_action:
                new_actions.append(h_action)
        return new_actions
Beispiel #6
0
    def handle(self, *args, **options):
        days_back = -1
        if options.get('days'):
            days_back = int(options['days'])
        print("Calcing karma for {} days".format(days_back))

        for profile in Profile.objects.all():
            if profile.is_plan_valid():
                if days_back == -1:
                    profile_time = user_time_now(profile.utc_offset)
                    if self.is_midnight(profile_time):
                        calc_datetime = profile_time - datetime.timedelta(days=1)
                        print("Calcing karma for {} for {}".format(profile.id, calc_datetime.isoformat()))
                        self.calc_karma(profile, calc_datetime.date())
                else:
                    profile_today = user_time_now(profile.utc_offset)
                    for i in range(1, days_back):
                        calc_datetime = profile_today - datetime.timedelta(days=i)
                        print("Calcing karma for {} for {}".format(profile.id, calc_datetime.isoformat()))
                        self.calc_karma(profile, calc_datetime.date())
Beispiel #7
0
 def get(self, request, entry_type):
     print("we out here")
     if entry_type not in JournalEntry.JOURNAL_TYPES:
         return HttpResponse(status=401, content="Entry type invalid")
     profile = self.profile(request)
     user_journal = Journal.objects.get(user=profile)
     user_date = user_time_now(profile.utc_offset).date()
     the_entry = JournalEntry.create_from_template(entry_type,
                                                   user_journal.id,
                                                   user_date_now=user_date)
     self.update_daily_success('journals', todo=1)
     return redirect('journal-entry', entry_id=the_entry.id)
Beispiel #8
0
 def store_personal_tasks(self, profile):
     personal_tasks_worked = ProjectTodoItem.personal_tasks_worked_today(
         profile)
     profile_now = user_time_now(profile.utc_offset)
     profile_yesterday = (profile_now - datetime.timedelta(days=1)).date()
     for task in personal_tasks_worked:
         record = TrackWorkedDay(user=profile,
                                 task=task,
                                 track_date=profile_yesterday,
                                 minutes_worked=task.minutes_worked_today)
         record.save()
         task.minutes_worked_today = 0
         task.save()
Beispiel #9
0
 def is_plan_valid(self):
     users_today = user_time_now(self.utc_offset)
     if self.is_trial():
         if self.trial_end_time:
             return self.trial_end_time >= users_today.date()
         else:
             # to be investigated
             return True
     else:
         if not self.plan_end_time:
             return True
         else:
             return self.plan_end_time >= users_today.date()
Beispiel #10
0
 def iterate_profiles_and_sync_planners(cls):
     for profile in Profile.objects.all():
         email = profile.account.user.email
         try:
             profile_time = user_time_now(profile.utc_offset)
             if profile_time.hour == 0:
                 logger.info("It is midnight now for {}".format(email))
                 synced_tasks = PersonalTodoList.sync_week_planner_today(
                     profile)
                 logger.info("Synced {} tasks for {}".format(
                     synced_tasks, email))
         except Exception:
             logger.exception(
                 "Problem in week planner sync for {}".format(email))
             logger.exception(traceback.format_exc())
Beispiel #11
0
 def iterate_profiles_and_gen_stuff(cls):
     for profile in Profile.objects.all():
         email = profile.account.user.email
         if not profile.is_plan_valid():
             logger.info("Skipping profile {}".format(email))
             continue
         try:
             profile_time = user_time_now(profile.utc_offset)
             if profile_time.hour == 0:
                 logger.info("It is midnight now for {}".format(email))
                 cls.create_journals(profile, profile_time)
                 if profile_time.isoweekday() == 1:
                     cls.create_habit_actions(profile)
         except Exception:
             logger.exception(
                 "Problem in midnight cron for {}".format(email))
             logger.exception(traceback.format_exc())
Beispiel #12
0
def calc_list_date(profile_utc_offset, list_name):
    DAY_MAP = {
        "Monday": 1,
        "Tuesday": 2,
        "Wednesday": 3,
        "Thursday": 4,
        "Friday": 5,
        "Saturday": 6,
        "Sunday": 7
    }
    users_today = user_time_now(profile_utc_offset).date()
    today_weekday = users_today.isoweekday()

    day_list_weekday = DAY_MAP[list_name]
    list_offset = day_list_weekday - today_weekday
    list_date = users_today + datetime.timedelta(days=list_offset)
    return list_date
Beispiel #13
0
def get_success_context(request):
    empty_success = {
        'valid': False,
        'total_score': 0,
        'rev_total_score': 100,
        'journals': {
            'score': 0,
            'rev_score': 100,
            'todo': 0,
            'done': 0
        },
        'habits': {
            'score': 0,
            'rev_score': 100,
            'todo': 0,
            'done': 0
        },
        'work': {
            'score': 0,
            'rev_score': 100,
            'todo': 0,
            'done': 0
        },
    }
    if 'success_data' in request.session:
        if not request.session['success_data']['valid']:
            request.session['success_data'] = empty_success
            context = empty_success
        else:
            profile = request.user.account.profile
            profile_today = user_time_now(
                profile.utc_offset).date().isoformat()
            if request.session['success_data']['date'] != profile_today:
                request.session['success_data'] = empty_success
                context = empty_success
            else:
                context = request.session['success_data']
    else:
        request.session['success_data'] = empty_success
        context = empty_success
    return context
Beispiel #14
0
 def handle(self, *args, **options):
     for profile in Profile.objects.all():
         try:
             user_now = user_time_now(profile.utc_offset)
             email = profile.account.user.email
             onboarding = OnboardEvents.objects.filter(user=profile).first()
             if not onboarding:
                 onboarding = OnboardEvents.objects.create(user=profile)
                 profile.trial_end_time = datetime.datetime.utcnow().date() + datetime.timedelta(days=20)
                 profile.save()
                 logger.info("Creating onboarding object for {} and extending trial to {}".format(email, profile.trial_end_time.isoformat()))
             if onboarding.onboard_canceled:
                 if not onboarding.sales_canceled and profile.is_trial():
                     OnboardSender.send_sales(profile, onboarding, user_now)
             elif onboarding.onboard_finished:
                 if profile.is_trial():
                     OnboardSender.send_sales(profile, onboarding, user_now)
             else:
                 OnboardSender.onboard_user(profile, onboarding, user_now)
         except Exception as e:
             print("error onboarding user ", profile.account.user.email)
             print(e)
Beispiel #15
0
    def do(self):
        logger.info("Running all reminders cron")
        for profile in Profile.objects.all():
            try:
                logger.info("Parsting user {}".format(
                    profile.account.user.email))
                if not profile.is_plan_valid():
                    logger.info("Profile plan has expired, no reminders")
                    continue
                email = profile.account.user.email
                if profile.account.user.is_staff:
                    logger.info("Skipping admin {}".format(email))
                    continue
                profile_time = user_time_now(profile.utc_offset)
                morning_reminder = profile.get_morning_reminder()
                if morning_reminder and self.it_is_time(
                        profile_time, morning_reminder):
                    self.send_morning_email(profile, email)
                    logger.info("Morning email to {}".format(email))

                midday_reminder = profile.get_midday_reminder()
                if midday_reminder and self.it_is_time(profile_time,
                                                       midday_reminder):
                    self.send_midday_email(profile, email)
                    logger.info("Midday email to {}".format(email))

                evening_reminder = profile.get_evening_reminder()
                if evening_reminder and self.it_is_time(
                        profile_time, evening_reminder):
                    self.send_evening_email(profile, email)
                    logger.info("Evening email to {}".format(email))

            except Exception:
                logger.exception("Error for {}".format(
                    profile.account.user.email))
                logger.exception(traceback.format_exc())
Beispiel #16
0
    def prepare_morning_context(cls, profile):
        _lists = PersonalTodoList.objects.filter(
            user=profile).order_by('priority')
        users_today = user_time_now(profile.utc_offset).date()
        urgent_list, important_list, extra_list = PersonalListExtractorMixin.extract_personal_lists(
            _lists, users_today)
        user_habits = Habit.objects.filter(
            user=profile, status=HabitStatus.ACTIVE).order_by('id').all()
        base_url = "https://{0}".format(settings.MY_HOSTNAME)

        journal_message = "Get your mindset right for the day."
        context = {
            'name': profile.name or 'friend',
            'journal_link': '{}{}'.format(base_url, '/journal/'),
            'journal_message': journal_message,
            'important': important_list,
            'important_count': len(important_list.todo),
            'urgent': urgent_list,
            'urgent_count': len(urgent_list.todo),
            'habits': user_habits,
            'todos_link': '{}{}'.format(base_url, '/master/todo/'),
            'habits_link': '{}{}'.format(base_url, '/habits/'),
        }
        return context
Beispiel #17
0
    def calc_stats(h_actions, profile, light=False):
        sums = {}
        counters = {}
        today_date = user_time_now(profile.utc_offset).date()
        today_key = today_date.isoformat()
        if not len(h_actions):
            return Habit.empty_stats(light), 0, 0

        for action in h_actions:
            date_key = action.action_date.isoformat()
            if date_key not in counters:
                sums[date_key] = 0
                counters[date_key] = 0
            if action.status == HabitActionStatus.YES:
                sums[date_key] += 1
            elif action.status == HabitActionStatus.HALF:
                sums[date_key] += 0.5
            counters[date_key] += 1
        stats = OrderedDict()
        if light:
            days = ["M", "T", "W", "T", "F", "S", "S"]
            spacing_coef = 35
        else:
            days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
            spacing_coef = 80
        i = 0
        today_score = 0
        week_score_sum = 0
        week_score_count = 0
        sorted_keys = list(counters.keys())
        sorted_keys.sort()
        today = datetime.datetime.today().date()
        for key in sorted_keys:
            count = counters[key]
            score = sums[key] / count
            stats[key] = {
                "height": score * 100 + 10,
                "score_height": score * 100 + 50,
                "left": i * spacing_coef,
                "day": days[i],
                "score": int(score * 100),
                "iso_date": key
            }
            if key == today_key:
                today_score = score
                before_today = False
                stats[key]["today"] = True
            key_date = parse(key).date()
            if key_date <= today:
                week_score_sum += score
                week_score_count += 1

            i += 1
            if score < .2:
                color = "indianred"
            elif score <= .5:
                color = "orange"
            elif score <= .75:
                color = "lightgreen"
            else:
                color = "green"
            stats[key]["color"] = color
        if week_score_count == 0:
            week_score = 0
        else:
            week_score = week_score_sum / week_score_count
        return stats, today_score, week_score