예제 #1
0
def url_to_subscription(subscription_url):
    """Create a subscription object from a url —if possible"""
    if not subscription_url.startswith('http://'):
        subscription_url = 'http://%s' % subscription_url
    feeds = feedfinder.feeds(subscription_url)
    if feeds:
        subscription = Subscription()
        subscription.feed_url = feeds[0]
        data = feedparser.parse(subscription.feed_url)
        links = data.feed.get('links', [])
        if links:
            hubs = [link for link in data.feed.links if link['rel']==u'hub']
            logging.info(hubs)
            if len(hubs) > 0:
                subscription.hub = hubs[0]['href']
            else:
                subscription.hub = ''
        subscription.feed_id = data.feed.get('id', 'No ID')
        subscription.title = data.feed.get('title', 'No title')
        subscription.url = data.feed.get('link', subscription_url)
        subscription.etag = data.get('etag', '')
        updated_tuple = data.feed.get('date_parsed', None)
        if updated_tuple:
            subscription.updated = datetime.datetime(*updated_tuple[:6])
        else:
            subscription.updated = datetime.datetime.today()

    else:
        subscription = None

    return subscription
예제 #2
0
class SubscriptionModelTest(TestCase):
    def setUp(self) -> None:
        self.obj = Subscription(
            name='Victor',
            cpf='11122233344',
            email='*****@*****.**',
            phone='(21) 2222-3333'
        )

        self.obj.save()

    def test_create(self):
        self.assertTrue(Subscription.objects.exists())

    def test_created_at(self):
        """Subscription must have an auto created_at attr."""
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_str(self):
        self.assertEqual("Victor", str(self.obj))

    def test_paid_default_to_false(self):
        """By default paid must be False."""
        self.assertEqual(False, self.obj.paid)

    def test_get_absolute_url(self):
        url = resolve_url('subscriptions:detail', self.obj.hashid)
        self.assertEqual(url, self.obj.get_absolute_url())
 def test_signal_subscription_due(self):
     with signal_handler(signals.subscription_due) as handler:
         sub = Subscription(state=State.ACTIVE, end=self.yearish)
         sub.renew()
         handler.assert_called_once_with(sender=sub,
                                         signal=signals.subscription_due)
     self.assertEqual(sub.state, State.RENEWING)
 def test_signal_autorenew_canceled(self):
     with signal_handler(signals.autorenew_canceled) as handler:
         sub = Subscription(state=State.ACTIVE, end=self.yearish)
         sub.cancel_autorenew()
         handler.assert_called_once_with(sender=sub,
                                         signal=signals.autorenew_canceled)
     self.assertEqual(sub.state, State.EXPIRING)
예제 #5
0
class SubscriptionTest(TestCase):

    def setUp(self):
        self.obj = Subscription(
            name="Rafael Vidal",
            cpf="80100011187",
            email="*****@*****.**",
            phone="47-91943004"
        )

    def test_create(self):
        'Subscription must have a name, cpf, e-mail, phone'
        self.obj.save()
        self.assertEqual(1, self.obj.pk)

    def test_has_created_at(self):
        'Subscription must have automatic created_at'
        self.obj.save()
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_unicode(self):
        self.assertEqual(u'Rafael Vidal', unicode(self.obj))

    def test_paid_default_value_is_False(self):
        'By default paid must be false'
        self.assertEqual(False, self.obj.paid)
예제 #6
0
class SubscriptionTest(TestCase):
    def setUp(self):
        self.obj = Subscription(
                name='Leonardo Rezende',
                cpf='12345678901',
                email='*****@*****.**',
                phone='(82) 123456789'
            )

    def test_create(self):
        '''
        Subscription must have name, cpf, email, phone
        '''
        self.obj.save()
        self.assertEqual(1, self.obj.id)

    def test_has_created_at(self):
        '''
        Subscription must have automatic created_at
        '''
        self.obj.save()
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_unicode(self):
        '''
        Unicode str must return the subscription.name
        '''
        self.assertEqual(u'Leonardo Rezende', unicode(self.obj))

    def test_paid_default_values_is_False(self):
        '''
        By default paid must be false
        '''
        self.assertEqual(False, self.obj.paid)
예제 #7
0
def create_profile(request):
    # Create user profile and subscription
    if request.method == 'POST':

        form_data = {
            'user': request.user,
            'full_name': request.POST['full_name'],
            'email': request.user.email,
            'phone_number': request.POST['phone_number'],
            'company_name': request.POST['company_name'],
            'company_street_address1': request.POST['company_street_address1'],
            'company_street_address2': request.POST['company_street_address2'],
            'company_city': request.POST['company_city'],
            'company_county': request.POST['company_county'],
            'company_postcode': request.POST['company_postcode'],
        }
        user_profile_form = UserProfileForm(form_data)
        if user_profile_form.is_valid():
            user_profile_form.save()
            # Create 14 day free Subscription
            end_date = date.today() + timedelta(days=14)
            create_subscription = Subscription(user=request.user,
                                               start_date=date.today(),
                                               end_date=end_date)
            create_subscription.save()
            messages.info(request, 'Profile created Successfully')

        return redirect(reverse('profile'))

    user_profile_form = UserProfileForm()
    template = 'profiles/create_profile.html'
    context = {
        'user_profile_form': user_profile_form,
    }
    return render(request, template, context)
예제 #8
0
class SubscriptionTest(TestCase):
    def setUp(self):
        self.obj = Subscription(
            name='Test Testing Name',
            cpf='12345678901',
            email='*****@*****.**',
            phone='12-123456789'
        )

    def test_create(self):
        'Subscription must have name, cpf, email, phone'
        self.obj.save()
        self.assertEqual(1, self.obj.pk)

    def test_has_created_at(self):
        'Subscription must have a automatic created_at field'
        self.obj.save()
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_unicode(self):
        'Verify subscriber name'
        self.assertEqual(u'Test Testing Name', unicode(self.obj))

    def test_paid_default_value_is_false(self):
        'By default paid must be False'
        self.assertEqual(False, self.obj.paid)
예제 #9
0
파일: test_models.py 프로젝트: rougeth/wttd
class SubscriptionTest(TestCase):
    def setUp(self):
        self.subscription = Subscription(
            name='Marco Rougeth',
            cpf='1234567890',
            email='*****@*****.**',
            phone='1234567890'
        )

    def test_create(self):
        ''' Subscription must have name, cpf, email and phone
        '''
        self.subscription.save()
        self.assertEqual(1, self.subscription.pk)

    def test_has_created_at(self):
        ''' Subscription must have automatic created_at
        '''
        self.subscription.save()
        self.assertIsInstance(self.subscription.created_at, datetime)

    def test_str(self):
        '''
        '''
        self.assertEqual('Marco Rougeth', str(self.subscription))
 def setUp(self):
     self.obj = Subscription(
         name="Marcio Ramos",
         cpf="36911563213",
         email="*****@*****.**",
         phone="15-996042331"
     )
     self.obj.save()
예제 #11
0
    def test_sets_lastSent_datetime_to_current_time_when_instance_is_new(self):
        subscription = Subscription(subscriber=self.user, feed_record=self.record)

        before = now()
        subscription.save()
        after = now()

        self.assert_(before <= subscription.last_sent <= after)
예제 #12
0
    def test_sets_lastSent_datetime_to_current_time_when_instance_is_new(self):
        subscription = Subscription(subscriber=self.user, feed_record=self.record)

        before = datetime.datetime.now()
        subscription.save()
        after = datetime.datetime.now()

        self.assert_(before <= subscription.last_sent <= after)
예제 #13
0
 def setUp(self):
     self.obj = Subscription(
         name="Guilherme Gouw",
         cpf="12345678901",
         email="*****@*****.**",
         phone="21-996186180",
     )
     self.obj.save()
예제 #14
0
    def set_subscription_plan(self, plan_id, subscription_id):
        from subscriptions.models import Subscription, SubscriptionPlan

        subscription_plan = SubscriptionPlan.objects.filter(
            plan_id=plan_id).get()
        subscription = Subscription(owner=self,
                                    subscription_id=subscription_id,
                                    plan=subscription_plan)
        subscription.save()
예제 #15
0
    def setUp(self) -> None:
        self.obj = Subscription(
            name='Victor',
            cpf='11122233344',
            email='*****@*****.**',
            phone='(21) 2222-3333'
        )

        self.obj.save()
