Esempio n. 1
0
 def setup_shopdata(self):
     product = Product(name='Test', slug='test')
     product.save()
     tax = TaxClass(name='VAT', rate=10.00)
     tax.save()
     price = ProductPrice(product=product, currency='USD', 
                          _unit_price=100.00, tax_included=1, tax_class=tax)
     price.save()
     order = Order.objects.create(user_id=1, currency='USD')
     order.modify_item(product, relative=1)
     self.order = order
Esempio n. 2
0
class CheckoutCartToOrderTestCase(TestCase):

    def setUp(self):
        self.user = User.objects.create(username="******",
                                        email="*****@*****.**",
                                        first_name="Test",
                                        last_name="Toto")
        self.request = Mock()
        setattr(self.request, 'user', self.user)
        setattr(self.request, 'session', {})
        setattr(self.request, 'method', 'GET')
        self.product = Product(name='pizza', slug='pizza', unit_price='1.45')
        self.product.save()
        self.cart = Cart()
        self.cart.user = self.user
        self.cart.save()

    def test_order_created(self):
        view = CheckoutSelectionView(request=self.request)
        res = view.create_order_object_from_cart()
        self.assertEqual(res.order_total, Decimal('0'))

    def test_orders_are_created_and_cleaned_up(self):
        view = CheckoutSelectionView(request=self.request)
        # create a new order with pk 1
        old_order = view.create_order_object_from_cart()
        # create order with pk 2 so sqlite doesn't reuse pk 1
        Order.objects.create()
        # then create a different new order, from a different cart with pk 3
        # order pk 1 should be deleted here
        self.cart.add_product(self.product)
        new_order = view.create_order_object_from_cart()
        self.assertFalse(Order.objects.filter(pk=old_order.pk).exists()) # check it was deleted
        self.assertNotEqual(old_order.order_total, new_order.order_total)

    def test_processing_signal(self):
        view = CheckoutSelectionView(request=self.request)

        order_from_signal = []
        def receiver(sender, order=None, **kwargs):
            order_from_signal.append(order)

        processing.connect(receiver)
        res = view.create_order_object_from_cart()

        self.assertIs(res, order_from_signal[0])
Esempio n. 3
0
 def handle(self, *args, **options):
     try:
         p = Product()
         p.name = u'\"Норка\"'
         p.price = 100500.0
         p.img_url = '/static/bfriday/1.png'
         p.SKU = '-1'
         p.save()
     except Exception, e:
         pass
Esempio n. 4
0
 def setUp(self):
     self.user = User.objects.create(username="******",
                                     email="*****@*****.**",
                                     first_name="Test",
                                     last_name="Toto")
     self.request = Mock()
     setattr(self.request, 'user', self.user)
     setattr(self.request, 'session', {})
     setattr(self.request, 'method', 'GET')
     self.product = Product(name='pizza', slug='pizza', unit_price='1.45')
     self.product.save()
     self.cart = Cart()
     self.cart.user = self.user
     self.cart.save()
Esempio n. 5
0
from django.conf.urls.defaults import *
from shop.models import Product

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('django.views.generic.simple',
    (r'^$', 'direct_to_template', {'template': 'home/index.html'}),
)

urlpatterns += patterns('django.views.generic.list_detail',
    (r'^products/$', 'object_list', {'queryset': Product.get_ordered_by_price(), 'template_name': 'product/list.html'})
)


urlpatterns += patterns('project.shop.views',
    (r'^create-product/$', 'create_product'),
    (r'^add-product/$', 'add_product'),
    (r'^edit-product/(?P<product_id>\d+)$', 'edit_product'),
    (r'^update-product/(?P<product_id>\d+)$', 'update_product'),
    (r'^delete-product/(?P<product_id>\d+)$', 'delete_product'),
 
    (r'^card/$', 'card'),
    (r'^add-to-card/(?P<product_id>\d+)$', 'add_to_card'),
    
    (r'^register/$', 'register'),
    (r'^login/$', 'login'),
    (r'^logout/$', 'logout')
)
Esempio n. 6
0
    def trans():
        to_put = list()
        customer_store_order_key = Order.create_key(
            customer.id, Order.CUSTOMER_STORE_ORDER_NUMBER)
        subscription_order_key = Order.create_key(
            customer.id, customer.subscription_order_number)
        team_key = RegioManagerTeam.create_key(customer.team_id)
        product_key = Product.create_key(item.code)

        if item.app_id is not MISSING:
            app_key = App.create_key(item.app_id)
            product, customer_store_order, sub_order, app, team = db.get([
                product_key, customer_store_order_key, subscription_order_key,
                app_key, team_key
            ])
            if sub_order.status != Order.STATUS_SIGNED:
                raise BusinessException(
                    translate(lang, SOLUTION_COMMON, u'no_unsigned_order'))
            # check if the provided app does exist
            azzert(app)
        else:
            product, customer_store_order, team = db.get(
                [product_key, customer_store_order_key, team_key])

        # Check if the item has a correct count.
        # Should never happen unless the user manually recreates the ajax request..
        azzert(
            not product.possible_counts
            or item.count in product.possible_counts
            or item.code == Product.PRODUCT_EXTRA_CITY,
            u'Invalid amount of items supplied')
        number = 0
        existing_order_items = list()
        vat_pct = get_vat_pct(customer, team)
        item_already_added = False
        if not customer_store_order:
            # create new order
            customer_store_order = Order(key=customer_store_order_key)
            customer_store_order.contact_id = contact.key().id()
            customer_store_order.date = now()
            customer_store_order.vat_pct = 0
            customer_store_order.amount = 0
            customer_store_order.vat = 0
            customer_store_order.vat_pct = vat_pct
            customer_store_order.total_amount = 0
            customer_store_order.is_subscription_order = False
            customer_store_order.manager = STORE_MANAGER
            customer_store_order.team_id = None
        else:
            order_items = OrderItem.list_by_order(customer_store_order.key())
            for i in order_items:
                number = i.number if i.number > number else number
                existing_order_items.append(i)
                # Check if this city isn't already in the possible pending order.
                if hasattr(i, 'app_id') and (i.app_id == item.app_id or
                                             item.app_id in customer.app_ids):
                    raise BusinessException(
                        translate(lang, SOLUTION_COMMON,
                                  u'item_already_added'))
                else:
                    # Check if there already is an orderitem with the same product code.
                    # If so, add the count of this new item to the existing item.
                    for it in order_items:
                        if it.product_code == item.code and it.product_code not in (
                                Product.PRODUCT_EXTRA_CITY,
                                Product.PRODUCT_NEWS_PROMOTION):
                            if (
                                    it.count + item.count
                            ) in product.possible_counts or not product.possible_counts:
                                it.count += item.count
                                item_already_added = True
                                to_put.append(it)
                                order_item = it
                            elif len(product.possible_counts) != 0:
                                raise BusinessException(
                                    translate(
                                        lang,
                                        SOLUTION_COMMON,
                                        u'cant_order_more_than_specified',
                                        allowed_items=max(
                                            product.possible_counts)))

        if item.app_id is not MISSING:
            remaining_length, _ = get_subscription_order_remaining_length(
                customer.id, customer.subscription_order_number)
            subscription_order_charge_date = format_date(
                datetime.datetime.utcfromtimestamp(sub_order.next_charge_date),
                locale=lang)
            total = remaining_length * product.price
        else:
            total = product.price * item.count
        vat = total * vat_pct / 100
        total_price = total + vat
        customer_store_order.amount += total
        customer_store_order.vat += vat
        azzert(customer_store_order.total_amount >= 0)
        customer_store_order.total_amount += total_price
        service_visible_in_translation = None
        if not item_already_added:
            order_item = OrderItem(parent=customer_store_order.key())
            order_item.number = number
            order_item.comment = product.default_comment(customer.language)
            order_item.product_code = product.code
            if item.app_id is not MISSING:
                order_item.count = remaining_length
                service_visible_in_translation = translate(
                    lang,
                    SOLUTION_COMMON,
                    'service_visible_in_app',
                    subscription_expiration_date=subscription_order_charge_date,
                    amount_of_months=remaining_length,
                    extra_city_price=product.price_in_euro,
                    app_name=app.name)
            else:
                order_item.count = item.count
            order_item.price = product.price

            if item.app_id is not MISSING:
                order_item.app_id = item.app_id
            to_put.append(order_item)
        to_put.append(customer_store_order)
        db.put(to_put)
        return order_item, service_visible_in_translation
