Exemplo n.º 1
0
    def save(self, *args, **kwargs):
        """
        In real world, this object is replicated in the sub_database for consistency purposes and so will hardly
        be modified from that database since Invoice object is never exposed in the admin interface of the IAO.
        So said the save() method on this object will generally be called when the object is being manipulated
        from the upper Ikwen website itself. The changes made from there must then be replicated to the sub database.

        The replication is made by adding the actual Invoice database to DATABASES in settings and calling
        save(using=database).

        Let's recall that we determine if we are on Ikwen website by testing that there is no DATABASE connection
        named 'foundation', since 'foundation' is the 'default' database there.
        """
        using = kwargs.get('using')
        if using:
            del (kwargs['using'])
        else:
            using = 'default'
        if getattr(settings, 'IS_IKWEN', False):
            # If we are on Ikwen itself, replicate the update on the current Service database
            db = self.subscription.__dict__.get('database')
            if db:
                add_database_to_settings(db)
                super(Invoice, self).save(using=db, *args, **kwargs)
        super(Invoice, self).save(using=using, *args, **kwargs)
Exemplo n.º 2
0
    def save_model(self, request, obj, form, change):
        if not change:
            company_id = request.POST.get('company')
            delcom = Service.objects.using(UMBRELLA).get(pk=company_id)
            delcom_config = delcom.config
            if delcom != service:
                if request.POST.get('auth_code') != delcom_config.auth_code:
                    self.message_user(request, _("AUTH CODE is invalid, please verify. If the problem persists, please "
                                                 "contact %s to get the good one." % delcom_config.company_name))
                    return

            try:
                Service.objects.get(pk=delcom.id)
            except Service.DoesNotExist:
                delcom.save(using='default')
                delcom_config.save(using='default')

            add_database_to_settings(delcom.database)
            try:
                Service.objects.using(delcom.database).get(pk=service.id)
            except Service.DoesNotExist:
                config = service.config
                service.save(using=delcom.database)
                config.save(using=delcom.database)

        obj.slug = slugify(obj.name)
        super(DeliveryOptionAdmin, self).save_model(request, obj, form, change)
Exemplo n.º 3
0
 def test_do_import_items(self):
     """
     Importing items merely copies a list of items from the provider database to the retailer database.
     Retailer profile and Member object are copied to the provider's database and vice versa.
     Every imported item must have the field is_retailed=True.
     """
     call_command('loaddata', 'wn_members.yaml', database=UMBRELLA)
     copy_service_and_config_to_default_db()
     service = Service.objects.using(UMBRELLA).get(pk='56eb6d04b37b3379b531b102')
     add_database_to_settings(service.database)
     Item.objects.using(service.database).all().delete()
     call_command('loaddata', 'wn_profiles.yaml', database=service.database)
     call_command('loaddata', 'items.yaml', database=service.database)
     self.client.login(username='******', password='******')
     response = self.client.get(reverse('items:do_import_items'),
                                {'provider_slug': 'les-brasseries-du-cameroun',
                                 'provider_id': '56922874b37b33706b51f002',
                                 'item_ids': '55d1fa8feb60008099bd4152,55d1fa8feb60008099bd4153'})
     self.assertEqual(response.status_code, 200)
     response = json.loads(response.content)
     self.assertTrue(response['success'])
     self.assertEqual(Item.objects.using('default').all().count(), 2)
     Member.objects.using(service.database).get(username='******')  # Member must be in Provider's database
     OperatorProfile.objects.using(service.database).get(pk='56922874b37b33706b51f003')  # Retailer must be in Provider's database
     Service.objects.using(service.database).get(pk='56eb6d04b37b3379b531b103')  # Service must be in Provider's database
     for item in Item.objects.using(service.database).filter(pk__in=['55d1fa8feb60008099bd4152', '55d1fa8feb60008099bd4153']):
         self.assertTrue(item.is_retailed)
     from pymongo import Connection
     cnx = Connection()
     cnx.drop_database(service.database)