예제 #16
0
 def test_signal_subscription_renewed(self):
     with signal_handler(signals.subscription_renewed) as handler:
         sub = Subscription(state=State.RENEWING, end=self.yearish)
         new_end = self.yearish + timedelta(days=365)
         sub.renewed(new_end, "NEWREF")
         handler.assert_called_once_with(sender=sub, signal=signals.subscription_renewed)
     self.assertEqual(sub.state, State.ACTIVE)
     self.assertEqual(sub.end, new_end)
     self.assertEqual(sub.reference, "NEWREF")
 def test_signal_renewal_failed(self):
     with signal_handler(signals.renewal_failed) as handler:
         sub = Subscription(state=State.RENEWING, end=self.yearish)
         sub.renewal_failed(description="DECLINED")
         handler.assert_called_once_with(sender=sub,
                                         signal=signals.renewal_failed)
     self.assertEqual(sub.state, State.SUSPENDED)
     log = StateLog.objects.for_(sub).get()
     self.assertEqual(log.description, "DECLINED")
     self.assertEqual(log.transition, "renewal_failed")
 def test_signal_subscription_ended(self):
     with signal_handler(signals.subscription_ended) as handler:
         sub = Subscription(state=State.SUSPENDED, end=self.yearish)
         sub.end_subscription(description="LetItGo")
         handler.assert_called_once_with(sender=sub,
                                         signal=signals.subscription_ended)
     self.assertEqual(sub.state, State.ENDED)
     log = StateLog.objects.for_(sub).get()
     self.assertEqual(log.description, "LetItGo")
     self.assertEqual(log.transition, "end_subscription")
 def test_signal_subscription_error(self):
     with signal_handler(signals.subscription_error) as handler:
         sub = Subscription(state=State.RENEWING, end=self.yearish)
         sub.state_unknown(description="WAT")
         handler.assert_called_once_with(sender=sub,
                                         signal=signals.subscription_error)
     self.assertEqual(sub.state, State.ERROR)
     log = StateLog.objects.for_(sub).get()
     self.assertEqual(log.description, "WAT")
     self.assertEqual(log.transition, "state_unknown")
예제 #20
0
def migrate(request, from_table, what_pk, to_table):
    print('Migrating ' + from_table + "/" + what_pk + " to " + to_table)
    if not request.user.is_superuser:
        return redirect("/admin")
    if request.user.is_superuser:
        if from_table == to_table:
            print('Promote into the same table??')
        else:
            if from_table == 'company':
                if to_table == 'subscription':
                    company = Company.objects.get(pk=what_pk)
                    Subscription(company=company,
                                 reference=company.reference,
                                 name=company.name).save()
                elif to_table == 'uncategorised':
                    print('Not yet implemented')
                else:
                    print('Unknown table: ' + to_table)
            elif from_table == 'subscription':
                if to_table == 'company':
                    print('Not yet implemented')
                elif to_table == 'uncategorised':
                    print('Not yet implemented')
                else:
                    print('Unknown table: ' + to_table)
            elif from_table == 'uncategorised':
                if to_table == 'company':
                    uncategorised = Uncategorised.objects.get(pk=what_pk)
                    Company(name=uncategorised.name,
                            reference=uncategorised.reference,
                            category=uncategorised.category).save()
                    uncategorised.delete()
                elif to_table == 'subscription':
                    print('Not yet implemented')
                else:
                    print('Unknown table: ' + to_table)
            elif from_table == 'transaction':
                if to_table == 'company':
                    transaction = Transaction.objects.get(pk=what_pk)
                    Company(reference=transaction.reference).save()
                elif to_table == 'subscription':
                    transaction = Transaction.objects.get(pk=what_pk)
                    company = Company.search_by_reference(
                        transaction.reference)
                    Subscription(company=company,
                                 reference=transaction.reference,
                                 name=company.name,
                                 monthly_price=-transaction.amount).save()
                else:
                    print('Unknown table: ' + to_table)
            else:
                print('Unknown table: ' + from_table)
    else:
        print('No superuser')
    return redirect(request.GET.get('next', '/analyse'))
예제 #21
0
파일: signals.py 프로젝트: kshutashvili/gnc
def subscribe_user(sender, instance, **kwargs):
    """
    this signal called twice:
    1. when User object created
    2. when User log in on the site (this call creating LogEntry instance
        and set changes to last_login field in User model)
    to prevent this used if statement
    """
    if kwargs['created']:
        user_subscription = Subscription(email=instance.email)
        user_subscription.save()
 def test_signal_subscription_renewed_from_active(self):
     with signal_handler(signals.subscription_renewed) as handler:
         sub = Subscription(state=State.ACTIVE, end=self.yearish)
         new_end = self.yearish + timedelta(days=365)
         sub.renewed(new_end, "NEWREF", description="AUTOSUB")
         handler.assert_called_once_with(
             sender=sub, signal=signals.subscription_renewed)
     self.assertEqual(sub.state, State.ACTIVE)
     self.assertEqual(sub.end, new_end)
     self.assertEqual(sub.reference, "NEWREF")
     log = StateLog.objects.for_(sub).get()
     self.assertEqual(log.description, "AUTOSUB")
     self.assertEqual(log.transition, "renewed")