Esempio n. 7
0
def create_free_product(legal_entity_id, code_prefix=''):
    p = Product(key_name=code_prefix + Product.PRODUCT_FREE_SUBSCRIPTION)
    p.price = 0
    p.default_count = 1
    p.default = False
    p.possible_counts = []
    p.is_subscription = True
    p.organization_types = []
    p.product_dependencies = []
    p.visible = True
    p.legal_entity_id = legal_entity_id
    p.module_set = 'ALL'
    if code_prefix:
        p.description_translation_key = p.code[len(code_prefix
                                                   ):] + '.description'
        p.default_comment_translation_key = p.code[len(code_prefix
                                                       ):] + '.default_comment'
    return p
Esempio n. 8
0
def _recurrent_billing():
    today = now()
    products = Product.get_products_dict()
    run_job(_qry, [today], _create_charge, [today, products])
Esempio n. 9
0
def create_and_pay_news_order(service_user, news_item_id, order_items_to):
    """
    Creates an order, orderitems, charge and executes the charge. Should be executed in a transaction.
    Args:
        service_user (users.User)
        news_item_id (long)
        order_items_to (ist of OrderItemTO)

    Raises:
        NoCreditCardException
        ProductNotFoundException
    """
    @db.non_transactional
    def _get_customer():
        return get_customer(service_user)

    @db.non_transactional
    def _get_contact():
        return Contact.get_one(customer)

    customer = _get_customer()
    azzert(customer)
    contact = _get_contact()
    azzert(contact)
    if not customer.stripe_valid:
        raise NoCreditCardException(customer)
    extra_city_product_key = Product.create_key(Product.PRODUCT_EXTRA_CITY)
    news_product_key = Product.create_key(Product.PRODUCT_NEWS_PROMOTION)
    rmt_key = RegioManagerTeam.create_key(customer.team_id)
    extra_city_product, news_promotion_product, team = db.get(
        (extra_city_product_key, news_product_key, rmt_key))
    azzert(extra_city_product)
    azzert(news_promotion_product)
    azzert(team)
    new_order_key = Order.create_key(customer.id,
                                     OrderNumber.next(team.legal_entity_key))
    vat_pct = get_vat_pct(customer, team)

    total_amount = 0
    added_app_ids = []
    for order_item in order_items_to:
        if order_item.product == Product.PRODUCT_EXTRA_CITY:
            total_amount += extra_city_product.price * order_item.count
            added_app_ids.append(order_item.app_id)
            order_item.price = extra_city_product.price
        elif order_item.product == Product.PRODUCT_NEWS_PROMOTION:
            total_amount += news_promotion_product.price * order_item.count
            order_item.price = news_promotion_product.price
        else:
            raise BusinessException('Invalid product \'%s\'' %
                                    order_item.product)
    si = get_default_service_identity(users.User(customer.service_email))
    if added_app_ids:
        keys = [App.create_key(app_id) for app_id in added_app_ids]
        apps = db.get(keys)
        for app_id, app in zip(added_app_ids, apps):
            if not app:
                raise AppNotFoundException(app_id)
            if app_id in si.appIds:
                raise BusinessException('Customer %s already has app_id %s' %
                                        (customer.id, app_id))

    vat = int(round(vat_pct * total_amount / 100))
    total_amount_vat_incl = int(round(total_amount + vat))
    now_ = now()
    to_put = []
    order = Order(key=new_order_key,
                  date=now_,
                  amount=total_amount,
                  vat_pct=vat_pct,
                  vat=vat,
                  total_amount=total_amount_vat_incl,
                  contact_id=contact.id,
                  status=Order.STATUS_SIGNED,
                  is_subscription_order=False,
                  is_subscription_extension_order=False,
                  date_signed=now_,
                  manager=STORE_MANAGER,
                  team_id=team.id)
    to_put.append(order)
    azzert(order.total_amount >= 0)

    for item in order_items_to:
        order_item = OrderItem(parent=new_order_key,
                               number=item.number,
                               product_code=item.product,
                               count=item.count,
                               comment=item.comment,
                               price=item.price)
        order_item.app_id = item.app_id
        if order_item.product_code == Product.PRODUCT_NEWS_PROMOTION:
            order_item.news_item_id = news_item_id
        to_put.append(order_item)

    db.put(to_put)

    # Not sure if this is necessary
    deferred.defer(generate_and_put_order_pdf_and_send_mail,
                   customer,
                   new_order_key,
                   service_user,
                   _transactional=True)

    # No need for signing here, immediately create a charge.
    to_put = []
    charge = Charge(parent=new_order_key)
    charge.date = now()
    charge.type = Charge.TYPE_ORDER_DELIVERY
    charge.amount = order.amount
    charge.vat_pct = order.vat_pct
    charge.vat = order.vat
    charge.total_amount = order.total_amount
    charge.manager = order.manager
    charge.team_id = order.team_id
    charge.status = Charge.STATUS_PENDING
    charge.date_executed = now()
    charge.currency_code = team.legal_entity.currency_code
    to_put.append(charge)

    # Update the regiomanager statistics so these kind of orders show up in the monthly statistics
    deferred.defer(update_regiomanager_statistic,
                   gained_value=order.amount / 100,
                   manager=order.manager,
                   _transactional=True)

    # Update the customer service
    si.appIds.extend(added_app_ids)
    to_put.append(si)

    # Update the customer object so the newly added apps are added.
    customer.app_ids.extend(added_app_ids)
    customer.extra_apps_count += len(added_app_ids)
    to_put.append(customer)
    db.put(to_put)
    deferred.defer(re_index, si.user)

    # charge the credit card
    if charge.total_amount > 0:
        get_payed(customer.id, order, charge)
        server_settings = get_server_settings()
        send_to = server_settings.supportWorkers
        send_to.append(MC_DASHBOARD.email())
        channel_data = {
            'customer': customer.name,
            'no_manager': True,
            'amount': charge.amount / 100,
            'currency': charge.currency
        }
        channel.send_message(map(users.User, send_to),
                             'shop.monitoring.signed_order',
                             info=channel_data)
    else:
        charge.status = Charge.STATUS_EXECUTED
        charge.date_executed = now()
        charge.put()
    channel.send_message(service_user, 'common.billing.orders.update')
Esempio n. 10
0
 def get(self, request):
     product =  Product()
     catalogs = Catalog.objects.all()
     pclasess = ProductClass.objects.all()
     return render(request=request, template_name='cms/products/edit.html',
                   context={"title_page": "Товары", "product": product, "catalogs": catalogs, "product_class_list": pclasess})
Esempio n. 11
0
def add_product(request):
    product = Product(name = request.POST['name'], price = request.POST['price'])
    product.save()
    return render_to_response('product/form.html', {'action': 'add', 'button': 'Dodaj', 'message': 'Dodano produkt'})
