Exemplo n.º 1
0
def set_default_user_plan(sender, instance, created, **kwargs):
    """
    Creates default plan for the new user but also extending an account for default grace period.
    """

    if created:
        default_plan = Plan.get_default_plan()
        if default_plan is not None:
            UserPlan.objects.create(user=instance, plan=default_plan, active=False, expire=None)
Exemplo n.º 2
0
def set_default_user_plan(sender, instance, created, **kwargs):
    if created:
        default_plan = Plan.get_default_plan()
        if default_plan is not None:
            UserPlan.objects.create(user=instance,
                                    plan=default_plan,
                                    active=True,
                                    expire=datetime.utcnow().replace(tzinfo=utc) +
                                           timedelta(days=getattr(settings, 'PLAN_DEFAULT_GRACE_PERIOD', 30)))
Exemplo n.º 3
0
def set_default_user_plan(sender, instance, created, **kwargs):
    """
    Creates default plan for the new user but also extending an account for default grace period.
    """

    if created:
        default_plan = Plan.get_default_plan()
        if default_plan is not None:
            UserPlan.objects.create(user=instance,
                                    plan=default_plan,
                                    active=False,
                                    expire=None)
Exemplo n.º 4
0
def prepare_adding_website_to_cluster(self):
    # create a push package
    package = create_push_package(os.path.join(settings.MEDIA_ROOT, 'test2'))
    # create and log in a user
    register_user_from_homepage()
    logged_in = c.login(username='******', password='******')
    profile = ClientProfile.objects.all()[0]
    # add an account_key because the test will not actually associate a push
    # package to this profile
    profile.account_key = "123"
    profile.save()
    plan = Plan(user=profile.user, type=PlanVariant.PRO, status='active')
    plan.save()
    # assert that he logged in
    self.assertTrue(logged_in)
    self.assertEqual(WebsiteIcon.objects.count(), 0)

    # get the URL first, to create the website cluster
    resp = c.get(reverse('websites'))
    self.assertEqual(resp.status_code, 200)
    return package
Exemplo n.º 5
0
 def tomorrow_plan(self):
     tomorrow = (datetime.datetime.now(tz=pytz.timezone(self.timezone)) +
                 datetime.timedelta(1)).date()
     try:
         id, user_id, plan_array, status_array, date = \
             execute_database_command('SELECT * FROM plans WHERE user_id=%s AND date=%s', (self.id, tomorrow))[0]
         plan_array = ast.literal_eval(
             plan_array.replace('{', '[').replace('}', ']'))
         status_array = ast.literal_eval(
             status_array.replace('{', '[').replace('}', ']'))
         return Plan(user_id, plan_array, status_array, date, id)
     except:
         return None
Exemplo n.º 6
0
def handle_report_plan(bot, update):
    user = User.get(update.user_id)
    plan = Plan.get(update.cmd_args['plan_id'])
    text = f'{status_icons[plan.status_array[0]]} {plan.plan_array[0]}'

    bot.send_message(
        update.user_id,
        text,
        keyboard=keyboards.get_plan_item_keyboard(
            user,
            plan.id,
            0,
            pending=plan.status_array[0] == CheckStatus.PENDING.value),
        update=update.update_current)
Exemplo n.º 7
0
def redeem(request):
    redeemed = False
    plan = None
    if request.method == "POST":
        form = RedeemForm(data=request.POST)
        if form.is_valid():
            #mark coupon as redeemed
            code = form.cleaned_data['code']
            coupon = Coupon.objects.get(string=code)
            coupon.redeemed = True
            coupon.user = request.user
            coupon.save()
            redeemed = True
            #create a new plan for this coupon
            end_at = datetime.now() + timedelta(days=365 *
                                                coupon.time_unit_count)
            if coupon.time_unit == 'monthly':
                end_at = datetime.now() + timedelta(days=30 *
                                                    coupon.time_unit_count)
            plan = Plan(user=request.user,
                        type=coupon.plan,
                        end_at=end_at,
                        status='active',
                        payed=False,
                        txn_id='Coupon')
            plan.save()
            redeemed = True
    else:
        form = RedeemForm()

    return render_to_response('coupons/redeem.html', {
        'form': form,
        'redeemed': redeemed,
        'plan': plan,
        'plans': PlanVariant,
    }, RequestContext(request))
Exemplo n.º 8
0
def handle_plan_item_change(bot, update):
    user = User.get(update.user_id)
    plan = Plan.get(update.cmd_args['plan_id'])
    cur_item_idx = update.cmd_args['item_idx']
    new_item_dx = ((cur_item_idx + 1) % len(plan.plan_array)) if update.cmd_args['to'] == 'next' \
        else ((cur_item_idx - 1) % len(plan.plan_array))
    text = f'{status_icons[plan.status_array[new_item_dx]]} {plan.plan_array[new_item_dx]}'

    bot.send_message(update.user_id,
                     text,
                     keyboard=keyboards.get_plan_item_keyboard(
                         user,
                         plan.id,
                         new_item_dx,
                         pending=plan.status_array[new_item_dx] ==
                         CheckStatus.PENDING.value),
                     update=update.update_current)