예제 #23
0
 def setUp(self):
     self.obj = Subscription(
         name="Rafael Vidal",
         cpf="80100011187",
         email="*****@*****.**",
         phone="47-91943004"
     )
예제 #24
0
파일: views.py 프로젝트: directeur/socnode
def add_subscription(request):
    """
    This is complicated. (tm)
    A subscription can be:
    1) A user's service: The subscription has to be created if it doesn't exist
    before and the user will be its owner (only subscriber)
    2) A socnode feed: in this case, create the subscription only if it doesn't
    exist before and append the user to its subscribers.
    """
    host = 'http://%s' % request.get_host()
    if request.method == 'POST':
        surl = request.POST.get('surl', '')
        is_service = request.POST.get('is_service', '0')
        subscription_kind = 'service' if is_service=='1' else 'friend'
        subscription =  url_to_subscription(surl)
        if subscription:
            hub = subscription.hub
            subscription.is_service = True if is_service=='1' else False
            msg = '%s is on %s' % (surl, hub)
            # is there any similar subscription?
            similar = Subscription.all().filter('feed_url = ', subscription.feed_url)
            if similar and not subscription.is_service:
                subscription = similar[0]
                created = False
            else:
                created = True
            subscription.subscribers.append(request.user.key())
            subscription.save()
            post_subscribe.send(sender=Subscription, instance=subscription, 
                host=host, created=created)
        else:
            msg = '%s is not a valid feed url' % surl
        return HttpResponseRedirect('/subscriptions/?kind=%s' %
                subscription_kind)
예제 #25
0
파일: test_models.py 프로젝트: rougeth/wttd
 def setUp(self):
     self.subscription = Subscription(
         name='Marco Rougeth',
         cpf='1234567890',
         email='*****@*****.**',
         phone='1234567890'
     )
예제 #26
0
 def setUp(self):
     self.obj = Subscription(
         name='Test Testing Name',
         cpf='12345678901',
         email='*****@*****.**',
         phone='12-123456789'
     )
예제 #27
0
def delete(request, table, pk):
    if not request.user.is_superuser:
        return redirect("/admin")
    if request.user.is_superuser:
        if table == 'company':
            deleted, row_count = Company.objects.filter(pk=pk).delete()
            Company.save_to_fixture()
        elif table == 'subscription':
            deleted, row_count = Subscription.objects.filter(pk=pk).delete()
            Subscription.save_to_fixture()
        elif table == 'uncategorised':
            deleted, row_count = Uncategorised.objects.filter(pk=pk).delete()
            Uncategorised.save_to_fixture()
        else:
            print('Unknown table: ' + table)
    return redirect(request.GET.get('next', '/analyse'))
예제 #28
0
 def setUp(self):
     self.obj = Subscription(
             name='Leonardo Rezende',
             cpf='12345678901',
             email='*****@*****.**',
             phone='(82) 123456789'
         )
예제 #29
0
 def setUp(self):
     self.owner = User.objects.create_user("owner", "*****@*****.**", "testpw")
     owner_profile = Profile(user=self.owner)
     owner_profile.save()
     self.user = User.objects.create_user("test", "*****@*****.**", "testpw")
     self.user2 = User.objects.create_user("user2", "*****@*****.**", "user2")
     Profile(user=self.user).save()
     Profile(user=self.user2).save()
     
     self.marketplace = MarketPlace(name="greatsomething", title="Great Something", slug="great-something", 
                                    template_prefix="default", base_domain="greatsomething.com")
     self.marketplace.save()
     self.shop = Shop(marketplace=self.marketplace, admin=self.owner, name="test_shop")
     self.shop.save()
     Preference(shop=self.shop).save()
     self.shop.update()
     plan = SubscriptionPlan(plan_id=1,
                      marketplace=self.marketplace, 
                      trial_period=True, 
                      total_store_revenue=1000, 
                      concurrent_store_items=1000)
     plan.save()
     Subscription(owner=owner_profile, plan=plan).save()
     self.category = MarketCategory(marketplace=self.marketplace, name="Category1")
     self.category.save()
     self.subcategory = MarketSubCategory(marketplace=self.marketplace, parent=self.category, name="SubCategory1")
     self.subcategory.save()
     
     self.cart = Cart(shop=self.shop, bidder=self.user)
     self.cart.save()
     
     self.cart2 = Cart(shop=self.shop, bidder=self.user2)
     self.cart2.save()