Esempio n. 12
0
def create_product_list_from_file(filepath):

    df = pd.read_excel(filepath)

    count = 0
    errors = []

    with transaction.atomic():

        for index, row in df.iterrows():

            brand = row['Бренд']
            model = row['Модель']
            is_published = bool(row['Опубликовано'])
            price = int(row['Цена'])
            purhcase_price = int(row['Оптовая цена'])
            old_price = int(row['Цена до скидки'])
            is_sale = bool(row['Распродажа'])
            is_new = bool(row['Новинка'])
            is_bestseller = bool('Бестселлер')
            series = row['Коллекция']
            is_in_stock = bool(row['В наличии'])

            slug_body = '{brand}-{model}'.format(
                brand=brand,
                model=model,
            )
            slug = slugify(translit(slug_body, 'ru', reversed=True))

            instance = Product(_price=price,
                               brand=brand,
                               series=series,
                               old_price=old_price,
                               is_sale=is_sale,
                               is_new=is_new,
                               is_bestseller=is_bestseller,
                               _purchase_price=purhcase_price,
                               is_published=is_published,
                               model=model,
                               slug=slug,
                               is_in_stock=is_in_stock)

            try:
                instance.full_clean()
                instance.save()
                count += 1
            except Exception as e:
                msg = 'Ошибка для товарной позиции. Модель: {model}'.format(
                    model=model, )
                errors.append(msg)

    value_new = Value.objects.get(attribute__name='Новинка', value_bool=True)

    with transaction.atomic():

        for index, row in df.iterrows():

            model = row['Модель']

            try:
                instance = Product.objects.get(model=model)
            except ObjectDoesNotExist:
                instance = None

            if instance is not None:

                brand = instance.brand
                series = instance.series

            try:
                brand_value = Value.objects.get(attribute__name='Бренд',
                                                value_enum=brand)
                instance.add_value(brand_value)
            except ObjectDoesNotExist:
                msg = 'Бренд: {brand_name} не существует'.format(
                    brand_name=brand)
                errors.append(msg)

            if str(series) != 'nan':
                try:
                    series_value = Value.objects.get(
                        attribute__name='Коллекция', value_enum=series)
                    instance.add_value(series_value)
                except ObjectDoesNotExist:
                    msg = 'Коллекция: {series_name} не существует'.format(
                        series_name=series)
                    errors.append(msg)

            instance.add_value(value_new)

    return {'results': {'count': count, 'errors': errors}}
Esempio n. 13
0
    def trans():
        old_order, team = db.get(
            (old_order_key, RegioManagerTeam.create_key(customer.team_id)))

        if not old_order:
            return BoolReturnStatusTO.create(
                False,
                translate(
                    get_solution_settings(service_user).main_language,
                    SOLUTION_COMMON, u'cart_empty'), False)

        # Duplicate the order
        to_put = list()
        to_delete = list()
        properties = copy_model_properties(old_order)
        properties['status'] = Order.STATUS_SIGNED
        properties['date_signed'] = now()
        new_order_key = Order.create_key(
            customer.id, OrderNumber.next(team.legal_entity_key))
        new_order = Order(key=new_order_key, **properties)
        new_order.team_id = team.id
        to_delete.append(old_order)

        # duplicate all of the order items
        old_order_items = OrderItem.list_by_order(old_order_key)
        all_products = db.get([
            Product.create_key(item.product_code) for item in old_order_items
        ])
        is_subscription_extension_order = False
        for product in all_products:
            if product.is_subscription_extension:
                is_subscription_extension_order = True
                break
        new_order.is_subscription_extension_order = is_subscription_extension_order
        if is_subscription_extension_order:
            subscription_order = Order.get_by_order_number(
                customer.id, customer.subscription_order_number)
            new_order.next_charge_date = subscription_order.next_charge_date
        added_apps = list()
        should_create_shoptask = False
        for old_item in old_order_items:
            properties = copy_model_properties(old_item)
            new_item = OrderItem(parent=new_order_key, **properties)
            to_put.append(new_item)
            to_delete.append(old_item)
            if hasattr(old_item, 'app_id'):
                added_apps.append(old_item.app_id)
            else:
                should_create_shoptask = True
        to_put.append(new_order)
        db.put(to_put)
        db.delete(to_delete)

        deferred.defer(generate_and_put_order_pdf_and_send_mail,
                       customer,
                       new_order_key,
                       service_user,
                       _transactional=True)

        # No need for signing here, immediately create a charge.
        azzert(new_order.total_amount > 0)
        charge = Charge(parent=new_order_key)
        charge.date = now()
        charge.type = Charge.TYPE_ORDER_DELIVERY
        charge.amount = new_order.amount
        charge.vat_pct = new_order.vat_pct
        charge.vat = new_order.vat
        charge.total_amount = new_order.total_amount
        charge.manager = new_order.manager
        charge.team_id = new_order.team_id
        charge.status = Charge.STATUS_PENDING
        charge.date_executed = now()
        charge.currency_code = team.legal_entity.currency_code
        charge.put()

        # Update the regiomanager statistics so these kind of orders show up in the monthly statistics
        deferred.defer(update_regiomanager_statistic,
                       gained_value=new_order.amount / 100,
                       manager=new_order.manager,
                       _transactional=True)

        # Update the customer service
        si = get_default_service_identity(users.User(customer.service_email))
        si.appIds.extend(added_apps)
        si.put()
        deferred.defer(re_index, si.user, _transactional=True)

        # Update the customer object so the newly added apps are added.
        customer.app_ids.extend(added_apps)
        customer.extra_apps_count += len(added_apps)
        customer.put()

        get_payed(customer.id, new_order, charge)
        # charge the credit card
        channel.send_message(service_user, 'common.billing.orders.update')
        channel_data = {
            'customer': customer.name,
            'no_manager': True,
            'amount': charge.amount / 100,
            'currency': charge.currency
        }
        server_settings = get_server_settings()
        send_to = server_settings.supportWorkers
        send_to.append(MC_DASHBOARD.email())
        channel.send_message(map(users.User, send_to),
                             'shop.monitoring.signed_order',
                             info=channel_data)
        if should_create_shoptask:
            prospect_id = customer.prospect_id
            if prospect_id is None:
                prospect = create_prospect_from_customer(customer)
                prospect_id = prospect.id
            deferred.defer(create_task_for_order,
                           customer.team_id,
                           prospect_id,
                           new_order.order_number,
                           _transactional=True)
        return BoolReturnStatusTO.create(True, None)
Esempio n. 14
0
from django.urls import path, include

from blog.models import ArticlePhotoReport
from events.models import Event
from shop.models import Product
from workers.models import Achievement, Person
from .settings import site_name

if not os.path.exists(settings.MEDIA_ROOT):
    os.makedirs(settings.MEDIA_ROOT)

ArticlePhotoReport.all_img_from_binary()
Achievement.all_img_from_binary()
Event.all_img_from_binary()
Person.all_img_from_binary()
Product.all_img_from_binary()

admin.site.site_header = site_name
admin.site.site_title = site_name
admin.site.index_title = "Добро пожаловать в панель настроек " + site_name

urlpatterns = [
                  path('blog/', include('blog.urls')),
                  path('workers/', include('workers.urls')),
                  path('mail/', include('mail.urls')),
                  path('shop/', include('shop.urls')),
                  path('summernote/', include('django_summernote.urls')),
                  path('admin/', admin.site.urls),
                  path('', include('events.urls')),
              ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \
              + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Esempio n. 15
0
        5, 'Shoes', 'Adidas xr1', 'Adidas_xr1',
        'products/2018/04/19/NMD_xr1.jpg', 'Adidas Sports Shoes xr1', 79, 200,
        1
    ],
    [
        6, 'Electronic', 'Samsung S9', 'Samsung_S9',
        'products/2018/04/19/S9.jpg', 'Samsung Galaxy S9', 1099, 150, 0
    ],
]
server = Server()

for pic in pic:
    try:
        p = Product.objects.get(pid=pic[0])
    except:
        p = Product()
        p.pid = pic[0]
        category = pic[1]
        try:
            c = Category.objects.get(name=category)
        except:
            c = Category.objects.create(name=category, slug=category)
        p.category = c
        p.name = pic[2]
        p.slug = pic[3]
        p.image = pic[4]
        p.description = pic[5]
        p.price = pic[6]
        p.stock = pic[7]
        p.whnum = pic[8]
        p.save()
Category.tree.rebuild()

ipsum = '''
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mattis massa rhoncus dolor imperdiet feugiat. Etiam felis enim, interdum pulvinar pharetra ut, blandit sit amet neque. Aliquam semper, nunc nec fermentum dapibus, magna risus posuere quam, vitae tincidunt neque neque eu turpis. Donec convallis posuere mi, non venenatis felis tincidunt vitae. Morbi viverra elementum felis vitae blandit. Aliquam ut elit libero. Proin a dui magna. Morbi non lobortis sapien. Aliquam felis mi, sagittis vel fringilla sed, pellentesque a neque.</p>

	<p>Suspendisse sit amet nulla ut turpis rhoncus congue eget non justo. Sed dignissim ultricies porta. Nam euismod nisi vitae nisi porttitor in pretium risus lacinia. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas eu consequat eros. Etiam ipsum metus, sollicitudin id blandit ut, placerat eget metus. Nunc mi nisi, ultricies in sodales nec, lacinia sed neque. Nulla sodales justo et sapien volutpat nec mattis sapien tristique.</p>

	<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas sed arcu odio, eu sagittis risus. Vestibulum vitae lectus eu nisi imperdiet bibendum vitae ac mauris. Ut a ante eu lorem bibendum gravida quis nec elit. Suspendisse nec tellus velit. Sed at volutpat mi. Duis posuere faucibus venenatis. Proin ante diam, pharetra a vehicula vitae, tempus ac ipsum. Morbi nulla lectus, dapibus vitae sodales non, faucibus eget eros.</p>

	<p>Aenean metus mauris, mollis id ornare quis, facilisis vitae nunc. Aenean rutrum eleifend accumsan. Nulla facilisi. Suspendisse at odio nunc, mollis aliquet justo. Proin consequat condimentum nisl, tincidunt pretium mi egestas consectetur. In porta lorem ut neque rutrum tincidunt. Mauris arcu nibh, lobortis non rutrum id, tempor at massa. Nullam at faucibus ante. Integer tellus lorem, sagittis at gravida ac, pretium semper metus. Mauris sit amet justo lectus, nec convallis metus. Curabitur scelerisque nulla luctus ipsum pulvinar pharetra. Mauris semper nulla vel mauris tempor et ultrices est volutpat. Duis nibh tortor, facilisis at lobortis nec, rutrum vitae enim. Aenean tempor mi et est blandit vel vulputate erat tristique. Ut sed ligula sed nibh accumsan placerat a eget neque. Aliquam vulputate sodales congue.</p>

	<p>Nulla aliquam faucibus dictum. Donec a lectus at nisl rhoncus tincidunt ut sit amet nulla. Morbi eget dui orci, non adipiscing sapien. Suspendisse pharetra vulputate auctor. Aliquam accumsan, justo id interdum mattis, orci mi pretium est, id feugiat nisi nunc vel ante. Duis tincidunt, arcu sit amet imperdiet semper, sem elit pharetra neque, ut consectetur tortor est quis eros. Nulla eget libero non elit gravida auctor. Integer vehicula ullamcorper porta. Donec eleifend facilisis lacus nec condimentum. Pellentesque imperdiet, elit eget bibendum volutpat, neque tortor consectetur mi, a pharetra velit arcu quis purus. Nam consectetur urna felis. Suspendisse condimentum ligula eu mauris laoreet in consequat turpis imperdiet.</p>

	<p>Curabitur sagittis tellus at lectus rutrum tristique. Maecenas viverra, orci ut pulvinar placerat, elit ante suscipit odio, sit amet tempus dui risus vel justo. Quisque eget tellus lacus. Mauris sit amet neque sed nunc malesuada tempor. Aenean malesuada odio non risus interdum eu ultrices metus ornare. Morbi eleifend, diam quis bibendum porttitor, nibh mauris varius erat, ultricies luctus est enim sed diam. Proin pretium porta ornare. Fusce enim nibh, volutpat non vulputate in, dapibus vitae diam. Nulla luctus augue mattis augue ultricies tempus dictum metus malesuada. Fusce velit sem, porttitor eget vehicula in, sagittis at odio. Nullam vitae sapien non quam eleifend dapibus nec sit amet elit. Donec dapibus ultricies odio bibendum aliquet. Vivamus interdum dui in mauris pellentesque elementum. Praesent at nibh et augue facilisis consequat in sit amet libero. Maecenas id felis vel nibh pharetra cursus at sit amet nulla.</p>

	<p>Donec mattis egestas enim eu accumsan. Curabitur posuere purus mollis massa ullamcorper ac tempus mauris blandit. Sed nunc nisi, pharetra et fringilla a, vestibulum cursus metus. Etiam porttitor, purus in tempor imperdiet, ligula purus mollis felis, id tincidunt enim tellus quis nibh. Vestibulum nec mi ante. Nam dapibus nisi sed justo dignissim in euismod eros consectetur. Suspendisse tincidunt orci et eros dapibus eu ornare metus tempor. Quisque nec iaculis ligula. Quisque in vehicula turpis. Integer vehicula, dui ac lobortis vestibulum, erat augue volutpat turpis, nec tristique leo leo eget neque.</p>

	<p>Mauris vitae lectus et velit imperdiet scelerisque at id metus. Etiam viverra convallis neque, at sollicitudin orci interdum nec. Nulla purus odio, tempor non pellentesque nec, luctus eget magna. Suspendisse non erat augue, sit amet porttitor ligula. Quisque at orci ante. Aliquam vitae ligula dui. Praesent aliquam, eros nec commodo dignissim, nisi ipsum rutrum sapien, vel tincidunt tortor tellus sed velit. Quisque laoreet ipsum at risus tempus at rhoncus erat mattis. Praesent nec viverra diam. Quisque ut nisi cursus sem scelerisque rhoncus non non massa. Nunc eu leo augue, quis tristique libero. Vivamus a eros ut libero dapibus ultrices id sit amet magna. Suspendisse commodo congue mi, et varius dui vehicula sit amet. Aliquam dignissim gravida sapien, ut laoreet nibh rutrum sed.</p>

	<p>Aenean vitae adipiscing leo. Pellentesque ligula mi, scelerisque at molestie eget, lobortis porta ante. Maecenas sapien mauris, tempor et ornare nec, viverra rhoncus dui. Etiam neque lacus, hendrerit et blandit sit amet, imperdiet et turpis. Nunc elementum convallis libero in faucibus. Sed ullamcorper turpis sit amet ipsum tristique sed pretium lacus fermentum. Nunc tempus sagittis tortor, sed varius nibh sollicitudin ut. Nulla ac suscipit mauris. Fusce in sapien purus. Integer mauris est, auctor ac ultrices at, vehicula mollis justo. Duis venenatis facilisis mollis.</p>

	<p>In congue euismod nulla, id commodo odio hendrerit a. Aliquam feugiat cursus convallis. Nulla nec elit consectetur metus aliquam egestas. Pellentesque laoreet velit sed nunc posuere eget gravida magna condimentum. Duis at metus tortor, eu vestibulum dui. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In volutpat lorem vel mi interdum pretium molestie justo pulvinar. Fusce laoreet adipiscing quam, quis fermentum ante lacinia eu. Vivamus eleifend auctor turpis a dictum. Nam in purus quis diam blandit suscipit vitae in erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque eu nulla et nunc porta mollis lobortis et quam.</p>'''

lorem = ipsum.split('</p>')
for i in lorem:
    category = Category.objects.order_by('?')[0]
    name = strip_tags(i).strip()[:20]
    slug = slugify(name)
    product = Product(name=name, slug=slug, active=True, body=i, unit_price=Decimal(random.randint(50, 1000)), main_category=category, weigth_in_grams=250)
    product.save()
    product.additional_categories.add(category)
Esempio n. 17
0
    def test_str(self):
        a_product = Product(name='Stül')

        self.assertEqual(str(a_product), 'Stül')