Exemplo n.º 9
0
 def _create_plan(self, **kwargs):
     opts = {
         'name': 'test-plan',
         'available': True,
         'visible': True,
         'created': datetime.now()
     }
     opts.update(kwargs)
     p = Plan(**opts)
     p.full_clean()
     p.save()
     return p
Exemplo n.º 10
0
def handle_finish_plan(bot, update):
    user = User.get(update.user_id)
    plan = Plan(update.user_id, preparing_plans[update.user_id]['plan_array'],
                preparing_plans[update.user_id]['status_array'],
                preparing_plans[update.user_id]['date']).save()

    today = datetime.datetime.now(tz=pytz.timezone(user.timezone)).date()
    if today == plan.date:
        plan_text = "*План на сегодня*\n\n" if user.language_code == 'ru' else '*Plan for today*\n\n'
    else:
        plan_text = "*План на завтра*\n\n" if user.language_code == 'ru' else '*Plan for tomorrow*\n\n'

    for num, item in enumerate(plan.plan_array, 1):
        plan_text += f'🔲 {item}\n'

    bot.send_message(update.user_id,
                     plan_text,
                     keyboard=keyboards.get_report_plan_keyboard(
                         user, plan_id=plan.id),
                     update=preparing_plans[update.user_id]['update_current'])

    del preparing_plans[update.user_id]
Exemplo n.º 11
0
def handle_plan_item_report(bot, update):
    user = User.get(update.user_id)
    plan = Plan.get(update.cmd_args['plan_id'])
    item_idx = update.cmd_args['item_idx']
    status = update.cmd_args['status']
    plan.status_array[item_idx] = status
    plan.save()

    if status == CheckStatus.SUCCESS.value:
        user.score += 1
    elif status == CheckStatus.FAIL.value:
        user.score -= 1
    user.save()

    if CheckStatus.PENDING.value in plan.status_array:
        text = f"{status_icons[status]} {plan.plan_array[item_idx]}\n\n"
        sign = '+' if status == CheckStatus.SUCCESS.value else '-'
        point = '1 очко' if user.language_code == 'ru' else '1 point'
        text += sign + point

        bot.send_message(update.user_id,
                         text,
                         keyboard=keyboards.get_plan_item_keyboard(
                             user,
                             plan.id,
                             item_idx,
                             pending=(status == CheckStatus.PENDING.value)),
                         update=update.update_current)
        return False

    else:
        handle_show_plan(bot, update)
        ru_text = 'Теперь можно и отдохнуть😊'
        en_text = 'Now you can relax😊'
        text = ru_text if user.language_code == 'ru' else en_text

        bot.send_message(update.user_id, text)
        return True
Exemplo n.º 12
0
def handle_show_plan(bot, update):
    user = User.get(update.user_id)
    if update.cmd_args:
        plan = Plan.get(update.cmd_args['plan_id'])
    else:
        plan = user.today_plan

    today = datetime.datetime.now(tz=pytz.timezone(user.timezone)).date()
    if today == plan.date:
        plan_text = "*План на сегодня*\n\n" if user.language_code == 'ru' else '*Plan for today*\n\n'
    else:
        plan_text = "*План на завтра*\n\n" if user.language_code == 'ru' else '*Plan for tomorrow*\n\n'

    for item, status in zip(plan.plan_array, plan.status_array):
        plan_text += f'{status_icons[status]} {item}\n'

    if CheckStatus.PENDING.value in plan.status_array:
        bot.send_message(update.user.user_id,
                         plan_text,
                         keyboard=keyboards.get_report_plan_keyboard(
                             user, plan.id),
                         update=update.update_current)
    else:
        bot.send_message(update.user.user_id, plan_text)
Exemplo n.º 13
0
def add_plan(request, access_token):
	result = login_auth(access_token)
	if result['err']['code'] != 0:
		return HttpResponse(json.dumps(result))	
	userid = result['data']['id']
	try:
		new_plan = Plan()
		user = FBUser.objects.get(fbid=userid)
		new_plan.holder = user
		new_plan.title = request.POST.get('title', "testtitle")
		new_plan.destination = request.POST.get('destination', "testdestination")
		new_plan.description = request.POST.get('description', "testdescription")
		new_plan.depart_time = request.POST.get('depart_time', datetime.today())
		new_plan.length = request.POST.get('length', 2)
		new_plan.limit = request.POST.get('limit', 2)
		visible_type = request.POST.get('visible_type', 1)
		new_plan.visible_type = int(visible_type)
		friend_list = request.POST.getlist('friendlist',[])
		new_plan.full_clean()
		new_plan.save()
		if new_plan.visible_type == 3:
			for friendid in friend_list:
				friend = FBUser.objects.get(fbid=friendid)
				private = PrivatePlan()
				private.accessible_user = friend
				private.accessible_plan = new_plan
				private.full_clean()
				private.save()
		result = format(0, 'create success')
		return HttpResponse(json.dumps(result))	
	except Exception as e:
   		result = format(400, str(e))
        return HttpResponse(json.dumps(result))	