예제 #30
0
    def setUp(self):
        from subscriptions.models import Subscription

        self.obj = Subscription(
            name='Italo Maia',
            cpf='12345678901',
            email='*****@*****.**',
            phone='2345678')
def makePayment(uid, amount, ogid, pay_date):
  intAmount = int(amount)
  user = fetchUser(uid)
  #oldGid = usergroupid(user)
  oldGid = ogid

  sub = Subscription(user=user, amount=intAmount)
  sub.oldGroupId = oldGid
  sub.delayed = intAmount == 0
  sub.paymaster = paymaster
  sub.paymentType = 'P'
  sub.date = pay_date
  sub.subsEnd = sub.date + timedelta(days=365)
  sub.save()
class SubscribeModelTest(TestCase):
    def setUp(self):
        self.obj = Subscription(
            name="Marcio Ramos",
            cpf="36911563213",
            email="*****@*****.**",
            phone="15-996042331"
        )
        self.obj.save()

    def test_create(self):
        self.assertTrue(Subscription.objects.exists())

    def test_created_at(self):
        """Subscription must have an auto created_at attr."""
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_str(self):
        self.assertEqual('Marcio Ramos', str(self.obj))
예제 #33
0
    def setUp(self):
        Subscriber.objects.all().delete()
        ContentFeedRecord.objects.all().delete()
        ContentFeedParameter.objects.all().delete()
        Subscription.objects.all().delete()

        user = self.user = Subscriber(); user.save()
        record = self.record = ContentFeedRecord(); record.save()

        sub = self.sub = Subscription(subscriber=user, feed_record=record); sub.save()
예제 #34
0
class SubscriptionModelTest(TestCase):
    def setUp(self):
        self.obj = Subscription(
            name="Guilherme Gouw",
            cpf="12345678901",
            email="*****@*****.**",
            phone="21-996186180",
        )
        self.obj.save()

    def test_create(self):
        self.assertTrue(Subscription.objects.exists())

    def test_created_at(self):
        """Subscription must have an auto created_at attr"""
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_str(self):
        self.assertEqual('Guilherme Gouw', str(self.obj))
예제 #35
0
파일: views.py 프로젝트: directeur/socnode
def cron_job(request):
    """
    fetch subscriptions that aren't connected to a hub.
    """
    nohub_subscriptions = Subscription.all().filter('hub = ', "")
    keys = [str(s.key()) for s in nohub_subscriptions]
    # now launch eftching tasks
    for key in keys:
        logging.info('task set to fetch subscription %s' % key)
        taskqueue.add(url='/subscriptions/fetch_feed/', params={'key': key})
    return HttpResponse('done')
예제 #36
0
파일: views.py 프로젝트: directeur/socnode
def list_subscriptions(request):
    kind = request.GET.get("kind", 'friend')
    his_subscriptions = Subscription.all().filter('subscribers = ',
            request.user.key())
    if kind == 'service':
        his_subscriptions.filter('is_service = ', True)
    elif kind == 'friend':
        his_subscriptions.filter('is_service = ', False)
    extra_context = {'kind': kind}
    return object_list(request, his_subscriptions, paginate_by=10,
            extra_context=extra_context)
예제 #37
0
class SubscriptionModel(TestCase):
    def setUp(self):
        self.obj = Subscription(name='Fabio Oliveira',
                                cpf='12345678901',
                                email='*****@*****.**',
                                phone='3333-2222')
        self.obj.save()

    def test_create(self):
        self.assertTrue(Subscription.objects.exists())

    def test_created_at(self):
        """Subscription must have an auto created_at attr..."""
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_str(self):
        self.assertEqual('Fabio Oliveira', str(self.obj))

    def test_paid_default_to_False(self):
        """By default paid must be False"""
        self.assertEqual(False, self.obj.paid)
예제 #38
0
class SubscriptionTest(TestCase):
    def setUp(self):
        self.obj = Subscription(name='Jeferson Calazans', cpf='60546831524',
            email='*****@*****.**', phone='21-86478151',)

    def test_create(self):
        'Subscription must have name, cpf, email, phone'
        self.obj.save()
        self.assertEqual(self.obj.id, 1)

    def test_has_created_at(self):
        'Subscription must have created_at'
        self.obj.save()
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_unicode(self):
        self.assertEqual(u'Jeferson Calazans', unicode(self.obj))

    def test_paid_default_value_is_False(self):
        'By default paid must be False'
        self.assertEqual(False, self.obj.paid)