Esempio n. 18
0
def create_reseller_invoice_for_legal_entity(legal_entity,
                                             start_date,
                                             end_date,
                                             do_send_email=True):
    """
    Args:
        legal_entity (LegalEntity) 
        start_date (long)
        end_date (long)
        do_send_email (bool)
    """
    if legal_entity.is_mobicage:
        # To avoid a composite index we don't filter on is_mobicage
        return
    solution_server_settings = get_solution_server_settings()
    from_email = solution_server_settings.shop_no_reply_email
    to_emails = solution_server_settings.shop_payment_admin_emails
    mobicage_legal_entity = get_mobicage_legal_entity()
    logging.info(
        'Exporting reseller invoices for legal entity %s(id %d) from %s(%s) to %s(%s)',
        legal_entity.name, legal_entity.id, start_date, time.ctime(start_date),
        end_date, time.ctime(end_date))
    invoices = list(Invoice.all().filter(
        'legal_entity_id',
        legal_entity.id).filter('paid_timestamp >', start_date).filter(
            'paid_timestamp <', end_date).filter('paid', True).filter(
                'payment_type IN',
                (Invoice.PAYMENT_MANUAL, Invoice.PAYMENT_MANUAL_AFTER)))
    start_time = time.strftime('%m/%d/%Y', time.gmtime(int(start_date)))
    end_time = time.strftime('%m/%d/%Y', time.gmtime(int(end_date)))
    if not invoices:
        message = 'No new invoices for reseller %s for period %s - %s' % (
            legal_entity.name, start_time, end_time)
        logging.info(message)
        if do_send_email:
            send_mail(from_email, to_emails, message, message)
        return
    items_per_customer = {}
    customers_to_get = set()
    products = {
        p.code: p
        for p in Product.list_by_legal_entity(legal_entity.id)
    }
    for invoice in invoices:
        # get all subscription order items
        order_items = list(OrderItem.list_by_order(invoice.order_key))
        for item in reversed(order_items):
            product = products[item.product_code]
            # We're only interested in subscription items
            if product.is_subscription or product.is_subscription_extension or product.is_subscription_discount:
                if invoice.customer_id not in items_per_customer:
                    items_per_customer[invoice.customer_id] = []
                    customers_to_get.add(
                        Customer.create_key(invoice.customer_id))
                items_per_customer[invoice.customer_id].append(item)
            else:
                order_items.remove(item)
    if not customers_to_get:
        message = 'No new invoices containing subscriptions for reseller %s for period %s - %s' % (
            legal_entity.name, start_time, end_time)
        logging.info(message)
        if do_send_email:
            send_mail(from_email, to_emails, message, message)
        return
    customers = {c.id: c for c in db.get(customers_to_get)}
    product_totals = {}
    for customer_id in items_per_customer:
        items = items_per_customer[customer_id]
        for item in items:
            if item.product_code not in product_totals:
                product_totals[item.product_code] = {
                    'count': 0,
                    'price': int(item.price * legal_entity.revenue_percent)
                }
            product_totals[item.product_code]['count'] += item.count
    total_amount = 0
    for product in product_totals:
        p = product_totals[product]
        price = p['count'] * p['price']
        p['total_price'] = format_currency(
            price / 100.,
            legal_entity.currency_code,
            locale=mobicage_legal_entity.country_code)
        total_amount += price
    total_amount_formatted = format_currency(
        total_amount / 100.,
        legal_entity.currency_code,
        locale=mobicage_legal_entity.country_code)
    vat_amount = total_amount / mobicage_legal_entity.vat_percent if mobicage_legal_entity.country_code == legal_entity.country_code else 0
    vat_amount_formatted = format_currency(
        vat_amount / 100.,
        legal_entity.currency_code,
        locale=mobicage_legal_entity.country_code)
    from_date = format_datetime(datetime.utcfromtimestamp(start_date),
                                locale=SHOP_DEFAULT_LANGUAGE,
                                format='dd/MM/yyyy HH:mm')
    until_date = format_datetime(datetime.utcfromtimestamp(end_date),
                                 locale=SHOP_DEFAULT_LANGUAGE,
                                 format='dd/MM/yyyy HH:mm')

    solution_server_settings = get_solution_server_settings()
    template_variables = {
        'products':
        products,
        'customers':
        customers,
        'invoices':
        invoices,
        'items_per_customer':
        items_per_customer,
        'product_totals':
        product_totals.items(),
        'mobicage_legal_entity':
        mobicage_legal_entity,
        'legal_entity':
        legal_entity,
        'language':
        SHOP_DEFAULT_LANGUAGE,
        'from_date':
        from_date,
        'until_date':
        until_date,
        'revenue_percent':
        legal_entity.revenue_percent,
        'vat_amount_formatted':
        vat_amount_formatted,
        'total_amount_formatted':
        total_amount_formatted,
        'logo_path':
        '../html/img/osa_white_en_250.jpg',
        'tos_link':
        '<a href="%s">%s</a>' %
        (solution_server_settings.shop_privacy_policy_url,
         solution_server_settings.shop_privacy_policy_url)
    }
    source_html = SHOP_JINJA_ENVIRONMENT.get_template(
        'invoice/reseller_invoice.html').render(template_variables)
    output_stream = StringIO()
    pisa.CreatePDF(src=source_html,
                   dest=output_stream,
                   path='%s/invoice' % SHOP_TEMPLATES_FOLDER)
    invoice_pdf_contents = output_stream.getvalue()
    output_stream.close()
    # Create an order, order items, charge and invoice.
    _now = now()
    customer = legal_entity.get_or_create_customer()
    mobicage_team = RegioManagerTeam.get_mobicage()

    def trans():
        to_put = list()
        order_number = OrderNumber.next(mobicage_legal_entity)
        order_key = db.Key.from_path(Order.kind(),
                                     order_number,
                                     parent=customer.key())
        order = Order(key=order_key)
        order.contact_id = legal_entity.contact_id
        order.date = _now
        order.vat_pct = mobicage_legal_entity.vat_percent if legal_entity.country_code == mobicage_legal_entity.country_code else 0
        order.amount = int(round(total_amount))
        order.vat = int(round(vat_amount))
        order.total_amount = int(round(total_amount + vat_amount))
        order.is_subscription_order = False
        order.is_subscription_extension_order = False
        order.team_id = mobicage_team.id
        order.manager = customer.manager
        order.status = Order.STATUS_SIGNED
        to_put.append(order)

        for i, (product_code, item) in enumerate(product_totals.iteritems()):
            order_item = OrderItem(parent=order_key)
            order_item.number = i + 1
            order_item.comment = products[product_code].default_comment(
                SHOP_DEFAULT_LANGUAGE)
            order_item.product_code = product_code
            order_item.count = item['count']
            order_item.price = item['price']
            to_put.append(order_item)

        charge_key = Charge.create_key(allocate_id(Charge), order_number,
                                       customer.id)
        charge = Charge(key=charge_key)
        charge.date = _now
        charge.type = Charge.TYPE_ORDER_DELIVERY
        charge.amount = order.amount
        charge.vat_pct = order.vat_pct
        charge.vat = order.vat
        charge.total_amount = order.total_amount
        charge.manager = order.manager
        charge.team_id = order.team_id
        charge.charge_number = ChargeNumber.next(mobicage_legal_entity)
        charge.currency_code = legal_entity.currency_code
        to_put.append(charge)

        invoice_number = InvoiceNumber.next(mobicage_legal_entity)
        invoice = Invoice(key_name=invoice_number,
                          parent=charge,
                          amount=charge.amount,
                          vat_pct=charge.vat_pct,
                          vat=charge.vat,
                          total_amount=charge.total_amount,
                          currency_code=legal_entity.currency_code,
                          date=_now,
                          payment_type=Invoice.PAYMENT_MANUAL_AFTER,
                          operator=charge.manager,
                          paid=False,
                          legal_entity_id=mobicage_legal_entity.id,
                          pdf=invoice_pdf_contents)
        charge.invoice_number = invoice_number
        to_put.append(invoice)
        put_and_invalidate_cache(*to_put)
        return order, charge, invoice

    order, charge, invoice = run_in_xg_transaction(trans)

    if do_send_email:
        serving_url = '%s/internal/shop/invoice/pdf?customer_id=%d&order_number=%s&charge_id=%d&invoice_number=%s' % (
            get_server_settings().baseUrl, customer.id, order.order_number,
            charge.id, invoice.invoice_number)
        subject = 'New reseller invoice for %s, %s - %s' % (
            legal_entity.name, start_time, end_time)
        body_text = 'A new invoice is available for reseller %s for period %s to %s here: %s' % (
            legal_entity.name, start_time, end_time, serving_url)

        send_mail(from_email, to_emails, subject, body_text)
