def get_licence_price(product_code): product = get_product(product_code) if product is None: return 0.00 selector = Selector() strategy = selector.strategy() purchase_info = strategy.fetch_for_product(product=product) return purchase_info.price.effective_price
def get_licence_price(product_title): product = get_product(product_title) if product is None: return 0.00 selector = Selector() strategy = selector.strategy() purchase_info = strategy.fetch_for_product(product=product) return purchase_info.price.effective_price
def is_licence_free(product_code): product = get_product(product_code) if product is None: return True selector = Selector() strategy = selector.strategy() purchase_info = strategy.fetch_for_product(product=product) return purchase_info.price.effective_price == 0
def is_licence_free(product_title): product = get_product(product_title) if product is None: return True selector = Selector() strategy = selector.strategy() purchase_info = strategy.fetch_for_product(product=product) return purchase_info.price.effective_price == 0
def get_context_data(self, **kwargs): ctx = {} ctx['summary'] = _("All products") search_context = self.search_handler.get_search_context_data( self.context_object_name) ctx.update(search_context) strategy = Selector().strategy() available_products = [] for product in ctx['products']: info = strategy.fetch_for_product(product) if info.availability.is_available_to_buy: available_products.append(product) ctx['object_list'] = available_products ctx['products'] = available_products ctx['paginator'].count = len(available_products) return ctx
def rent_price(self): product = self.get_object() strategy = Selector().strategy purchace_info = strategy().fetch_for_product(product) self.price = purchace_info.price.excl_tax self.rent_price_1 = float(self.price) * 0.2 self.rent_price_6 = float(self.price) * 0.4 print self.rent_price_1 return self.rent_price_1, self.rent_price_6
def form_view(request, pk): # if this is a POST request we need to process the form data if request.method == 'POST': obj = Product.objects.get(id=pk) strategy = Selector().strategy() stock = strategy.fetch_for_product(obj) # data = {'product_quantity': obj.attr.MinQuantity} # create a form instance and populate it with data from the request: form = MyForm(request.POST, request.FILES) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: formobj = form.save(commit=False) formobj.product_name = obj.title formobj.product_supplier = stock.stockrecord.partner.name formobj.save() return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: obj = Product.objects.get(id=pk) strategy = Selector().strategy() stock = strategy.fetch_for_product(obj) data = {'product_quantity': obj.attr.MinQuantity} form = MyForm(initial=data) return render( request, 'partner/partner_form.html', { 'form': form, 'supplier_name': stock.stockrecord.partner.name, 'product_name': obj.title })
def form_valid(self, form): super(BasketAddView, self).form_valid(form) selector = Selector() strategy = selector.strategy(request=self.request, user=self.request.user) purchase_info = strategy.fetch_for_product(product=self.product) price = purchase_info.price.excl_tax if price is None: price = 0 img = self.product.primary_image() if isinstance(img, ProductImage): img_url = img.original.url else: img_url = img['original'].name return JsonResponse({ 'id': self.product.id, 'upc': self.product.upc, 'title': self.product.title, 'img': img_url, 'price': price })
def _update_seats(self, batch_seats, succeeded, failed): strategy = Selector().strategy() for seat in batch_seats: info = strategy.fetch_for_product(seat) try: course = Course.objects.get(id=seat.attr.course_key) course.create_or_update_seat( seat.attr.certificate_type, seat.attr.id_verification_required, info.price.excl_tax, expires=seat.expires, sku=info.stockrecord.partner_sku) succeeded += 1 except Exception: # pylint: disable=broad-except logger.error( 'Could not update seat title="%s" in course_id="%s".', seat.title, seat.attr.course_key) failed += 1 return succeeded, failed
def get_redirect_url(self, ): try: basket = Basket.objects.get( pk=self.checkout_session.get_submitted_basket_id()) except Basket.DoesNotExist: print("basket problem") return reverse_lazy('checkout:preview') shipping_address = self.get_shipping_address(basket) billing_address = self.get_billing_address( shipping_address=shipping_address) basket.strategy = Selector().strategy(self.request) Applicator().apply(basket, self.request.user, request=self.request) order_number = self.checkout_session.get_order_number() shipping_address = self.get_shipping_address(basket) shipping_method = self.get_shipping_method(basket, shipping_address) shipping_charge = shipping_method.calculate(basket) billing_address = self.get_billing_address(shipping_address) order_total = self.get_order_totals(basket, shipping_charge=shipping_charge) order_kwargs = {} # make sure payment was actually paid try: data_query = \ Payment.objects.get(factor_number=order_number, status=1, amount=float(order_total.incl_tax)) except Payment.DoesNotExist: print("query problem") # if payment was not going in correct way it will return to checkoutperview data_query = None self.restore_frozen_basket() return reverse_lazy('checkout:preview') user = self.request.user if not user.is_authenticated: order_kwargs[ 'guest_email'] = self.checkout_session.get_guest_email() self.handle_order_placement(order_number, user, basket, shipping_address, shipping_method, shipping_charge, billing_address, order_total, **order_kwargs) # source_type, is_created = models.SourceType.objects.get_or_create( # name='AsanPardakht') # source = source_type.sources.model( # source_type=source_type, # amount_allocated=19500, # ) # self.add_payment_source(source) # self.add_payment_event('AsanPardakht', 19500) return reverse_lazy('checkout:thank-you')
def post(self, request, *args, **kwargs): if 'id' not in request.data: return Response({ "message": "Please provide payment intent id", "status": False, "result": {}, "status_code": 400 }) intent_id = request.data['id'] payment_intent = stripe.PaymentIntent.retrieve(id=intent_id) if payment_intent.status != 'succeeded': return Response({ "message": "Please confirm payment first, through payment intent confirmation", "status": False, "result": {}, "status_code": 400 }) # Load and fetch basket id from payment intent # This basket would be a paid and frozen basket, hence safe to be enrolled. basket_id = json.loads(payment_intent.metadata.basket_id) if not basket_id: return Response({ "status": False, "message": "Basket not found", "status_code": 404 }) basket = Basket.objects.get(id=basket_id) basket.strategy = Selector().strategy(user=self.request.user) # Get billing details from payment intent (to be specific, from payment method) billing_details = payment_intent.charges.data[0].billing_details # Create order and enroll user order = self.create_order( self.request, basket, billing_address=self.get_address_from_payment_intent( billing_details)) self.handle_post_order(order) # Following work is to generate the require response response = requests.get(url=settings.ECOMMERCE_URL_ROOT + '/api/v2/get-basket-detail/' + str(basket_id) + '/') checkout_response = json.loads(response.text) for product in checkout_response['products']: for item in product: if item['code'] == 'course_key': course_id = item['value'] lms_url = get_lms_url('/api/commerce/v2/checkout/' + course_id) commerce_response = requests.get( url=str(lms_url), headers={ 'Authorization': 'JWT ' + str(request.site.siteconfiguration.access_token) }) commerce_response = json.loads(commerce_response.text) if commerce_response['status_code'] == 200: price = commerce_response['result']['modes'][0]['price'] sku = commerce_response['result']['modes'][0]['sku'] discount_applicable = commerce_response['result'][ 'discount_applicable'] discounted_price = commerce_response['result'][ 'discounted_price'] media = commerce_response['result']['media']['image'] category = commerce_response['result']['new_category'] title = commerce_response['result']['name'] organization = commerce_response['result']['organization'] course_info = {'course_id' : course_id ,'media': media, 'category': category, 'title': title, 'price': price, 'discount_applicable': discount_applicable, \ 'discounted_price': discounted_price, 'organization': organization, 'sku': sku, 'code': "course_details"} product.append(course_info) checkout_response['products'] = [ i for j in checkout_response['products'] for i in j if not i['code'] in ['certificate_type', 'course_key', 'id_verification_required'] ] response = { "order_number": payment_intent.description, "total": payment_intent.amount, "products": checkout_response['products'] } # change the status of last saved basket to open baskets = Basket.objects.filter(owner=self.request.user, status="Open") if baskets.exists(): last_open_basket = baskets.last() del_lines = basket.all_lines() open_lines = last_open_basket.all_lines() for line in del_lines: product = line.product filtered_lines = open_lines.filter(product_id=product.id) if filtered_lines.exists(): filtered_lines.delete() last_open_basket.save() return Response({ "message": "order completed successfully", "status": True, "result": response, "status_code": 200 })
def post(self, request, *args, **kwargs): user = request.user email = user.email customer_id = user.tracking_context['customer_id'] customer = stripe.Customer.retrieve(customer_id) user_basket = Basket.objects.filter(owner=request.user, status="Commited").last() if user_basket: user_basket.strategy = Selector().strategy(user=self.request.user) else: return Response({ "message": "No item found in cart.", "status": False, "result": {}, "status_code": 400 }) if waffle.flag_is_active( request, DYNAMIC_DISCOUNT_FLAG) and user_basket.lines.count() > 0: discount_lms_url = get_lms_url('/api/discounts/') lms_discount_client = EdxRestApiClient( discount_lms_url, jwt=request.site.siteconfiguration.access_token) ck = user_basket.lines.first().product.course_id user_id = user_basket.owner.lms_user_id response = lms_discount_client.course(ck).get() jwt = jwt_decode_handler(response.get('jwt')) if jwt['discount_applicable']: offers = Applicator().get_offers(user_basket, request.user, request) user_basket.strategy = request.strategy discount_benefit = DynamicPercentageDiscountBenefit() percentage = jwt['discount_percent'] discount_benefit.apply(user_basket, 'dynamic_discount_condition', offers[0], discount_percent=percentage) Applicator().apply(user_basket, self.request.user, self.request) if user_basket.status == "Commited": total_amount = int(user_basket.total_incl_tax) if total_amount > 0: try: with transaction.atomic(): payment_response = self.make_stripe_payment_for_mobile( None, user_basket) response = {"total_amount": payment_response.total, "transaction_id": payment_response.transaction_id, \ "currency": payment_response.currency, "client_secret": payment_response.client_secret} # Freezing basket to prevent student from getting enrolled to possibily unpaid courses user_basket.status = Basket.FROZEN user_basket.save() return Response({ "message": "Payment completed.", "status": True, "result": response, "status_code": 200 }) except Exception as e: logger.exception(e) msg = 'Attempts to handle payment for basket ' + str( user_basket.id) + ' failed.' return Response({ "message": msg, "status": False, "result": {}, "status_code": 400 }) else: return Response({ "message": "Total amount must be greater than 0.", "status": False, "result": {}, "status_code": 400 }) else: return Response({ "message": "No item found in cart.", "status": False, "result": {}, "status_code": 400 })
def post(self, request, *args, **kwargs): user = request.user email = user.email customer_id = user.tracking_context['customer_id'] customer = stripe.Customer.retrieve(customer_id) user_basket = Basket.objects.filter(owner=request.user, status="Commited").last() if user_basket: user_basket.strategy = Selector().strategy(user=self.request.user) else: return Response({ "message": "No item found in cart.", "status": False, "result": {}, "status_code": 400 }) if user_basket.status == "Commited": total_amount = int(user_basket.total_incl_tax) #total_amount = 100 if total_amount > 0: token = user.tracking_context['token'] try: with transaction.atomic(): payment_response = self.handle_payment( token, user_basket) order = self.create_order( self.request, user_basket, billing_address=self.get_address_obj_from_customer( customer)) self.handle_post_order(order) response = {"total_amount": payment_response.total, "transaction_id": payment_response.transaction_id, \ "currency": payment_response.currency, "last_4_digits_of_card": payment_response.card_number, \ "card_type": payment_response.card_type} # change the status of last saved basket to open baskets = Basket.objects.filter(owner=user, status="Open") if baskets.exists(): last_open_basket = baskets.last() del_lines = user_basket.all_lines() open_lines = last_open_basket.all_lines() for line in del_lines: product = line.product filtered_lines = open_lines.filter( product_id=product.id) if filtered_lines.exists(): filtered_lines.delete() last_open_basket.save() # send's payment confirmation mail to user try: order = order.objects.get(basket=basket) user = order.user send_confirm_purchase_email(None, user=request.user, order=order) except: pass return Response({ "message": "Payment completed.", "status": True, "result": response, "status_code": 200 }) except Exception as e: msg = 'Attempts to handle payment for basket ' + str( user_basket.id) + ' failed.' return Response({ "message": msg, "status": False, "result": {}, "status_code": 400 }) else: return Response({ "message": "Total amount must be greater than 0.", "status": False, "result": {}, "status_code": 400 }) else: return Response({ "message": "No item found in cart.", "status": False, "result": {}, "status_code": 400 })
def meta_tag(page_type, tag, object, request, category=None, filter=None): # Return ModelMetaTag if exists if isinstance(object, Product) or isinstance(object, Category): model_meta_tag = ModelMetaTag.objects.filter( content_type=ContentType.objects.get_for_model(object), object_id=object.id, ) if model_meta_tag.exists(): tag = getattr(model_meta_tag[0], tag) return tag # else return tag from tokens morph = pymorphy2.MorphAnalyzer(lang=get_language()) meta_tags = MetaTag.objects.get(type=page_type) tag = getattr(meta_tags, tag) tokens = get_tokens(tag) for k in tokens: value = object for token in k: token_clean = token.replace('[', '').replace(']', '') if token_clean in OpencorporaTag.CASES: try: word = morph.parse(unicode(value))[0] value = word.inflect({token_clean}).word except AttributeError: value = value elif token_clean == 'filter': value = '' for item in filter: filter_values = ', '.join([m for m in filter[item]]) value += u' {}: {};'.format(item, filter_values) elif token_clean == 'category' and category is not None: value = category.name elif token_clean == 'site_name': current_site = get_current_site(request) value = current_site.name elif token_clean == 'site_domain': current_site = get_current_site(request) value = current_site.domain elif (page_type == MetaTag.PRODUCT and (token_clean == 'price' or token_clean == 'availability')): selector = Selector() strategy = selector.strategy() purchase_info = strategy.fetch_for_product(object) if token_clean == 'price': value = unicode(purchase_info.price.incl_tax) elif token_clean == 'availability': value = unicode(purchase_info.availability.message) else: if (token_clean == 'name' and (page_type == MetaTag.BRAND or page_type == MetaTag.BRAND_FILTER)): token_clean = 'option' try: value = getattr(value, token_clean) except AttributeError: value = '' tag = tag.replace(''.join(k), value) if tag[0:2] == ' .': tag = tag[2:] tag = tag.replace(' . ', '. ') return tag
class Basket(AbstractBasket): _strategy = Selector().strategy()
from django.conf import settings from django.contrib.sites.models import Site from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from oscar.apps.checkout.views import PaymentDetailsView as CorePaymentDetailsView from oscar.apps.payment.exceptions import RedirectRequired from oscar.core.loading import get_model from oscar.apps.partner.strategy import Selector strategy = Selector().strategy() from . import PAYMENT_METHOD_STRIPE, PAYMENT_EVENT_PURCHASE, STRIPE_EMAIL, STRIPE_TOKEN import stripe, json import uuid SourceType = get_model('payment', 'SourceType') Source = get_model('payment', 'Source') stripe.api_key = settings.STRIPE_SECRET_KEY class PaymentDetailsView(CorePaymentDetailsView): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs):