def get_context_data(self, *args, **kwargs): context = super(PaymentSuccess, self).get_context_data(**kwargs) tx = self.request.GET.get("tx") if not tx: return context results = PaymentSuccess.paypal_post(tx) send_email.delay( "mail/feedback", {"message": str(results), "email": self.request.user.email}, "User payment validation" ) context["result"] = results[0] == "SUCCESS" if context["result"]: result_dict = dict(res.split("=") for res in results[1:]) amount_paid = result_dict.get("mc_gross") if not amount_paid or int(float(amount_paid)) < 3: context["result"] = False elif result_dict.get("payment_status") in ("Pending", "Completed", "Created", "Processed"): amount_paid = int(float(amount_paid)) user = self.request.user """:type: Profile""" item_name = result_dict.get("item_name") if "small" not in item_name: user.plan = Profile.PLAN_BUSINESS else: user.plan = Profile.PLAN_SMALL_BUSINESS user.plan_expiry = user.new_plan_expiry(amount_paid) # https://cms.paypal.com/uk/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables if result_dict.get("txn_type") == "subscr_payment": user.subscription = True user.save() return context
def register(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) # Generate activation key for user account activation_key = generate_activation_key(user.email) user.activation_key = activation_key user.is_active = False user.save() send_email.delay('mail/confirmation', {'link': activation_key}, u'\u2713 ' + _("Welcome to Prestashop-Sync Service"), [user.email]) return HttpResponse( simplejson.dumps({ 'response': _("Email with a confirmation link has been sent"), 'result': 'success' })) else: response = {} for k in form.errors: response[k] = form.errors[k][0] return HttpResponse( simplejson.dumps({ 'response': response, 'result': 'error' }))
def _checked_update_presta_data(shop, data_list, language): domain = shop.domain user = shop.user # TODO: this is something weird, it seems that update status is never updated after creation status, created = UpdateStatus.objects.get_or_create(domain=domain, defaults={'update_status': 'wait'}) try: result_dict = shop.api.update_presta_data(data_list) start_char = u'\u2713 ' result_dict['language'] = language if result_dict['errors']: start_char = u'\u2717 ' send_html_email.delay('mail/customers/update_report.html', result_dict, 'Update failure for {0}'.format(shop.domain)) send_html_email.delay('mail/customers/update_report.html', result_dict, start_char + _('Update report for %s') % shop.domain, email=[user.email]) except SoftTimeLimitExceeded: # send email send_email.delay('mail/feedback', {'message': unicode(shop.domain), 'email': user.email}, 'Time limit exceeded') send_email.delay('mail/customers/time_limit_exceeded.html', {'language': language}, _('Time limit exceeded'), email=[user.email]) status.update_status = 'success' status.save()
def get_context_data(self, *args, **kwargs): context = super(PaymentSuccess, self).get_context_data(**kwargs) tx = self.request.GET.get('tx') if not tx: return context results = PaymentSuccess.paypal_post(tx) send_email.delay('mail/feedback', { 'message': str(results), 'email': self.request.user.email }, 'User payment validation') context['result'] = (results[0] == 'SUCCESS') if context['result']: result_dict = dict(res.split('=') for res in results[1:]) amount_paid = result_dict.get('mc_gross') if not amount_paid or int(float(amount_paid)) < 3: context['result'] = False elif result_dict.get('payment_status') in ('Pending', 'Completed', 'Created', 'Processed'): amount_paid = int(float(amount_paid)) user = self.request.user """:type: Profile""" item_name = result_dict.get('item_name') if 'small' not in item_name: user.plan = Profile.PLAN_BUSINESS else: user.plan = Profile.PLAN_SMALL_BUSINESS user.plan_expiry = user.new_plan_expiry(amount_paid) # https://cms.paypal.com/uk/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables if result_dict.get('txn_type') == 'subscr_payment': user.subscription = True user.save() return context
def send_registration_email(sender, instance, created, **kwargs): """ Send email on registration :type instance: Profile """ if created and not instance.is_guest(): send_email.delay('mail/feedback', {'message': str(instance.provider), 'email':instance.email}, "User registration")
def get_data(request, form): """ :type form: LoadDataBaseForm """ # TODO: test get_data when there are < 50 products, but > 50 combinations request.session["shop"] = shop = form.get_shop(True) data, error_dict = shop.get_data() if error_dict: return HttpResponse(simplejson.dumps({"response": error_dict, "result": "error"})) next = shop.is_data_finished(len(data), 1) # put (data, real page number, start page index) request.session["data"] = (data, 0, 0) if len(data) > settings.PAGINATION: data = data[: settings.PAGINATION] request.session["sync_type"] = shop.sync_type from tools.utils import send_email send_email.delay("mail/error", {"domain": shop.domain}, "Successful GetData") response = render_to_string( "partial/products_table.html", {"data": data, "sync_type": shop.sync_type, "next": next, "previous": 0, "start_index": 0}, ) return HttpResponse(simplejson.dumps({"response": unicode(response), "result": "success", "temp": shop.temp}))
def get_data(request, form): """ :type form: LoadDataBaseForm """ # TODO: test get_data when there are < 50 products, but > 50 combinations request.session['shop'] = shop = form.get_shop(True) data, error_dict = shop.get_data() if error_dict: return HttpResponse(simplejson.dumps({'response': error_dict, 'result': 'error'})) next = shop.is_data_finished(len(data), 1) # put (data, real page number, start page index) request.session['data'] = (data, 0, 0) if len(data) > settings.PAGINATION: data = data[:settings.PAGINATION] request.session['sync_type'] = shop.sync_type from tools.utils import send_email send_email.delay('mail/error', {'domain': shop.domain}, "Successful GetData") response = render_to_string('partial/products_table.html', {'data': data, 'sync_type': shop.sync_type, 'next': next, 'previous': 0, 'start_index': 0}) return HttpResponse(simplejson.dumps({'response': unicode(response), 'result': 'success', 'temp': shop.temp}))
def notify(self): if self.is_valid(): data = { 'message': self.cleaned_data['message'], 'email': self.cleaned_data.get('from_email') or self.request.user.email } send_email.delay("mail/feedback", data, "Feedback")
def send_registration_email(sender, instance, created, **kwargs): """ Send email on registration :type instance: Profile """ if created and not instance.is_guest(): send_email.delay('mail/feedback', { 'message': str(instance.provider), 'email': instance.email }, "User registration")
def add_product_data(self, data_list, images): """ :param data_list: list of product data in the following form: [{'ean13':EAN13, 'price':PRICE, 'categories':[MAIN_CATEGORY, OTHER,...], 'langs': ['id':LANG_ID, 'name':PRODUCT_NAME, 'link_rewrite': link_rewrite]},...] see how these fields are generated in AddProductsShopForm.clean() method. :param images: list of images for every product :return: update_ok string if everything is fine, error string that matches HTML ID in template otherwise """ # Check default lang, add link rewrite if it is different default_lang = self.default_lang for prod in data_list: langs = set([lang['id'] for lang in prod['langs']]) if default_lang not in langs: new_value = prod['langs'][0].copy() new_value['id'] = default_lang prod['langs'].append(new_value) domain = self.shop.domain headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': self.shop.authheader} context = {'prestashop_url': domain, 'products': data_list, 'date_add': datetime.now()} products_xml = render_to_string('xml_templates/add_products15.xml', context).encode('utf-8') try: result = get_xml_data("http://%s/api/products" % domain, headers, urllib.urlencode({'xml': products_xml})) # Extract product ids product_ids = [e.text for e in result.findall('.//product/id')] # TODO: Prestashop 1.5 does not allow to set quantities simalteniously, # set them separately quantities = [x['quantity'] for x in data_list] update_data_list = [(p_id, '0', {'quantity': str(q)}) for p_id, q in zip(product_ids, quantities)] self.update_presta_data(update_data_list) # IMAGES ADD CODE self.add_images.delay(self, product_ids, images) except urllib2.HTTPError, e: result = e.fp.read() send_email.delay('mail/error', {'domain': domain, 'message': str(result), 'data_list': str(data_list), 'full_data': ''}, "Add product client Error") return '14_update_permission_or_csv'
def add_images(self, product_ids, images): domain = self.shop.domain headers = {'Content-Type': MULTIPART_CONTENT, 'Authorization': self.shop.authheader} for i, p_images in enumerate(images): # TODO: why sometimes index does not exist? if i >= len(product_ids): send_email.delay('mail/error', {'domain': domain, 'message': str(product_ids), 'data_list': '', 'full_data': ''}, "Add images error") break product_id = product_ids[i] for image in p_images: data = encode_multipart(BOUNDARY, {'image': image}) req = urllib2.Request(smart_str("http://%s/api/images/products/%s" % (domain, product_id)), headers=headers, data=smart_str(data)) urllib2.urlopen(req) self.make_first_image_default(product_ids, headers)
def loginza_login(request): if request.method=='POST': token=request.POST.get('token') if token: result = simplejson.loads(get_auth_info(token)) # Check if there is an error - like token was used previously if result.has_key('error_message'): # TODO: redirect to page with error message and ask for relogin send_email.delay('mail/error', {'message': str(result)}, "Loginza Error") raise Http404 uid, provider, defaults = parse_result(result) if not (defaults['email'] or Profile.objects.filter(uid=uid, provider=provider).exists()): form = RequestEmailForm(request=request) request.session['token'] = result return direct_to_template(request, "users/request_email.html", extra_context={'form': form }) user = register_loginza_user(uid, provider, defaults, request) return HttpResponseRedirect(user.get_register_redirect()) raise Http404
def get_presta_data(self, page_num, page_limit): domain = self.shop.domain headers = {"Authorization": self.shop.authheader} sync_type = self.shop.sync_type.lower() result_dict = {} try: # get products initial_index = page_num * page_limit data = get_xml_data("http://%s/api/%s?display=[id,%s,%s,name]&sort=[id_ASC]&limit=%d,%d&price[base_price][use_reduction]=0&price[base_price][use_tax]=0" % (domain, 'products', sync_type, JOINED_ATTRS, initial_index, page_limit), headers) self._get_presta_data(headers, data, result_dict, domain, sync_type, page_limit, page_num) except urllib2.HTTPError as e: error = PrestaError.get_error(PrestaError.DOMAIN, 'Incorrect value', self) if e.code == 500: # This should never happen after we implemented proper pagination message = e.fp.read() send_email.delay('mail/error', {'domain': domain, 'data_list': str(e.message), 'full_data': str(page_num), 'message': str(message)}, "Client Error") error = {PrestaError.DOMAIN: _('You have some problem with API access configuration,<br>' 'try if API works by manually examining url:<br>') + '<a href="http://%s/api/products">http://%s/api/products</a>' % (domain, domain)} elif e.code in (401, 403): # send email about this send_email.delay('mail/error', {'domain': domain, 'data_list': '', 'full_data': '', 'message': ''}, "Incorrect key") error = PrestaError.get_error(PrestaError.KEY, 'Incorrect value', self) if 'attribute_lang' in result_dict: error = PrestaError.get_error(PrestaError.KEY, PrestaError.PROD_COMBINATIONS, self) elif 'product' in result_dict: error = PrestaError.get_error(PrestaError.KEY, PrestaError.PROD_OPTIONS_VALUES, self) elif e.code == 404 or e.code == 503: error = PrestaError.get_error(PrestaError.DOMAIN, PrestaError.NOT_ACTIVATED, self) return result_dict, error except (urllib2.URLError, socket.timeout): # either timeout or dns error error = PrestaError.get_error(PrestaError.DOMAIN, PrestaError.NOT_REACHABLE, self) return result_dict, error except PrestaError, e: # no products found in the shop error = PrestaError.get_error(PrestaError.DOMAIN, e.message, self) return result_dict, error
def register(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) # Generate activation key for user account activation_key = generate_activation_key(user.email) user.activation_key = activation_key user.is_active = False user.save() send_email.delay('mail/confirmation', {'link': activation_key}, u'\u2713 ' + _("Welcome to Prestashop-Sync Service"), [user.email]) return HttpResponse(simplejson.dumps({'response': _("Email with a confirmation link has been sent"), 'result': 'success'})) else: response = {} for k in form.errors: response[k] = form.errors[k][0] return HttpResponse(simplejson.dumps({'response': response, 'result': 'error'}))
def loginza_login(request): if request.method == 'POST': token = request.POST.get('token') if token: result = simplejson.loads(get_auth_info(token)) # Check if there is an error - like token was used previously if result.has_key('error_message'): # TODO: redirect to page with error message and ask for relogin send_email.delay('mail/error', {'message': str(result)}, "Loginza Error") raise Http404 uid, provider, defaults = parse_result(result) if not (defaults['email'] or Profile.objects.filter( uid=uid, provider=provider).exists()): form = RequestEmailForm(request=request) request.session['token'] = result return direct_to_template(request, "users/request_email.html", extra_context={'form': form}) user = register_loginza_user(uid, provider, defaults, request) return HttpResponseRedirect(user.get_register_redirect()) raise Http404
def send_error(request): if request.method == 'POST': send_email.delay('mail/js_error', request.POST, "JavaScript Error") return HttpResponse("ok")
def notify(self): if self.is_valid(): data = {'message': self.cleaned_data['message'], 'email': self.cleaned_data.get('from_email') or self.request.user.email} send_email.delay("mail/feedback", data, "Feedback")
result_dict['language'] = language if result_dict['errors']: start_char = u'\u2717 ' send_html_email.delay('mail/customers/update_report.html', result_dict, 'Periodic update failure for {0}'.format(shop.domain)) send_html_email.delay('mail/customers/update_report.html', result_dict, start_char + _('Periodic update report for %s') % shop.domain, email=[user.email]) else: message = str(result['response']) except Exception, e: message = unicode(e) # notify if message is not None: send_email.delay('mail/feedback', {'message': u'{0}:\n{1}'.format(unicode(shop.domain), message), 'email': user.email}, 'Exception during periodic checked update') send_email.delay('mail/customers/csv_update_error.html', {'language': language, 'message': unicode(message)}, _('Scheduled update failure'), email=[user.email]) def _checked_update_presta_data(shop, data_list, language): domain = shop.domain user = shop.user # TODO: this is something weird, it seems that update status is never updated after creation status, created = UpdateStatus.objects.get_or_create(domain=domain, defaults={'update_status': 'wait'}) try: result_dict = shop.api.update_presta_data(data_list) start_char = u'\u2713 '