Esempio n. 19
0
	def get_context_data(self,*args, **kwargs):
		serial_num = Product.ran_gen_serial_num()
		context = super(ProductCreateView,self).get_context_data(*args,**kwargs)
		context['serial_num'] = serial_num
		return context
    def update(self, request, *args, **kwargs):
        """
        제품 데이터 수정
        """
        product_id = request.data['id']
        #json데이터를 객체로 역직렬화
        product_data = json.loads(request.data['product'])        
        file_list = request.FILES.getlist('photos')

        #업로드된 이미지 파일 저장
        photo_urls = product_data["photo_urls"]

        photo_urls = photo_urls + \
            self.__get_product_images(product_id, file_list)

        #원래 등록되어 있었던 이미지 목록 조회
        original_images = \
            ProductImage.objects.filter(product_id=product_id)
        
        #삭제된 이미지 삭제 처리
        for oi in original_images:
            if oi.photo_url not in photo_urls:
                oi.delete()
        
        #새로 추가된 이미지 추가
        self.__add_product_images(product_id, photo_urls)        

        category_ids = product_data["category_ids"]
        
        #원래 등록되어 있었던 분류 목록 조회
        original_categories =\
            ProductCategory.objects.filter(product_id=product_id)

        #삭제된 분류 삭제
        for oc in original_categories:
            if oc.category_id not in category_ids:
                oc.delete()

        #새로 추가된 분류 추가
        self.__add_product_categories(
            product_id, 
            category_ids)

        #제품 데이터 검증 및 모델 객체 생성
        serializer = ProductSerializer(data=product_data)
        if serializer.is_valid():
            validated_data = serializer.validated_data
            #모델에 포함되지 않은 속성은 삭제
            del validated_data["category_ids"]
            #데이터에서 모델 객체 생성
            product = Product(**serializer.validated_data)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        
        #생성일은 변경하지 않도록 처리
        del product.createdDate
        product.modifiedDate = datetime.now()
        product.save()
        
        return Response({
            "id": product.id
        })
Esempio n. 21
0
from shop.models import Category, Product
c1 = Category(name="Mobile Devices")
c1.save()
c2 = Category(name="Computers")
c2.save()
p1 = Product(
    name="Apple iPhone X",
    price=1149.99,
    stock=12,
    description=
    "iPhone X features a new all-screen design. FaceID, which makes your face your password. And the most powerful and smartest chip ever in a smartphone.",
    category=c1)
p1.save()
p2 = Product(
    name="Google Pixel2",
    price=860.20,
    stock=14,
    description=
    "The unlocked Pixel 2 provides a clean, bloat-free experience with no unwanted apps, one of the highest rated smartphone cameras, with free unlimited storage.",
    category=c1)
p2.save()
p3 = Product(
    name="Sony Xperia ZX2",
    price=920.49,
    stock=9,
    description=
    "The Xperia XZ2 is packed with the latest Sony technologies to deliver an entertainment experience that touches your senses in a whole new way – whether you’re lost in a HDR movie or capturing hidden details with the new advanced Motion Eye™ camera.",
    category=c1)