Exemplo n.º 4
0
 def test_ProviderProductListView_query_by_category_json_format(self):
     """
     Requesting products list with GET parameter format=json&category_slug=slug&q=searchTerm should.
     Result must return as a list of JSON objects
     """
     copy_service_and_config_to_default_db()
     service = Service.objects.using(UMBRELLA).get(
         pk='56eb6d04b37b3379b531b102')
     add_database_to_settings(service.database)
     Product.objects.using(service.database).all().delete()
     call_command('loaddata',
                  'kc_setup_data.yaml',
                  database=service.database)
     call_command('loaddata', 'products.yaml', database=service.database)
     provider = Service.objects.using(
         service.database).get(pk='56eb6d04b37b3379b531b102')
     Product.objects.using(
         service.database).exclude(provider=provider).delete()
     response = self.client.get(
         reverse('kako:provider_product_list',
                 args=('56922874b37b33706b51f002', )), {
                     'format': 'json',
                     'category_slug': 'food',
                     'q': 'col',
                     'start': 0,
                     'length': 24
                 })
     self.assertEqual(response.status_code, 200)
     products = json.loads(response.content)
     self.assertEqual(len(products), 1)
     self.assertEqual(products[0]['name'], 'Coca-Cola')
     from pymongo import Connection
     cnx = Connection()
     cnx.drop_database(service.database)
Exemplo n.º 5
0
def render_subscription_event(event, request):
    service = event.service
    database = service.database
    add_database_to_settings(database)
    tk = event.model.split('.')
    app_label = tk[0]
    model = tk[1]
    subscription_model = get_model(app_label, model)
    try:
        subscription = subscription_model.objects.using(database).get(
            pk=event.object_id)
        short_description = subscription.__dict__.get('short_description')
        image = subscription.product.image
        try:
            cost = subscription.monthly_cost
            billing_cycle = subscription.billing_cycle
        except AttributeError:
            cost = subscription.product.cost
            billing_cycle = None

        c = Context({
            'title': _(event.event_type.title),
            'product_name': subscription.product.name,
            'short_description': short_description,
            'currency_symbol': service.config.currency_symbol,
            'cost': cost,
            'image_url': image.url if image and image.name else None,
            'billing_cycle': billing_cycle,
            'obj': subscription
        })
    except Subscription.DoesNotExist:
        return None

    html_template = get_template('billing/events/subscription.html')
    return html_template.render(c)
Exemplo n.º 6
0
 def test_set_stock(self):
     """
     set_stock sets stock to the number of units, all passed as url parameter
     """
     call_command('loaddata', 'kc_members.yaml', database=UMBRELLA)
     call_command('loaddata', 'kc_setup_data.yaml')
     call_command('loaddata', 'kc_operators_configs.yaml')
     call_command('loaddata', 'products.yaml')
     service = Service.objects.using(UMBRELLA).get(
         pk='56eb6d04b37b3379b531b103')
     add_database_to_settings(service.database)
     Product.objects.using(service.database).all().delete()
     call_command('loaddata', 'products.yaml', database=service.database)
     response = self.client.get(
         reverse('kako:set_stock',
                 args=('api-signature2', '55d1fa8feb60008099bd4152', 12)))
     response = json.loads(response.content)
     self.assertTrue(response['success'])
     self.assertDictEqual(response['details'], {
         'kcid': '55d1fa8feb60008099bd4152',
         'stock': 12
     })
     product = Product.objects.using(
         service.database).get(pk='55d1fa8feb60008099bd4152')
     self.assertEqual(product.stock, 12)
     config = get_service_instance(UMBRELLA).config
     self.assertEqual(config.last_stock_update_method,
                      OperatorProfile.AUTO_UPDATE)
Exemplo n.º 7
0
 def test_put_product_in_trash(self):
     """
     set_stock causes the stock to lower or raise by the number of units, all passed as GET parameters
     """
     call_command('loaddata', 'kc_members.yaml', database=UMBRELLA)
     copy_service_and_config_to_default_db()
     service = Service.objects.using(UMBRELLA).get(
         pk='56eb6d04b37b3379b531b103')
     add_database_to_settings(service.database)
     call_command('loaddata', 'kc_setup_data.yaml', database='default')
     call_command('loaddata', 'products.yaml', database='default')
     call_command('loaddata',
                  'kc_operators_configs.yaml',
                  database='default')
     call_command('loaddata', 'categories.yaml', database=service.database)
     call_command('loaddata', 'products.yaml', database=service.database)
     Product.objects.using('default').all().update(is_retailed=True)
     self.client.login(username='******', password='******')
     response = self.client.get(
         reverse('kako:put_product_in_trash') +
         '?selection=55d1fa8feb60008099bd4152')
     response = json.loads(response.content)
     self.assertIsNotNone(response['message'])
     product = Product.objects.using(
         service.database).filter(pk='55d1fa8feb60008099bd4152')
     self.assertEqual(product.count(), 0)
     member3 = Member.objects.using(UMBRELLA).get(username='******')
     self.assertEqual(member3.personal_notices, 1)
     self.assertEqual(
         ConsoleEvent.objects.using(UMBRELLA).filter(
             member=member3).count(), 1)