예제 #39
0
def gift_redeem(request, context):
    with transaction.commit_on_success():
        save = transaction.savepoint()
        try:
            code = context["gift_code"]
            gift = GiftSubscription.objects.get(code=code, redeemed=None)
            gift.redeemed = datetime.now()
            gift.save()

            # Create coupon so customer gets free subscription
            coupon = stripe.Coupon.create(percent_off=100, duration="once")["id"]

            customer_form = context["customer_form"]
            customer = customer_form.save(commit=False).customer

            subscription = Subscription(customer=customer, plan=context["plan"])
            subscription.save(coupon=coupon)

            transaction.savepoint_commit(save)

            if not customer.user.is_active:
                send_verification_mail(request, customer.user, "signup_verify")
                info(request, _("A verification email has been sent with " "a link for activating your account."))
                return redirect(request.GET.get("next", "/"))
            else:
                info(request, _("Successfully signed up"))
                auth_login(request, customer.user)
                return login_redirect(request)
            data = {
                "plan": context["plan"],
                "giftee": context["gift_form"].cleaned_data["giftee"],
                "gifter": context["gift_form"].cleaned_data["gifter"],
            }

        except Exception as e:
            transaction.savepoint_rollback(save)
            error(request, e)

    return context
예제 #40
0
def create(request):
    form = SubscriptionForm(request.POST)

    if not form.is_valid():
        context = RequestContext(request, {'form': form})
        return render_to_response('subscriptions/new.html', context)

    s = Subscription()
    s.name = form.cleaned_data['name']
    s.cpf = form.cleaned_data['cpf']
    s.email = form.cleaned_data['email']
    s.phone = form.cleaned_data['phone']
    s.save()

    # notifica o cadastro
    send_subscription_email(s)
    return HttpResponseRedirect(reverse('subscriptions:success', args=[ s.pk ]))
예제 #41
0
    def setUp(self):
        # create store owner user and profile
        self.owner = User.objects.create_user("test-owner", "*****@*****.**", "test-owner")
        owner_profile = Profile(user=self.owner)
        owner_profile.save()

        # create a marketplace
        self.marketplace = MarketPlace(name="greatcoins", title="greatcoins", slug="greatcoins", 
                                       template_prefix="greatcoins", base_domain="greatcoins.com")
        self.marketplace.save()

        # create a shop
        self.shop = Shop(marketplace=self.marketplace, admin=self.owner, name="test_shop")
        self.shop.save()

        # create a Preference and SubscriptionPlan to shop
        Preference(shop=self.shop).save()
        self.shop.update()
        plan = SubscriptionPlan(plan_id=1,
                         marketplace=self.marketplace,
                         trial_period=True,
                         total_store_revenue=1000,
                         concurrent_store_items=1000)
        plan.save()
        Subscription(owner=owner_profile, plan=plan).save()

        # create marketplace categories and sub-categories
        self.category = MarketCategory(marketplace=self.marketplace, name="Category")
        self.category.save()
        self.subcategory = MarketSubCategory(marketplace=self.marketplace, parent=self.category, name="SubCategory")
        self.subcategory.save()

        # create a user, profile and shipping data
        self.user = User.objects.create_user("test-user", "*****@*****.**", "test-user")
        Profile(user=self.user).save()
        shippingdata = ShippingData(first_name='User',
                                    last_name='Buyer',
                                    street_address="Calle 54",
                                    city="La Plata",
                                    state="Buenos Aires",
                                    zip="1900",
                                    country="AR")
        shippingdata.save()

        # create a shopping cart
        self.cart = Cart(shop=self.shop, bidder=self.user)
        self.cart.shippingdata = shippingdata
        self.cart.save()