Exemplo n.º 14
0
 def test_get_user_quota_expired_no_default(self):
     u = User.objects.get(username='******')
     u.userplan.expire = date.today() - timedelta(days=5)
     Plan.get_default_plan().delete()
     with self.assertRaises(ValidationError):
         get_user_quota(u)
Exemplo n.º 15
0
def add_plan(request, access_token):
    result = login_auth(access_token)
    if result['err']['code'] != 0:
        return HttpResponse(json.dumps(result))
    userid = result['data']['id']
    try:
        new_plan = Plan()
        user = FBUser.objects.get(fbid=userid)
        new_plan.holder = user
        new_plan.title = request.POST.get('title', "testtitle")
        new_plan.destination = request.POST.get('destination',
                                                "testdestination")
        new_plan.description = request.POST.get('description',
                                                "testdescription")
        new_plan.depart_time = request.POST.get('depart_time',
                                                datetime.today())
        new_plan.length = request.POST.get('length', 2)
        new_plan.limit = request.POST.get('limit', 2)
        visible_type = request.POST.get('visible_type', 1)
        new_plan.visible_type = int(visible_type)
        friend_list = request.POST.getlist('friendlist', [])
        new_plan.full_clean()
        new_plan.save()
        if new_plan.visible_type == 3:
            for friendid in friend_list:
                friend = FBUser.objects.get(fbid=friendid)
                private = PrivatePlan()
                private.accessible_user = friend
                private.accessible_plan = new_plan
                private.full_clean()
                private.save()
        result = format(0, 'create success')
        return HttpResponse(json.dumps(result))
    except Exception as e:
        result = format(400, str(e))
    return HttpResponse(json.dumps(result))
Exemplo n.º 16
0
def register_thank_you(request, profile_id=None):
    try:
        profile = ClientProfile.objects.get(id=profile_id)
        if profile.registration_step != 3:

            raise Http404("Wrong user.")
        profile.registration_step = 4
        profile.save()
    except:
        raise Http404(
            "Reached register_thank_you with no ClientProfile. profile_id=" +
            str(profile_id))
    if profile.has_push_package():
        return redirect('dashboard')
    if profile.status == 'active':
        return redirect('dashboard')
    #push package
    package_manager = PushPackageManager()
    package = package_manager.get_push_package(profile)
    if package:
        profile_image = ProfileImage.objects.get(profile=profile)
        package.generate_zip(
            profile.website_name,
            profile.website,
            profile_image.image128_2x.path,
            profile_image.image128.path,
            profile_image.image32_2x.path,
            profile_image.image32.path,
            profile_image.image16_2x.path,
            profile_image.image16.path,
        )
        profile.status = 'active'
        profile.account_key = package.identifier
        profile.website_push_id = package.website_push_id
        profile.save()
        package.used = True
        package.save()
    else:
        profile.status = 'pending'
        profile.save()
    #plan
    if profile.from_envato:
        plan = Plan.objects.create_fixed_plan(profile.user)
    else:
        plan = Plan(user=profile.user,
                    type=plans.TRIAL,
                    end_at=datetime.now() + timedelta(days=30),
                    status='active',
                    payed=False)
    plan.save()
    #send email to ADMINS
    email_manager = PlansEmailManager()
    email_manager.send_admin_new_plan(profile.user.email,
                                      profile.user.first_name, plan)
    url = profile.return_url
    if len(url):
        #redirect back to WP
        if package:
            if url.find('?') > 0:
                url += "&push_monkey_account_key=" + profile.account_key + "&push_monkey_registered=1"
            else:
                url += "?push_monkey_account_key=" + profile.account_key + "&push_monkey_registered=1"
        else:
            url += "&push_monkey_package_pending=1&push_monkey_registered=1"
        return HttpResponseRedirect(url)

    return render_to_response('clients/register-thank-you.html', {},
                              RequestContext(request))
Exemplo n.º 17
0
with open('plan_3.json', encoding="utf8") as f:
    plan_json = json.load(f)

for plan in plan_json:
    try:
        plan = Plan(person=Person.objects.get(pk=int(plan['person'])),
                    job=Job.objects.get(pk=int(plan['job'])),
                    creation_date=plan['creation_date'],
                    name=plan['name'],
                    number=plan['number'],
                    active=plan['active'],
                    md=plan['md'],
                    inc=plan['inc'],
                    azi=plan['azi'],
                    tvd=plan['tvd'],
                    north=plan['north'],
                    east=plan['east'],
                    vertical_section=plan['vertical_section'],
                    dogleg=plan['dogleg'],
                    build_rate=plan['build_rate'],
                    turn_rate=plan['turn_rate'],
                    calculated_tf=plan['calculated_tf'],
                    zero_vs=plan['zero_vs'],
                    step_out=plan['step_out'],
                    tie_in_depth=plan['tie_in_depth'])
        plan.save()
    except:
        print("bad plan")

with open('motors.json', encoding="utf8") as f:
    assets_json = json.load(f)