Exemplo n.º 8
0
 def save(self, *args, **kwargs):
     using = kwargs.pop('using', 'default')
     if getattr(settings, 'IS_IKWEN', False):
         db = self.service.database
         add_database_to_settings(db)
         try:
             obj_mirror = OperatorProfile.objects.using(db).get(pk=self.id)
             obj_mirror.currency_code = self.currency_code
             obj_mirror.currency_symbol = self.currency_symbol
             obj_mirror.ikwen_share_rate = self.ikwen_share_rate
             obj_mirror.ikwen_share_fixed = self.ikwen_share_fixed
             obj_mirror.payment_delay = self.payment_delay
             obj_mirror.cash_out_min = self.cash_out_min
             obj_mirror.cash_out_rate = self.cash_out_rate
             obj_mirror.is_certified = self.is_certified
             obj_mirror.can_manage_delivery_options = self.can_manage_delivery_options
             obj_mirror.can_manage_currencies = self.can_manage_currencies
             obj_mirror.is_pro_version = self.is_pro_version
             obj_mirror.max_products = self.max_products
             obj_mirror.sms_api_script_url = self.sms_api_script_url
             super(OperatorProfile, obj_mirror).save(using=db)
         except OperatorProfile.DoesNotExist:
             pass
     else:
         settings_checkout_min = getattr(settings, 'CHECKOUT_MIN', 3000)
         can_set_min_checkout = self.is_pro_version or self.business_type == OperatorProfile.PROVIDER
         if self.checkout_min < settings_checkout_min and not can_set_min_checkout:
             self.checkout_min = settings_checkout_min
     super(OperatorProfile, self).save(using=using, *args, **kwargs)
Exemplo n.º 9
0
 def test_ProviderProductListView(self):
     """
     Page must return HTTP 200 status, products with largest items_sold must come first.
     """
     copy_service_and_config_to_default_db()
     service = Service.objects.using(UMBRELLA).get(
         pk='56eb6d04b37b3379b531b102')
     add_database_to_settings(service.database)
     Product.objects.using(service.database).all().delete()
     call_command('loaddata',
                  'kc_setup_data.yaml',
                  database=service.database)
     call_command('loaddata', 'products.yaml', database=service.database)
     provider = Service.objects.using(
         service.database).get(pk='56eb6d04b37b3379b531b102')
     Product.objects.using(
         service.database).exclude(provider=provider).delete()
     response = self.client.get(
         reverse('kako:provider_product_list',
                 args=('56922874b37b33706b51f002', )))
     self.assertEqual(response.status_code, 200)
     products = response.context['products']
     self.assertEqual(products.count(), 3)
     self.assertEqual(products[0].name, 'Breaded fish')
     from pymongo import Connection
     cnx = Connection()
     cnx.drop_database(service.database)
Exemplo n.º 10
0
 def save(self, **kwargs):
     for operator in OperatorProfile.objects.filter(
             business_type=OperatorProfile.RETAILER):
         db = operator.service.database
         add_database_to_settings(db)
         slug = slugify(self.name)
         try:
             obj_mirror = DeliveryOption.objects.using(db).get(pk=self.id)
             obj_mirror.name = self.name
             obj_mirror.slug = slug
             obj_mirror.short_description = self.short_description
             obj_mirror.description = self.description
             obj_mirror.icon = self.icon
             obj_mirror.cost = self.cost
             obj_mirror.checkout_min = self.checkout_min
             obj_mirror.max_delay = self.max_delay
         except ProductCategory.DoesNotExist:
             obj_mirror = DeliveryOption(
                 company=self.company,
                 name=self.name,
                 slug=slug,
                 short_description=self.short_description,
                 description=self.description,
                 icon=self.icon,
                 cost=self.cost,
                 max_delay=self.max_delay,
                 checkout_min=self.checkout_min)
         super(DeliveryOption, obj_mirror).save(using=db)
     super(DeliveryOption, self).save(**kwargs)