p3.save()
p4 = Product(
    name="Dell Inspiron 175000",
    def trans():
        charge = None
        expired_subscription, customer = db.get([ExpiredSubscription.create_key(customer_id),
                                                       Customer.create_key(customer_id)])
        expired_subscription.status = status
        expired_subscription.status_updated_timestamp = now()

        if status == ExpiredSubscription.STATUS_WILL_LINK_CREDIT_CARD:
            # Create a task for regiomanager to check if the customer has linked his credit card after two weeks.
            # the ExpiredSubscription object from this customer will be cleaned up in recurrentbilling the day after he has linked it.
            to_put.append(expired_subscription)
            team, prospect = db.get([RegioManagerTeam.create_key(customer.team_id),
                                     Prospect.create_key(customer.prospect_id)])
            execution_time = now() + DAY * 14
            date_string = datetime.datetime.utcfromtimestamp(execution_time).strftime(u'%A %d %b %Y')
            comment = u'Check if the customer has linked his creditcard (for automatic subscription renewal).' \
                      u' If he hasn\'t linked it before %s, contact him again.' % date_string
            task = create_task(current_user.email(), prospect, team.support_manager, execution_time,
                               ShopTask.TYPE_CHECK_CREDIT_CARD, prospect.app_id, comment=comment)
            to_put.append(task)

        elif status == ExpiredSubscription.STATUS_EXTEND_SUBSCRIPTION:
            # Creates a new charge using the customer his subscription order.
            subscription_order, team = db.get([Order.create_key(customer.id, customer.subscription_order_number),
                                               RegioManagerTeam.create_key(customer.team_id)])
            extension_order_item_keys = list()
            order_items = list(OrderItem.list_by_order(subscription_order.key()))
            products_to_get = list()
            for item in order_items:
                products_to_get.append(Product.create_key(item.product_code))
            products = {p.code: p for p in Product.get(products_to_get)}
            # extend per year
            months = 12
            total_amount = 0
            for item in order_items:
                product = products[item.product_code]
                if product.is_subscription and item.price > 0:
                    total_amount += months * item.price
                elif not product.is_subscription and (product.is_subscription_discount or product.extra_subscription_months > 0):
                    total_amount += months * item.price
                elif product.is_subscription_extension:
                    total_amount += months * item.price
                    extension_order_item_keys.append(item.key())

            if total_amount <= 0:
                raise BusinessException('The created charge has a negative amount (%d)' % total_amount)
            next_charge_datetime = datetime.datetime.utcfromtimestamp(now()) + relativedelta(months=months)
            subscription_order.next_charge_date = get_epoch_from_datetime(next_charge_datetime)
            to_put.append(subscription_order)

            # reconnect all previously connected friends if the service was disabled in the past
            if customer.service_disabled_at != 0:
                deferred.defer(set_service_enabled, customer.id, _transactional=True)

            vat_pct = get_vat_pct(customer, team)
            charge = Charge(parent=subscription_order)
            charge.date = now()
            charge.type = Charge.TYPE_SUBSCRIPTION_EXTENSION
            charge.subscription_extension_length = months
            charge.subscription_extension_order_item_keys = extension_order_item_keys
            charge.amount = total_amount
            charge.vat_pct = vat_pct
            charge.vat = int(total_amount * vat_pct / 100)
            charge.total_amount = charge.amount + charge.vat
            charge.currency_code = team.legal_entity.currency_code
            to_put.append(charge)
            to_delete.append(expired_subscription)

        db.put(to_put)
        if to_delete:
            db.delete(to_delete)

        return charge
Esempio n. 23
0
 def handle(self, *args, **options):
     d = Product.objects.all()
     d.delete()
     for c in ShopProduct.objects.using('old').all():
         category = Category.objects.filter(pk=c.category_id).first()
         prod = Product.objects.filter(category=category,
                                       slug=c.slug).first()
         if not prod:
             prod = Product(pk=c.pk)
         prod.name = c.name
         prod.category = category
         prod.slug = c.slug
         prod.title = c.title
         prod.description = c.metadesc
         prod.keywords = c.metakey
         prod.price = c.price
         prod.image = c.image
         prod.description = c.description
         prod.full_text = c.full_text
         prod.save()
         print(prod.id)
Esempio n. 24
0
def product_add_view(request):
    get_permission(request)
    if request.method == 'POST':
        user = request.user
        product_form = ProductForm(request.POST)

        type_post = request.POST.get('type_post')

        EmptySizeFormSet = modelformset_factory(ProductSize,
                                                form=SizeForm,
                                                can_delete=True)
        empty_size_formset = EmptySizeFormSet(request.POST,
                                              prefix="empty_form")

        if product_form.is_valid() and empty_size_formset.is_valid():

            if type_post == "check_form":
                return JsonResponse({'result': 'success_check_form'})
            elif type_post == "confirm_form":

                new_product = Product()
                product_form.save(new_product, request, user)

                empty_size_formset.save(commit=False)

                for object in empty_size_formset.new_objects:
                    object.product = new_product
                    object.save()

                products = Product.objects.all()
                main_product_response = render_template(
                    'shopadmin_product_main.html', {'products': products},
                    request)
                EmptySizeFormSet = modelformset_factory(ProductSize,
                                                        form=SizeForm,
                                                        can_delete=True,
                                                        extra=3)
                empty_size_formset = EmptySizeFormSet(
                    queryset=ProductSize.objects.none(), prefix="empty_form")
                photos = None
                product_form_response = render_template(
                    'shopadmin_product_form.html', {
                        'product_form': ProductForm(),
                        'empty_size_formset': empty_size_formset,
                        'photos': photos
                    }, request)
                return JsonResponse({
                    'product_form_response':
                    product_form_response,
                    'main_product_response':
                    main_product_response,
                    'result':
                    'success',
                    'message':
                    message("Продукт добавлен!", request)
                })
        else:
            photos = None
            product_form_response = render_template(
                'shopadmin_product_form.html', {
                    'product_form': product_form,
                    'empty_size_formset': empty_size_formset,
                    'photos': photos
                }, request)
            return JsonResponse({
                'product_form_response': product_form_response,
                'result': 'error'
            })
Esempio n. 25
0
def export_invoices(year, month):
    start_date = datetime.date(year, month, 1)
    end_date = start_date + relativedelta(months=1)

    qry = Invoice.all() \
        .filter('date >=', get_epoch_from_datetime(start_date)) \
        .filter('date <', get_epoch_from_datetime(end_date))

    invoices = list()
    order_keys = set()
    all_products = dict(((p.code, p) for p in Product.all()))
    for invoice_model in qry:
        i = model_to_dict(invoice_model)
        order_key = invoice_model.parent_key().parent()
        i['invoice_number'] = invoice_model.invoice_number
        i['order_items'] = map(model_to_dict,
                               OrderItem.all().ancestor(order_key))
        if invoice_model.charge.is_recurrent:
            # only apply recurrent charges
            for order_item in reversed(i['order_items']):
                order_item[
                    'count'] = invoice_model.charge.subscription_extension_length or 1
                product = all_products[order_item['product_code']]
                if not (product.is_subscription_discount
                        or product.is_subscription
                        or product.is_subscription_extension):
                    i['order_items'].remove(order_item)

            # add the subscription extensions like XCTY
            if invoice_model.charge.subscription_extension_order_item_keys:
                known_extension_item_keys = [
                    item['_key'] for item in i['order_items']
                ]

                extension_order_items = db.get(
                    invoice_model.charge.subscription_extension_order_item_keys
                )
                for item in extension_order_items:
                    item.count = 1
                    if str(item.key()) not in known_extension_item_keys:
                        i['order_items'].append(model_to_dict(item))

        i['order_key'] = order_key
        i['currency'] = invoice_model.currency_code
        order_keys.add(order_key)
        invoices.append(i)

    orders = {o.key(): o for o in db.get(order_keys)}

    contact_keys = set()
    customer_keys = set()
    for i in invoices:
        order_model = orders[i['order_key']]
        del i['order_key']
        i['customer_key'] = order_model.customer_key
        i['contact_key'] = order_model.contact_key
        i['manager'] = None if not order_model.manager else order_model.manager.email(
        )
        customer_keys.add(order_model.customer_key)
        contact_keys.add(order_model.contact_key)

    del orders

    customer_and_contact_models = {
        m.key(): m
        for m in db.get(customer_keys.union(contact_keys))
    }

    # filter invoices for customers of resellers
    reseller_ids = [
        k.id() for k in LegalEntity.list_non_mobicage(keys_only=True)
    ]
    reseller_team_ids = [
        t.id for t in RegioManagerTeam.all().filter('legal_entity_id IN',
                                                    reseller_ids)
    ]

    for i in reversed(invoices):
        customer_model = customer_and_contact_models[i['customer_key']]
        if customer_model.team_id in reseller_team_ids:
            invoices.remove(i)
            continue
        del i['customer_key']
        i['customer'] = model_to_dict(customer_model)
        contact_model = customer_and_contact_models[i['contact_key']]
        del i['contact_key']
        i['contact'] = model_to_dict(contact_model)

    del customer_and_contact_models

    return sorted(invoices,
                  key=lambda i: int(i['invoice_number'].split('.')[-1]))
Esempio n. 26
0
def create_news_product(legal_entity_id, code_prefix=''):
    p = Product(key_name=code_prefix + Product.PRODUCT_NEWS_PROMOTION)
    p.price = 1
    p.default_count = 1
    p.default = False
    p.possible_counts = []
    p.is_subscription = False
    p.organization_types = []
    p.product_dependencies = []
    p.visible = False  # Only orderable via dashboard when creating a newsfeed item
    p.legal_entity_id = legal_entity_id
    if code_prefix:
        p.description_translation_key = p.code[len(code_prefix
                                                   ):] + '.description'
        p.default_comment_translation_key = p.code[len(code_prefix
                                                       ):] + '.default_comment'
    return p
	<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Maecenas sed arcu odio, eu sagittis risus. Vestibulum vitae lectus eu nisi imperdiet bibendum vitae ac mauris. Ut a ante eu lorem bibendum gravida quis nec elit. Suspendisse nec tellus velit. Sed at volutpat mi. Duis posuere faucibus venenatis. Proin ante diam, pharetra a vehicula vitae, tempus ac ipsum. Morbi nulla lectus, dapibus vitae sodales non, faucibus eget eros.</p>

	<p>Aenean metus mauris, mollis id ornare quis, facilisis vitae nunc. Aenean rutrum eleifend accumsan. Nulla facilisi. Suspendisse at odio nunc, mollis aliquet justo. Proin consequat condimentum nisl, tincidunt pretium mi egestas consectetur. In porta lorem ut neque rutrum tincidunt. Mauris arcu nibh, lobortis non rutrum id, tempor at massa. Nullam at faucibus ante. Integer tellus lorem, sagittis at gravida ac, pretium semper metus. Mauris sit amet justo lectus, nec convallis metus. Curabitur scelerisque nulla luctus ipsum pulvinar pharetra. Mauris semper nulla vel mauris tempor et ultrices est volutpat. Duis nibh tortor, facilisis at lobortis nec, rutrum vitae enim. Aenean tempor mi et est blandit vel vulputate erat tristique. Ut sed ligula sed nibh accumsan placerat a eget neque. Aliquam vulputate sodales congue.</p>

	<p>Nulla aliquam faucibus dictum. Donec a lectus at nisl rhoncus tincidunt ut sit amet nulla. Morbi eget dui orci, non adipiscing sapien. Suspendisse pharetra vulputate auctor. Aliquam accumsan, justo id interdum mattis, orci mi pretium est, id feugiat nisi nunc vel ante. Duis tincidunt, arcu sit amet imperdiet semper, sem elit pharetra neque, ut consectetur tortor est quis eros. Nulla eget libero non elit gravida auctor. Integer vehicula ullamcorper porta. Donec eleifend facilisis lacus nec condimentum. Pellentesque imperdiet, elit eget bibendum volutpat, neque tortor consectetur mi, a pharetra velit arcu quis purus. Nam consectetur urna felis. Suspendisse condimentum ligula eu mauris laoreet in consequat turpis imperdiet.</p>

	<p>Curabitur sagittis tellus at lectus rutrum tristique. Maecenas viverra, orci ut pulvinar placerat, elit ante suscipit odio, sit amet tempus dui risus vel justo. Quisque eget tellus lacus. Mauris sit amet neque sed nunc malesuada tempor. Aenean malesuada odio non risus interdum eu ultrices metus ornare. Morbi eleifend, diam quis bibendum porttitor, nibh mauris varius erat, ultricies luctus est enim sed diam. Proin pretium porta ornare. Fusce enim nibh, volutpat non vulputate in, dapibus vitae diam. Nulla luctus augue mattis augue ultricies tempus dictum metus malesuada. Fusce velit sem, porttitor eget vehicula in, sagittis at odio. Nullam vitae sapien non quam eleifend dapibus nec sit amet elit. Donec dapibus ultricies odio bibendum aliquet. Vivamus interdum dui in mauris pellentesque elementum. Praesent at nibh et augue facilisis consequat in sit amet libero. Maecenas id felis vel nibh pharetra cursus at sit amet nulla.</p>

	<p>Donec mattis egestas enim eu accumsan. Curabitur posuere purus mollis massa ullamcorper ac tempus mauris blandit. Sed nunc nisi, pharetra et fringilla a, vestibulum cursus metus. Etiam porttitor, purus in tempor imperdiet, ligula purus mollis felis, id tincidunt enim tellus quis nibh. Vestibulum nec mi ante. Nam dapibus nisi sed justo dignissim in euismod eros consectetur. Suspendisse tincidunt orci et eros dapibus eu ornare metus tempor. Quisque nec iaculis ligula. Quisque in vehicula turpis. Integer vehicula, dui ac lobortis vestibulum, erat augue volutpat turpis, nec tristique leo leo eget neque.</p>

	<p>Mauris vitae lectus et velit imperdiet scelerisque at id metus. Etiam viverra convallis neque, at sollicitudin orci interdum nec. Nulla purus odio, tempor non pellentesque nec, luctus eget magna. Suspendisse non erat augue, sit amet porttitor ligula. Quisque at orci ante. Aliquam vitae ligula dui. Praesent aliquam, eros nec commodo dignissim, nisi ipsum rutrum sapien, vel tincidunt tortor tellus sed velit. Quisque laoreet ipsum at risus tempus at rhoncus erat mattis. Praesent nec viverra diam. Quisque ut nisi cursus sem scelerisque rhoncus non non massa. Nunc eu leo augue, quis tristique libero. Vivamus a eros ut libero dapibus ultrices id sit amet magna. Suspendisse commodo congue mi, et varius dui vehicula sit amet. Aliquam dignissim gravida sapien, ut laoreet nibh rutrum sed.</p>

	<p>Aenean vitae adipiscing leo. Pellentesque ligula mi, scelerisque at molestie eget, lobortis porta ante. Maecenas sapien mauris, tempor et ornare nec, viverra rhoncus dui. Etiam neque lacus, hendrerit et blandit sit amet, imperdiet et turpis. Nunc elementum convallis libero in faucibus. Sed ullamcorper turpis sit amet ipsum tristique sed pretium lacus fermentum. Nunc tempus sagittis tortor, sed varius nibh sollicitudin ut. Nulla ac suscipit mauris. Fusce in sapien purus. Integer mauris est, auctor ac ultrices at, vehicula mollis justo. Duis venenatis facilisis mollis.</p>

	<p>In congue euismod nulla, id commodo odio hendrerit a. Aliquam feugiat cursus convallis. Nulla nec elit consectetur metus aliquam egestas. Pellentesque laoreet velit sed nunc posuere eget gravida magna condimentum. Duis at metus tortor, eu vestibulum dui. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In volutpat lorem vel mi interdum pretium molestie justo pulvinar. Fusce laoreet adipiscing quam, quis fermentum ante lacinia eu. Vivamus eleifend auctor turpis a dictum. Nam in purus quis diam blandit suscipit vitae in erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Quisque eu nulla et nunc porta mollis lobortis et quam.</p>'''

lorem = ipsum.split('</p>')
for i in lorem:
    category = Category.objects.order_by('?')[0]
    name = strip_tags(i).strip()[:20]
    slug = slugify(name)
    product = Product(name=name,
                      slug=slug,
                      active=True,
                      body=i,
                      unit_price=Decimal(random.randint(50, 1000)),
                      main_category=category,
                      weigth_in_grams=250)
    product.save()
    product.additional_categories.add(category)
Esempio n. 28
0
def create_fcty_product(legal_entity_id, code_prefix=''):
    p = Product(key_name=code_prefix + 'FCTY')
    p.price = 0
    p.default_count = 1
    p.default = False
    p.possible_counts = [1]
    p.is_subscription = True
    p.is_subscription_discount = False
    p.module_set = 'ALL'
    p.organization_types = [ServiceProfile.ORGANIZATION_TYPE_CITY]
    p.product_dependencies = []
    p.visible = True
    p.legal_entity_id = legal_entity_id
    if code_prefix:
        p.description_translation_key = p.code[len(code_prefix
                                                   ):] + '.description'
        p.default_comment_translation_key = p.code[len(code_prefix
                                                       ):] + '.default_comment'
    return p
Esempio n. 29
0
def job():
    default_next_charge_date = Order.default_next_charge_date()
    all_products = {p.code: p for p in Product.all()}
    run_job(_all_subscription_orders, [],
            _update_next_charge_date, [default_next_charge_date, all_products],
            worker_queue=MIGRATION_QUEUE)
Esempio n. 30
0
 def test_string_representation(self):
     product = Product(name='red tea')
     self.assertEqual(str(product), product.name)
Esempio n. 31
0
def UpLoadDataFromCsv(path=mypath):
    writeCsvFiles(path)
    with open('list.csv', 'rb') as csvfile:
        rows = csv.DictReader(x.replace('', '') for x in csvfile)
        for row in rows:
            try:
                Navbar.objects.get(name=row['navbar'])
                try:
                    category = Category.objects.get(name=row['category'])
                    try:
                        Product.objects.get(name=row['name'])
                        continue
                    except Product.DoesNotExist:
                        product = Product(category=category,
                                          name=row['name'],
                                          kilometers=row['kilometers'],
                                          price=row['price'],
                                          stock=['stock'],
                                          available=row['available'])
                        name = row['name']
                        dir = row['directory']
                        product.image = ImageFile(open(dir, 'rb'))
                        product.save()
                        #product.image.save(File(open(dir,'rb')))
                        #product.image.save(name,File(open(dir,'r')))
                        #image = ImageFile(open("".join(row['directory']),"r"))
                        #product = Product(category=category,name=row['name'],image=image,kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available'])
                        #product = Product(category=category,name=row['name'],kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available'])
                        #product.image = ImageFile(open("".join(row['directory']),"r"))
                        #product.image = "products/".join(row['directory'])
                        #product.save()
                except Category.DoesNotExist:
                    category = Category(navbar=nav, name=row['category'])
                    category.save()
                    product = Product(category=category,
                                      name=row['name'],
                                      kilometers=row['kilometers'],
                                      price=row['price'],
                                      stock=['stock'],
                                      available=row['available'])
                    name = row['name']
                    dir = row['directory']
                    product.image.save(name, File(open(dir, 'rb')))
                    #product.image.save(row['name'].join('.jpg'),File(open(row['directory'],'r')))
                    #product = Product(category=category,name=row['name'],kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available'])
                    #product.image = ImageFile(open("".join(row['directory']),"r"))
                    #product.image = "products/".join(row['directory'])
                    #product.save()
            except Navbar.DoesNotExist:
                nav = Navbar(name=row['navbar'])
                nav.save()
                #createProduct(nav,row['category'])
                category = Category(navbar=nav, name=row['category'])
                category.save()
                name = row['name']
                dir = row['directory']
                product = Product(category=category,
                                  name=row['name'],
                                  kilometers=row['kilometers'],
                                  price=row['price'],
                                  stock=['stock'],
                                  available=row['available'])
                product.image.save(name, File(open(dir, 'rb')))
                #product.image.save(row['name'].join('.jpg'),File(open(row['directory'],'r')))
                #product = Product(category=category,name=row['name'],kilometers=row['kilometers'],price=row['price'],stock=['stock'],available=row['available'])
                #product.image = ImageFile(open("".join(row['directory']),"r"))
                #product.image = "products/".join(row['directory'])
                #product.save()
    csvfile.close()