예제 #42
0
def employer_questions(request, employer_id):
  employer = get_object_or_404(Employer, pk=employer_id)
  questions_qs = Question.objects.filter(employer=employer).order_by('-created')
  questions = questions_qs
  qids = [x.id for x in questions]
  all_answers = Answer.objects.filter(question__in=qids).order_by('question')

  extract_uid = lambda x: x.user_id
  # TODO - see if this is going to be useful or not...
  all_user_ids = set(map(extract_uid, questions) + map(extract_uid, all_answers))
  all_users = dict((x.id, x) for x in User.objects.filter(id__in=all_user_ids))
  for item in itertools.chain(questions, all_answers):
    if not item.is_anonymous:
      item.user = all_users[item.user_id]
  questions_dict = dict((q.id, q) for q in questions)
  # aggregate all the answers by question_id.
  # all_answers is sorted by question, so this should return unique groupings by question_id.
  for qid, answers in groupby(all_answers, lambda x: x.question_id):
    # set the mapping question -> list of answers.
    questions_dict[int(qid)]._answers = list(answers)

  # hide all questions that are
  # -deleted
  # -has no answer.
  questions = [q for q in questions if not(q.deleted and not q.answers)]

  num_unanswered = Question.objects.get_unanswered(employer).count()
  num_subscribed = Subscription.objects.filter(
    type=SUBSCRIPTIONS.QNA,
    employer=employer,
    is_active=True).count()

  # already subscribed or not.
  is_subscribed = Subscription.is_user_subscribed_to_qna(request.user, employer)
  ctx = dict(
    employer=employer,
    # forms
    question_form=QuestionForm({'employer':employer}, auto_id=None),
    # data to be displayed
    questions=questions,
    # questions_paginator=questions_paginator,
    num_unanswered=num_unanswered,
    num_subscribed=num_subscribed,
    is_subscribed=is_subscribed,
  )
  return partial_html_response('main/employer_discussions.html', ctx, request)
예제 #43
0
파일: views.py 프로젝트: tmbach/41Inc
    def post(self, request, *args, **kwargs):
        # Import API key
        stripe.api_key = settings.STRIPE_CLIENT_SECRET

        # Get current site ID
        site = get_current_site(request)

        # Import site's API key
        stripe_account = SubscriptionSettings.objects.get(
            pk=site.id).stripe_user_id

        # Get token from request
        token = request.POST['token']

        # Get plan
        plans = {
            'month': settings.PLAN_ID_MONTHLY,
            'year': settings.PLAN_ID_YEARLY
        }

        plan = plans[request.POST['plan']]

        # Create Stripe customer
        customer = stripe.Customer.create(source=token,
                                          plan=plan,
                                          email=request.user.email,
                                          stripe_account=stripe_account)

        # Create new subscription
        Subscription(customer_id=customer.id,
                     user=request.user,
                     site=site,
                     active_until=timezone.make_aware(
                         datetime.datetime.fromtimestamp(
                             int(customer.subscriptions.data[0].
                                 current_period_end)))).save()

        return HttpResponse('Subscription created.')
예제 #44
0
def add(request):
    if request.method == 'POST':
        form = SubscribeForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']

            # search if email was not registered yet
            if Subscription.objects.filter(email=email):

                return render_to_response(
                    'subscriptions/index.html', {
                        'form': form,
                        'error_message': 'Email already registered',
                    })

            else:

                sub = Subscription()
                sub.email = email
                sub.originating_ip = request.META['REMOTE_ADDR']
                sub.save()

                # Send email confirming and providing user with links to unsubscribe.
                send_subscribe_email(sub)

                # Always return an HttpResponseRedirect after successfully dealing
                # with POST data. This prevents data from being posted twice if a
                # user hits the Back button.
                return HttpResponseRedirect(
                    reverse('subscriptions.views.index') + '?success=1')

    else:
        form = SubscribeForm()

    return render_to_response('subscriptions/index.html', {
        'form': form,
    })
예제 #45
0
 def test_subscription_defaults(self):
     sub = Subscription(end=self.yearish)
     self.assertEqual(sub.state, State.ACTIVE)
예제 #46
0
class SubscriptionTest(TestCase):
    def setUp(self):
        from subscriptions.models import Subscription

        self.obj = Subscription(
            name='Italo Maia',
            cpf='12345678901',
            email='*****@*****.**',
            phone='2345678')

    def test_create(self):
        self.obj.save()
        self.assertEqual(1, self.obj.id)

    def test_has_created_at(self):
        """
        Subscription must have automatic created_at
        """
        self.obj.save()
        self.assertIsInstance(self.obj.created_at, datetime)

    def test_cpf_unique(self):
        """CPF must be unique"""
        from subscriptions.models import Subscription

        self.obj.save()
        s = Subscription(
            name='Italo Maia',
            cpf='12345678901',
            email='*****@*****.**',
            phone='2345678')
        self.assertRaises(IntegrityError, s.save)

    def test_email_can_repeat(self):
        """Email is not unique anymore"""
        from subscriptions.models import Subscription

        self.obj.save()
        s = Subscription.objects.create(
            name='Italo Maia',
            cpf='12345678902',
            email='*****@*****.**')
        self.assertEqual(2, s.pk)

    def test_unicode(self):
        from subscriptions.models import Subscription

        self.assertEqual(u'Italo Maia', unicode(self.obj))

    def test_permalink(self):
        self.obj.save()
        self.assertIsInstance(self.obj.get_absolute_url(), basestring)

    def test_permalink_has_id(self):
        self.obj.save()
        self.assertIn(str(self.obj.pk), self.obj.get_absolute_url())

    def test_paid_default_value_is_false(self):
        self.assertEqual(False, self.obj.paid)