Exemplo n.º 11
0
def wipe_test_data(db='default'):
    """
    This test was originally built with django-nonrel 1.6 which had an error when flushing the database after
    each test. So the flush is performed manually with this custom tearDown()
    """
    import ikwen_kakocase.kako.models
    import ikwen_kakocase.trade.models
    import ikwen_kakocase.shopping.models
    import ikwen_kakocase.kakocase.models
    import ikwen_kakocase.commarketing.models
    import ikwen.core.models
    import ikwen.revival.models
    import daraja.models
    if db != 'default':
        add_database_to_settings(db)
    for name in (
            'Customer',
            'AnonymousBuyer',
    ):
        model = getattr(ikwen_kakocase.shopping.models, name)
        model.objects.using(db).all().delete()
    for name in ('OperatorProfile', 'ProductCategory', 'BusinessCategory',
                 'DeliveryOption', 'City'):
        model = getattr(ikwen_kakocase.kakocase.models, name)
        model.objects.using(db).all().delete()
    for name in ('Product', 'RecurringPaymentService', 'Photo'):
        model = getattr(ikwen_kakocase.kako.models, name)
        model.objects.using(db).all().delete()
    for name in ('Order', 'Package'):
        model = getattr(ikwen_kakocase.trade.models, name)
        model.objects.using(db).all().delete()
    for name in ('Banner', 'SmartCategory'):
        model = getattr(ikwen_kakocase.commarketing.models, name)
        model.objects.using(db).all().delete()
    for name in (
            'Application',
            'Service',
            'Config',
            'ConsoleEventType',
            'ConsoleEvent',
            'Country',
    ):
        model = getattr(ikwen.core.models, name)
        model.objects.using(db).all().delete()
    for name in ('PartnerProfile', 'ApplicationRetailConfig'):
        model = getattr(ikwen.partnership.models, name)
        model.objects.using(db).all().delete()
    for name in ('ObjectProfile', 'MemberProfile', 'Revival', 'ProfileTag',
                 'Target'):
        model = getattr(ikwen.revival.models, name)
        model.objects.using(db).all().delete()
    for name in ('Product', 'Payment', 'Invoice', 'Subscription',
                 'InvoicingConfig', 'PaymentMean', 'MoMoTransaction',
                 'SupportBundle', 'SupportCode'):
        model = getattr(ikwen.billing.models, name)
        model.objects.using(db).all().delete()
    for name in ('DarajaConfig', 'DaraRequest', 'Dara', 'AbuseReport'):
        model = getattr(daraja.models, name)
        model.objects.using(db).all().delete()
Exemplo n.º 12
0
 def get_context_data(self, **kwargs):
     context = super(ProviderProductList, self).get_context_data(**kwargs)
     provider_id = kwargs['provider_id']
     service = OperatorProfile.objects.using(UMBRELLA).get(pk=provider_id).service
     add_database_to_settings(service.database)
     context['categories'] = ProductCategory.objects.using(service.database).filter(items_count__gt=0)
     context['provider_database'] = service.database
     return context
Exemplo n.º 13
0
 def setUp(self):
     self.client = Client()
     add_database_to_settings('test_kc_partner_jumbo')
     wipe_test_data()
     wipe_test_data('test_kc_partner_jumbo')
     wipe_test_data(UMBRELLA)
     for fixture in self.fixtures:
         call_command('loaddata', fixture)
         call_command('loaddata', fixture, database=UMBRELLA)
Exemplo n.º 14
0
 def get_context_data(self, **kwargs):
     context = super(ProviderItemDetail, self).get_context_data(**kwargs)
     provider_id = kwargs['provider_id']
     service = OperatorProfile.objects.using(UMBRELLA).get(pk=provider_id).service
     add_database_to_settings(service.database)
     item_id = kwargs['item_id']
     context['categories'] = ItemCategory.objects.using(service.database).filter(items_count__gt=0)
     context['item'] = Item.objects.using(service.database).get(pk=item_id)
     return context
Exemplo n.º 15
0
 def propagate_changes(self):
     for s in self.get_services():
         db = s.database
         add_database_to_settings(db)
         Member.objects.using(db).filter(pk=self.id)\
             .update(email=self.email, phone=self.phone, gender=self.gender, first_name=self.first_name,
                     last_name=self.last_name, full_name=self.first_name + ' ' + self.last_name,
                     photo=self.photo.name, cover_image=self.cover_image.name, phone_verified=self.phone_verified,
                     email_verified=self.email_verified, language=self.language)
