Ejemplo n.º 1
0
    def setUp(self):
        """
        """
        self.tax = TaxClass(name="20%", rate=Decimal('20.0'))
        self.tax.save()
        self.p1 = Product.objects.create(name="Product 1", slug="product-1")
        self.p2 = Product.objects.create(name="Product 2", slug="product-2")
        self.p1.save()
        self.p2.save()

        price1 = ProductPrice(product=self.p1,
                              _unit_price=Decimal('10.0'),
                              currency='CZK',
                              tax_class=self.tax,
                              tax_included=self.tax_included)
        price2 = ProductPrice(product=self.p2,
                              _unit_price=Decimal('100.0'),
                              currency='CZK',
                              tax_class=self.tax,
                              tax_included=self.tax_included)
        price1.save()
        price2.save()

        self.cart = Order()
        self.cart.save()

        item1 = OrderItem(order=self.cart, product=self.p1, quantity=1)
        item2 = OrderItem(order=self.cart, product=self.p2, quantity=1)
        item1.save()
        item2.save()

        self.cart.recalculate_totals()
        self.cart.save()
Ejemplo n.º 2
0
def add_to_cart(req, product_id, quantity=1):
    try:
        props = json.loads(req.GET['props'])
    except:
        props = []

    if not props:
        props = []

    product = Product.objects.get(id=product_id)

    order_item = OrderItem()
    order_item.product = product
    order_item.save()

    for prop in props:
        pps = list(
            ProductProp.objects.filter(title=prop['name'],
                                       product_id=product.id,
                                       value=prop['value']))
        if len(pps):
            pp = pps[0]
            order_item.props.add(pp)

    cart = Cart(req)
    cart.add(order_item, product.price, quantity)
    return JsonResponse({'success': True, 'count': cart.count()})
Ejemplo n.º 3
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')
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
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)
Ejemplo 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
Ejemplo n.º 7
0
def create_order(request):
    data = copy.deepcopy(request.data)
    request_serializer = CreateNewOrderSerializer(data=data)
    request_serializer.is_valid(raise_exception=True)

    user = request.user
    person = Person.objects.get(user=user)

    try:
        # Create the initial order
        items = []
        for order_item in data['order_items']:
            items.append({
                "type": 'sku',
                "parent": order_item['parent'],
                "quantity": order_item['quantity']
            })

        stripe.api_key = settings.STRIPE_PRIVATE_KEY
        stripe_order = stripe.Order.create(
            currency='usd',
            items=items,
            shipping={
                "name": '%s %s' % (user.first_name, user.last_name),
                "address": {
                    "line1": person.address_line_1,
                    "city": person.city,
                    "state": person.state,
                    "country": 'US',
                    "postal_code": person.zipcode
                },
            },
            email=user.email)

        # Store the order data in our database
        order = Order(order_id=stripe_order.id,
                      user=user,
                      amount=stripe_order.amount,
                      email=stripe_order.email,
                      status=stripe_order.status,
                      created=datetime.fromtimestamp(stripe_order.created),
                      updated=datetime.fromtimestamp(stripe_order.updated))
        order.currency = stripe_order.currency
        order.save()

        order_status = OrderStatusTransition(order=order,
                                             status=stripe_order.status,
                                             created=datetime.fromtimestamp(
                                                 stripe_order.updated))
        order_status.save()

        for item in stripe_order['items']:
            order_item = OrderItem(order=order,
                                   amount=item['amount'],
                                   description=item['description'],
                                   parent=item['parent'],
                                   quantity=item['quantity'],
                                   item_type=item['type'])
            order_item.currency = item.currency,
            order_item.save()

        updated_order = Order.objects.get(order_id=order.order_id)
        response_serializer = OrderSerializer(updated_order)
        return Response(response_serializer.data,
                        status=status.HTTP_201_CREATED)

    except Exception as e:
        return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
Ejemplo n.º 8
0
def checkout(request):
    if request.method == 'GET':
        form = CheckForm()
        cart = request.session.get('cart')
        if cart is None:
            cart = []

        for c in cart:
            size_str = c.get('size')
            tshirt_id = c.get('tshirt')
            size_obj = SizeVariant.objects.get(size=size_str, tshirt=tshirt_id)
            c['size'] = size_obj
            c['tshirt'] = size_obj.tshirt

        print(cart)

        return render(request, 'checkout.html', {
            "form": form,
            'cart': cart
        })
    else:
        # post request
        form = CheckForm(request.POST)
        user = None
        if request.user.is_authenticated:
            user = request.user
        if form.is_valid():
            # payment
            cart = request.session.get('cart')
            if cart is None:
                cart = []
            for c in cart:
                size_str = c.get('size')
                tshirt_id = c.get('tshirt')
                size_obj = SizeVariant.objects.get(size=size_str,
                                                   tshirt=tshirt_id)
                c['size'] = size_obj
                c['tshirt'] = size_obj.tshirt
            shipping_address = form.cleaned_data.get('shipping_address')
            phone = form.cleaned_data.get('phone')
            payment_method = form.cleaned_data.get('payment_method')
            total = cal_total_payable_amount(cart)
            print(shipping_address, phone, payment_method, total)

            order = Order()
            order.shipping_address = shipping_address
            order.phone = phone
            order.payment_method = payment_method
            order.total = total
            order.order_status = "PENDING"
            order.user = user
            order.save()

            # saving order items
            for c in cart:
                order_item = OrderItem()
                order_item.order = order
                size = c.get('size')
                tshirt = c.get('tshirt')
                order_item.price = floor(size.price -
                                         (size.price *
                                          (tshirt.discount / 100)))
                order_item.quantity = c.get('quantity')
                order_item.size = size
                order_item.tshirt = tshirt
                order_item.save()

            buyer_name = f'{user.first_name} {user.last_name}'
            print(buyer_name)
            # crating payment
            
            response = API.payment_request_create(
            amount=order.total,
            purpose="Payment For Tshirts",
            send_email=True,
            buyer_name=f'{user.first_name} {user.last_name}',
            email=user.email,
            redirect_url="http://localhost:8000/validate_payment"
            )

            payment_request_id = response ['payment_request']['id']
            url = response['payment_request']['longurl']

            payment = Payment()
            payment.order = order
            payment.payment_request_id= payment_request_id
            payment.save()
            return redirect(url)

        else:
            return redirect('/checkout/')