예제 #47
0
 def setUp(self):
     self.obj = Subscription(name='Jeferson Calazans', cpf='60546831524',
         email='*****@*****.**', phone='21-86478151',)
예제 #48
0
def signup(request):

    # Necessary data for page
    stripe_key = settings.STRIPE_PUBLIC_KEY
    subscription_form = SubscriptionForm(request.POST or None)
    customer_form = CustomerForm(request.POST or None)
    gift_form = GiftSubscriptionForm(request.POST or None)
    plans = Plan.objects.jsonify_for_form()
    code_check_url = reverse("gifts_check_code")
    invite_code = request.GET.get("invite_code", "")
    reward_code_form = RewardCodeForm(request.POST or None, initial={"invite_code": invite_code})

    context = {
        "customer_form": customer_form,
        "subscription_form": subscription_form,
        "gift_form": gift_form,
        "reward_code_form": reward_code_form,
        "stripe_key": stripe_key,
        "plans": plans,
        "gift_purchase": request.POST.get("gift_purchase"),
        "code_check_url": code_check_url,
        "gift_code": request.POST.get("code"),
    }

    # Shortcut for initial page load
    if request.method != "POST":
        return context

    # Validate forms, handle gift if necessary
    if subscription_form.is_valid():
        if subscription_form.cleaned_data["amount"] == "0.125":
            plan = Plan.objects.get(trial=True)
        else:
            plan = Plan.objects.get(
                amount=subscription_form.cleaned_data["amount"], interval=subscription_form.cleaned_data["interval"]
            )
        context["plan"] = plan
    else:
        return context

    if context.get("gift_purchase") and gift_form.is_valid():
        return gift_purchase(request, context)

    if context.get("gift_code") and customer_form.is_valid():
        return gift_redeem(request, context)

    if not customer_form.is_valid():
        return context

    if not reward_code_form.is_valid():
        return context

    # Attempt normal subscription signup
    with transaction.commit_on_success():
        save = transaction.savepoint()
        try:
            customer = customer_form.save(commit=False).customer
            customer.update_card(request.POST["stripeToken"])
            customer.save()

            subscription = Subscription(customer=customer, plan=plan)
            subscription.save()

            transaction.savepoint_commit(save)

            form_invite_code = reward_code_form.cleaned_data["invite_code"]
            if form_invite_code != "" and form_invite_code != None:
                inv_code_instance = InviteCode.objects.filter(code=form_invite_code)
                if inv_code_instance.exists():
                    inv = inv_code_instance.get()
                    inv.customer.grant_reward(customer)

            if not customer.user.is_active:
                send_verification_mail(request, customer.user, "signup_verify")
                info(request, _("A verification email has been sent with " "a link for activating your account."))
                return redirect(request.GET.get("next", "/"))
            else:
                info(request, _("Successfully signed up"))
                auth_login(request, customer.user)
                return redirect(reverse("customers_home"))

        except Exception as e:
            transaction.savepoint_rollback(save)
            error(request, e)

    return context
예제 #49
0
 def set_subscription_plan(self, plan_id, subscription_id):
     from subscriptions.models import Subscription, SubscriptionPlan
     
     subscription_plan = SubscriptionPlan.objects.filter(plan_id=plan_id).get()
     subscription = Subscription(owner=self, subscription_id=subscription_id, plan=subscription_plan)
     subscription.save()
예제 #50
0
 def post(self, request, content_id=None, *args, **kwargs):
     subscription = Subscription(user=self.request.user, content_id=content_id)
     subscription.save()
     return Response(status=HTTP_200_OK)
예제 #51
0
 def test_state_not_manually_updated(self):
     sub = Subscription(end=self.yearish)
     with self.assertRaises(AttributeError):
         sub.state = State.EXPIRING
예제 #52
0
 def test_initial_state_can_be_anything(self):
     sub = Subscription(state=State.ENDED, end=self.yearish)
     self.assertEqual(sub.state, State.ENDED)