Exemplo n.º 16
0
def render_service_deployed_event(event, request):
    from ikwen.conf import settings as ikwen_settings
    service = event.service
    database = service.database
    add_database_to_settings(database)
    currency_symbol = service.config.currency_symbol
    try:
        invoice = Invoice.objects.using(database).get(pk=event.object_id)
    except Invoice.DoesNotExist:
        try:
            invoice = Invoice.objects.using(UMBRELLA).get(pk=event.object_id)
        except:
            invoice = None
    service_deployed = invoice.service if invoice else Service.objects.get(
        pk=event.object_id)
    show_pay_now = invoice.status != Invoice.PAID if invoice else False
    due_date = invoice.due_date if invoice else None
    is_daraja = service_deployed.app.slug == 'daraja'
    member = service_deployed.member
    if request.GET['member_id'] != member.id:
        data = {
            'title': 'New service deployed',
            'details': service_deployed.details,
            'member': member,
            'service_deployed': True
        }
        template_name = 'billing/events/notice.html'
    else:
        template_name = 'core/events/service_deployed.html'
        data = {
            'obj': invoice,
            'project_name': service_deployed.project_name,
            'service_url': service_deployed.url,
            'due_date': due_date,
            'is_daraja': is_daraja,
            'show_pay_now': show_pay_now
        }
    if is_daraja:
        data.update({'details_url': reverse('daraja:registered_company_list')})
    else:
        data.update({
            'currency_symbol':
            currency_symbol,
            'details_url':
            IKWEN_BASE_URL +
            reverse('billing:invoice_detail', args=(invoice.id, )),
            'amount':
            invoice.amount,
            'MEMBER_AVATAR':
            ikwen_settings.MEMBER_AVATAR,
            'IKWEN_MEDIA_URL':
            ikwen_settings.MEDIA_URL
        })
    c = Context(data)
    html_template = get_template(template_name)
    return html_template.render(c)
Exemplo n.º 17
0
 def save_model(self, request, obj, form, change):
     super(ApplicationRetailConfigAdmin,
           self).save_model(request, obj, form, change)
     if obj.partner:
         db = obj.partner.database
         add_database_to_settings(db)
         try:
             Application.objects.using(db).get(pk=obj.app.id)
         except Application.DoesNotExist:
             obj.app.save(using=db)
Exemplo n.º 18
0
 def propagate_password_change(self, new_password):
     for s in self.get_services():
         db = s.database
         add_database_to_settings(db)
         try:
             m = Member.objects.using(db).get(pk=self.id)
             m.set_password(new_password)
             m.save(using=db)
         except Member.DoesNotExist:
             pass
Exemplo n.º 19
0
def put_product_in_trash(request, *args, **kwargs):
    # TODO: Implement Trash view itself so that people can view and restore the content of the trash
    config = get_service_instance().config
    selection = request.GET['selection'].split(',')
    deleted = []
    for product_id in selection:
        try:
            product = Product.objects.get(pk=product_id)
            product.in_trash = True
            product.visible = False
            product.save()
            deleted.append(product_id)
            if getattr(settings, 'IS_PROVIDER', False):
                connection = mail.get_connection()
                try:
                    connection.open()
                    connection_opened = True
                except:
                    connection_opened = False
                for retailer_profile in OperatorProfile.objects.filter(business_type=OperatorProfile.RETAILER):
                    member = retailer_profile.service.member
                    service = retailer_profile.service
                    db = service.database
                    add_database_to_settings(db)
                    Product.objects.using(db).get(pk=product_id).delete()
                    ProductCategory.objects.using(db).filter(pk=product.category.id).update(items_count=F('items_count')-1)
                    if product.is_retailed:
                        add_event(service, PROVIDER_REMOVED_PRODUCT_EVENT, member=member, object_id=product_id)
                        if connection_opened:
                            # TODO: Verify what mail looks like after tests once UIs are implemented
                            subject = _("Product taken out by %s" % config.company_name)
                            message = _("Hi %(member_name)s,<br/> The product below was"
                                        "removed by <strong>%(company_name)s.</strong> "
                                        "It won't appear on your website anymore." % {'member_name': member.first_name,
                                                                                      'company_name': config.company_name})
                            html_content = get_mail_content(subject, message,
                                                            template_name='kako/retailer/mails/product_removed.html',
                                                            extra_context={'product': product, 'service': service,
                                                                           'provider_id': config.id})
                            sender = '%s <no-reply@%s.com>' % (service.project_name, service.project_name_slug)
                            msg = EmailMessage(subject, html_content, sender, [member.email])
                            msg.content_subtype = "html"
                            Thread(target=lambda m: m.send(), args=(msg,)).start()

                try:
                    connection.close()
                except:
                    pass
        except Product.DoesNotExist:
            message = "Product %s was not found."
            break
    else:
        message = "%d product(s) moved to trash." % len(selection)
    response = {'message': message, 'deleted': deleted}
    return HttpResponse(json.dumps(response), 'content-type: text/json')
Exemplo n.º 20
0
    def activate_ssl(self, is_naked_domain=True, reload_web_server=False):
        """
        Creates and activates an SSL Certificate for the domain
        """
        if "go.ikwen.com" in self.url:
            return

        subprocess.call([
            'sudo', 'unlink',
            '/etc/apache2/sites-enabled/' + self.domain + '.conf'
        ])

        from ikwen.core.log import ikwen_error_log_filename
        eh = open(ikwen_error_log_filename, 'a')
        if is_naked_domain:  # Generate certificate for the raw domain and www
            val = subprocess.call([
                'sudo', 'certbot', 'certonly', '--apache', '-d', self.domain,
                '-d', 'www.' + self.domain
            ],
                                  stderr=eh)
        else:
            val = subprocess.call(
                ['sudo', 'certbot', 'certonly', '--apache', '-d', self.domain],
                stderr=eh)

        if val != 0:
            eh.close()
            raise OSError(
                "Failed to generate and install SSL certificate for %s" %
                self.domain)
        web_server_config_template = '%s/cloud_setup/apache_ssl.conf.html' % self.app.slug
        apache_tpl = get_template(web_server_config_template)
        apache_context = Context({
            'is_naked_domain': is_naked_domain,
            'domain': self.domain,
            'ikwen_name': self.project_name_slug
        })
        fh = open(self.home_folder + '/apache.conf', 'w')
        fh.write(apache_tpl.render(apache_context))
        fh.close()

        subprocess.call([
            'sudo', 'ln', '-sf', self.home_folder + '/apache.conf',
            '/etc/apache2/sites-enabled/' + self.domain + '.conf'
        ])
        self.has_ssl = True
        db = self.database
        add_database_to_settings(db)
        self.save(using='umbrella')
        self.save(using=db)
        if reload_web_server:
            from ikwen.core.tools import reload_server
            Thread(target=reload_server).start()
Exemplo n.º 21
0
 def tearDown(self):
     add_database_to_settings('test_kc_tecnomobile')
     add_database_to_settings('test_kc_sabc')
     add_database_to_settings('test_kc_foka')
     add_database_to_settings('test_kc_ems')
     add_database_to_settings('test_kc_afic')
     wipe_test_data()
     wipe_test_data('test_kc_tecnomobile')
     wipe_test_data('test_kc_sabc')
     wipe_test_data('test_kc_foka')
     wipe_test_data('test_kc_ems')
     wipe_test_data('test_kc_afic')
     wipe_test_data(UMBRELLA)
     OperatorWallet.objects.using(WALLETS_DB_ALIAS).all().update(balance=0)
     cache.clear()
Exemplo n.º 22
0
 def save(self, *args, **kwargs):
     using = kwargs.pop('using', 'default')
     if getattr(settings, 'IS_IKWEN', False):
         db = self.service.database
         add_database_to_settings(db)
         try:
             obj_mirror = OperatorProfile.objects.using(db).get(pk=self.id)
             obj_mirror.ikwen_share_rate = self.ikwen_share_rate
             obj_mirror.ikwen_share_fixed = self.ikwen_share_fixed
             obj_mirror.max_customers = self.max_customers
             obj_mirror.cash_out_min = self.cash_out_min
             obj_mirror.cash_out_rate = self.cash_out_rate
             super(OperatorProfile, obj_mirror).save(using=db)
         except OperatorProfile.DoesNotExist:
             pass
     super(OperatorProfile, self).save(using=using, *args, **kwargs)
Exemplo n.º 23
0
    def update_domain(self,
                      new_domain,
                      is_naked_domain=True,
                      web_server_config_template=None):
        """
        Update domain of a service to a new one. Rewrites the web server
        config file and reloads it.
        """
        previous_domain = self.domain
        if not web_server_config_template:
            if self.has_ssl:
                web_server_config_template = '%s/cloud_setup/apache_ssl.conf.html' % self.app.slug
            else:
                web_server_config_template = '%s/cloud_setup/apache.conf.html' % self.app.slug
        apache_tpl = get_template(web_server_config_template)
        apache_context = Context({
            'is_naked_domain': is_naked_domain,
            'domain': new_domain,
            'ikwen_name': self.project_name_slug
        })
        fh = open(self.home_folder + '/apache.conf', 'w')
        fh.write(apache_tpl.render(apache_context))
        fh.close()

        if "go.ikwen.com" not in self.url:
            subprocess.call([
                'sudo', 'unlink',
                '/etc/apache2/sites-enabled/' + previous_domain + '.conf'
            ])

        self.domain = new_domain
        self.url = 'http://' + new_domain
        self.save(using='umbrella')
        db = self.database
        add_database_to_settings(db)
        self.save(using=db)
        if self.retailer:
            db = self.retailer.database
            add_database_to_settings(db)
            self.save(using=db)

        subprocess.call([
            'sudo', 'ln', '-sf', self.home_folder + '/apache.conf',
            '/etc/apache2/sites-enabled/' + new_domain + '.conf'
        ])
        from ikwen.core.tools import reload_server
        Thread(target=reload_server).start()
Exemplo n.º 24
0
    def save(self, *args, **kwargs):
        """
        In real world, this object is replicated in the sub_database for consistency purposes and so will hardly
        be modified from that database since Payment object is never exposed in the admin interface of the IAO.
        So said the save() method on this object will generally be called when the object is being manipulated
        from the upper ikwen website itself. The changes made from there must then be replicated to the sub database.

        The replication is made by adding the actual Service database to DATABASES in settings and calling
        save(using=database).
        """
        using = kwargs.pop('using', 'default')
        if getattr(settings, 'IS_IKWEN', False):
            # If we are on ikwen itself, replicate the update on the current Service database
            db = self.invoice.subscription.__dict__.get('database')
            if db:
                add_database_to_settings(db)
                super(Payment, self).save(using=db)
        super(Payment, self).save(using=using, *args, **kwargs)
Exemplo n.º 25
0
 def save(self, *args, **kwargs):
     using = kwargs.pop('using', 'default')
     if getattr(settings, 'IS_IKWEN', False):
         db = self.service.database
         add_database_to_settings(db)
         try:
             obj_mirror = Config.objects.using(db).get(pk=self.id)
             obj_mirror.currency_code = self.currency_code
             obj_mirror.currency_symbol = self.currency_symbol
             obj_mirror.cash_out_min = self.cash_out_min
             obj_mirror.cash_out_rate = self.cash_out_rate
             obj_mirror.is_pro_version = self.is_pro_version
             obj_mirror.is_standalone = self.is_standalone
             obj_mirror.can_manage_currencies = self.can_manage_currencies
             obj_mirror.sms_api_script_url = self.sms_api_script_url
             super(Config, obj_mirror).save(using=db)
         except Config.DoesNotExist:
             pass
     super(Config, self).save(using=using)
Exemplo n.º 26
0
 def get_context_data(self, **kwargs):
     context = super(ProviderDashboard, self).get_context_data(**kwargs)
     customers_today = slice_watch_objects(Customer)
     customers_yesterday = slice_watch_objects(Customer, 1)
     customers_last_week = slice_watch_objects(Customer, 7)
     customers_last_28_days = slice_watch_objects(Customer, 28)
     customers_report = {
         'today':
         rank_watch_objects(customers_today, 'turnover_history'),
         'yesterday':
         rank_watch_objects(customers_yesterday, 'turnover_history', 1),
         'last_week':
         rank_watch_objects(customers_last_week, 'turnover_history', 7),
         'last_28_days':
         rank_watch_objects(customers_last_28_days, 'turnover_history', 28)
     }
     context['customers_report'] = customers_report
     try:
         if getattr(settings, 'DEBUG', False):
             _umbrella_db = 'ikwen_umbrella'
         else:
             _umbrella_db = 'ikwen_umbrella_prod'  # Force the umbrella Alias to point the real umbrella DB
         add_database_to_settings(_umbrella_db)
         service = get_service_instance()
         DarajaConfig.objects.using(_umbrella_db).get(
             service=service, referrer_share_rate__gt=0)
         daras_list = slice_watch_objects(Dara,
                                          28,
                                          time_field='last_transaction_on')
         daras_report = {
             'today':
             rank_watch_objects(daras_list, 'turnover_history'),
             'yesterday':
             rank_watch_objects(daras_list, 'turnover_history', 1),
             'last_week':
             rank_watch_objects(daras_list, 'turnover_history', 7),
             'last_28_days':
             rank_watch_objects(daras_list, 'turnover_history', 28)
         }
         context['daras_report'] = daras_report
     except:
         pass
     return context
Exemplo n.º 27
0
 def test_ProviderItemListView_json_format(self):
     """
     Requesting items list with GET parameter format=json&q=searchTerm should.
     Result must return as a list of JSON objects
     """
     copy_service_and_config_to_default_db()
     service = Service.objects.using(UMBRELLA).get(pk='56eb6d04b37b3379b531b102')
     add_database_to_settings(service.database)
     Item.objects.using(service.database).all().delete()
     call_command('loaddata', 'items.yaml', database=service.database)
     response = self.client.get(reverse('items:provider_item_list', args=('56922874b37b33706b51f002', )),
                                {'format': 'json', 'q': 'col', 'start': 0, 'length': 24})
     self.assertEqual(response.status_code, 200)
     items = json.loads(response.content)
     self.assertEqual(len(items), 1)
     self.assertEqual(items[0]['name'], 'Coca-Cola')
     from pymongo import Connection
     cnx = Connection()
     cnx.drop_database(service.database)
Exemplo n.º 28
0
def wipe_test_data(db='default'):
    """
    This test was originally built with django-nonrel 1.6 which had an error when flushing the database after
    each test. So the flush is performed manually with this custom tearDown()
    """
    import ikwen_webnode.items.models
    import ikwen_webnode.web.models
    import ikwen.core.models
    if db != 'default':
        add_database_to_settings(db)
    for name in ('Item','ItemCategory', 'RecurringPaymentService', 'Photo'):
        model = getattr(ikwen_webnode.items.models, name)
        model.objects.using(db).all().delete()
    for name in ('Banner', 'SmartCategory'):
        model = getattr(ikwen_webnode.web.models, name)
        model.objects.using(db).all().delete()
    for name in ('Application', 'Service', 'Config', 'ConsoleEventType', 'ConsoleEvent', 'Country', ):
        model = getattr(ikwen.core.models, name)
        model.objects.using(db).all().delete()
Exemplo n.º 29
0
 def test_join(self):
     """
     Joining adds the requesting member in the service local database and
     create the corresponding UserPermissionList object with the right group
     """
     service = Service.objects.get(pk='56eb6d04b37b3379b531b102')
     et = ConsoleEventType.objects.get(
         pk='56eb6db3379b531a0104b371'
     )  # Collaboration Access Request event type
     group_id = '5804b37b3379b531e01eb6d2'
     add_database_to_settings(service.database)
     Group.objects.using(service.database).create(pk=group_id,
                                                  name=COMMUNITY)
     UserPermissionList.objects.using(service.database).all().delete()
     self.client.login(username='******', password='******')
     response = self.client.get(reverse('ikwen:join'), {
         'service_id': service.id,
         'format': 'json'
     })
     json_response = json.loads(response.content)
     self.assertTrue(json_response['success'])
     member3 = Member.objects.get(pk='56eb6d04b37b3379b531e013')
     self.assertIn(group_id, member3.group_fk_list)
     self.assertEqual(
         ConsoleEvent.objects.filter(member=service.member,
                                     event_type=et).count(), 0)
     perm_obj = UserPermissionList.objects.using(
         service.database).get(user=member3)
     self.assertListEqual(perm_obj.group_fk_list, [group_id])
     self.client.logout()
     self.client.login(username='******', password='******')
     response = self.client.get(reverse('ikwen:console'))
     self.assertEqual(len(response.context['event_list']), 1)
     self.client.logout()
     self.client.login(username='******', password='******')
     response = self.client.get(reverse('ikwen:console'))
     self.assertIn(service.id, member3.customer_on_fk_list)
     self.assertEqual(len(response.context['event_list']), 1)
     from pymongo import Connection
     cnx = Connection()
     cnx.drop_database(service.database)
Exemplo n.º 30
0
 def test_submit_item_with_existing_item_being_retailed(self):
     """
     submit_item view redirects to the add_view page without actually updating item information
     if a provider attemps to update information of a item being retailed.
     """
     call_command('loaddata', 'wn_members.yaml', database=UMBRELLA)
     copy_service_and_config_to_default_db()
     service = Service.objects.using(UMBRELLA).get(pk='56eb6d04b37b3379b531b102')
     add_database_to_settings(service.database)
     call_command('loaddata', 'items.yaml')
     self.client.login(username='******', password='******')
     item = Item.objects.get(pk='55d1fa8feb60008099bd4152')
     item.is_retailed = True
     item.save()
     p_dict = item.__dict__
     p_dict['category'] = p_dict['category_id']
     p_dict['retail_price'] = 500
     response = self.client.post(reverse('items:change_item', args=('55d1fa8feb60008099bd4152', )), p_dict)
     self.assertIsNotNone(response.context['error'])
     item = Item.objects.get(pk='55d1fa8feb60008099bd4152')
     self.assertEqual(item.retail_price, 450)