def list_lists(): cm = CampaignMonitorApi(settings.CAMPAIGN_MONITOR_KEY, settings.CAMPAIGN_MONITOR_CLIENT) try: return cm.client_get_lists() except CampaignMonitorApi.CampaignMonitorApiException, e: print e.message return []
def retail_signup(request, template="accounts/retail_signup.html"): form = ProfileForm(request.POST or None) if request.method == "POST" and form.is_valid(): new_user = form.save() # Add to campaign monitor if bool(form.cleaned_data.get("optin")): cm_api = CampaignMonitorApi(settings.CM_API_KEY, settings.CM_CLIENT_ID) listid = settings.CM_RETAIL_LIST_ID custom_fields = {} #try: cm_api.subscriber_add( listid, form.cleaned_data.get("email"), form.cleaned_data.get("first_name") + ' ' + form.cleaned_data.get("last_name"), custom_fields=custom_fields) #except: # pass if not new_user.is_active: send_verification_mail(request, new_user, "signup_verify") info(request, "A verification email has been sent with a link for activating your account.") else: info(request, "Successfully signed up") auth_login(request, new_user) return my_login_redirect(request) context = {"form": form, "title": "Customer Registration"} return render(request, template, context)
def campaignmonitor(request): if not request.user.is_superuser: return locals() if request.method == "POST" and request.POST.get('export'): success = failure = [] mailable_users = CustomUser.objects.filter(can_email=True, is_active=True) cm = CampaignMonitorApi(settings.CAMPAIGN_MONITOR_KEY, None) for user in mailable_users: try: done = cm.subscriber_add(settings.CAMPAIGN_MONITOR_LIST, user.email, "%s %s" % (user.first_name, user.last_name)) if done: success.append(user.email) else: failure.append(user.email) except CampaignMonitorApi.CampaignMonitorApiException: failure.append("* " + user.email) messages.info(request, "%s new emails imported" % len(success)) if failure: messages.error(request, "Problem importing %s" % len(failure)) return locals()
def wholesale_signup(request, template="accounts/wholesale_signup.html"): form = ProfileForm(request.POST or None) if request.method == "POST" and form.is_valid(): new_user = form.save() g = Group.objects.get(name='Wholesale Customers') g.user_set.add(new_user) # Add to campaign monitor if bool(form.cleaned_data.get("optin")): cm_api = CampaignMonitorApi(settings.CM_API_KEY, settings.CM_CLIENT_ID) listid = settings.CM_WHOLESALE_LIST_ID usertype = "" if form.cleaned_data.get("user_type"): try: usertype = USER_TYPE_CHOICES[form.cleaned_data.get("user_type")] except: pass elif form.cleaned_data.get("user_type_other"): usertype = form.cleaned_data.get("user_type_other") custom_fields = {"CustomerType": usertype} try: cm_api.subscriber_add( listid, form.cleaned_data.get("email"), form.cleaned_data.get("first_name") + ' ' + form.cleaned_data.get("last_name"), custom_fields=custom_fields) except: pass if not new_user.is_active: send_verification_mail(request, new_user, "signup_verify") info(request, "A verification email has been sent with a link for activating your account.") else: info(request, "Successfully signed up") auth_login(request, new_user) send_registration_confirmation_email(request) return my_login_redirect(request, wholesale=True) context = {"form": form, "title": "Wholesale Customer Registration"} return render(request, template, context)
def submit(self): Form.submit(self) extension = CampaignMonitorExtension.instance cmlist = self.data["list"] email = self.data["email"].encode("utf-8") name = self.data.get("name") name = name.encode("utf-8") if name else "" api = CampaignMonitorApi(extension.api_key, extension.client_id) try: user_subscribed = api.subscribers_get_is_subscribed( cmlist.list_id, email) except CampaignMonitorApi.CampaignMonitorApiException: user_subscribed = False # Obtain custom fields new_custom_fields = self.custom_fields if user_subscribed: response = api.subscribers_get_single_subscriber( cmlist.list_id, email) subscriber = response.get("Subscribers.GetSingleSubscriber") custom_fields = subscriber[0].get("CustomFields") else: custom_fields = {} custom_fields.update(**new_custom_fields) # Encode custom fields encoded_custom_fields = {} for key, value in custom_fields.items(): encoded_key = (key.encode("utf-8") if isinstance(key, unicode) else key) encoded_value = (value.encode("utf-8") if isinstance( value, unicode) else value) encoded_custom_fields[encoded_key] = encoded_value try: api.subscriber_add_and_resubscribe(cmlist.list_id, email, name, encoded_custom_fields) except CampaignMonitorApi.CampaignMonitorApiException: # TODO: Capture the error code and show the correct message self.campaign_monitor_errors = True else: if user_subscribed and cmlist.confirmation_success_page: uri = self.get_confirmation_uri(cmlist, email=email, name=name, **encoded_custom_fields) elif not user_subscribed and cmlist.pending_page: uri = self.get_pending_uri(cmlist, email=email, name=name, **encoded_custom_fields) else: uri = self.get_default_uri(cmlist, email=email, name=name, **encoded_custom_fields) raise cherrypy.HTTPRedirect(uri.encode("utf-8"))
def checkout_steps(request): """ Display the order form and handle processing of each step. """ # Do the authentication check here rather than using standard # login_required decorator. This means we can check for a custom # LOGIN_URL and fall back to our own login view. settings.use_editable() authenticated = request.user.is_authenticated() if settings.SHOP_CHECKOUT_ACCOUNT_REQUIRED and not authenticated: url = "%s?next=%s" % (settings.LOGIN_URL, reverse("checkout")) return HttpResponseRedirect(url) wholesale_logged_in = False user_fullname = "" if authenticated: user_fullname = " ".join([request.user.first_name, request.user.last_name]) if request.user.has_perm('custom.wholesale_customer'): wholesale_logged_in = True if float(request.cart.total_price()) < float(settings.WHOLESALE_MINIMUM_SPEND): return HttpResponseRedirect(reverse("basket")) # Determine the Form class to use during the checkout process form_class = get_callable(settings.SHOP_CHECKOUT_FORM_CLASS) step = int(request.POST.get("step", checkout.CHECKOUT_STEP_FIRST)) initial = checkout.initial_order_data(request) form = form_class(request, step, initial=initial) data = request.POST checkout_errors = [] if request.POST.get("back") is not None: # Back button in the form was pressed - load the order form # for the previous step and maintain the field values entered. step -= 1 form = form_class(request, step, initial=initial) elif request.method == "POST": form = form_class(request, step, initial=initial, data=data) if form.is_valid(): # Copy the current form fields to the session so that # they're maintained if the customer leaves the checkout # process, but remove sensitive fields from the session # such as the credit card fields so that they're never # stored anywhere. request.session["order"] = dict(form.cleaned_data) sensitive_card_fields = ("card_number", "card_expiry_month", "card_expiry_year", "card_ccv") for field in sensitive_card_fields: del request.session["order"][field] # FIRST CHECKOUT STEP - handle shipping and discount code. if step == checkout.CHECKOUT_STEP_FIRST: try: billship_handler(request, form) except checkout.CheckoutError, e: checkout_errors.append(e) form.set_discount() # FINAL CHECKOUT STEP - handle payment and process order. if step == checkout.CHECKOUT_STEP_LAST and not checkout_errors: # Create and save the inital order object so that # the payment handler has access to all of the order # fields. If there is a payment error then delete the # order, otherwise remove the cart items from stock # and send the order reciept email. order = form.save(commit=False) order.setup(request) # Try payment. try: if order.total == 0: # FOR GROUPONS import datetime transaction_id = "GROUPON-%s" % str(datetime.datetime.now()).replace(' ','-') else: transaction_id = payment_handler(request, form, order) except checkout.CheckoutError, e: # Error in payment handler. order.delete() checkout_errors.append(e) if settings.SHOP_CHECKOUT_STEPS_CONFIRMATION: step -= 1 else: # Finalize order - ``order.complete()`` performs # final cleanup of session and cart. # ``order_handler()`` can be defined by the # developer to implement custom order processing. # Then send the order email to the customer. order.transaction_id = transaction_id order.complete(request) order_handler(request, form, order) checkout.send_order_email(request, order) # Set the cookie for remembering address details # if the "remember" checkbox was checked. response = HttpResponseRedirect(reverse("complete")) if form.cleaned_data.get("remember") is not None: remembered = "%s:%s" % (sign(order.key), order.key) set_cookie(response, "remember", remembered, secure=request.is_secure()) else: response.delete_cookie("remember") # Now add the customer to the CAMPAIGN MONITOR # subscriber list if they opted in addtolist = False if authenticated: if request.user.get_profile().optin: addtolist = True else: if bool(form.cleaned_data.get("optin")): addtolist = True if addtolist: cm_api = CampaignMonitorApi(settings.CM_API_KEY, settings.CM_CLIENT_ID) listid = settings.CM_RETAIL_LIST_ID custom_fields = {} if wholesale_logged_in: listid = settings.CM_WHOLESALE_LIST_ID usertype = USER_TYPE_CHOICES[request.user.get_profile().user_type] custom_fields = {"CustomerType": usertype} try: cm_api.subscriber_add( listid, form.cleaned_data.get("billing_detail_email"), form.cleaned_data.get("billing_detail_first_name") + ' ' + form.cleaned_data.get("billing_detail_last_name"), custom_fields=custom_fields) except: pass return response # If any checkout errors, assign them to a new form and # re-run is_valid. If valid, then set form to the next step. form = form_class(request, step, initial=initial, data=data, errors=checkout_errors) if form.is_valid(): step += 1 form = form_class(request, step, initial=initial)
def sign_up_to_list(email, name=""): cm = CampaignMonitorApi(settings.CAMPAIGN_MONITOR_KEY, None) try: return cm.subscriber_add(settings.CAMPAIGN_MONITOR_LIST, email, name) except CampaignMonitorApi.CampaignMonitorApiException, e: raise SignupException(e.message)
def list_subscribers(list_id): cm = CampaignMonitorApi(settings.CAMPAIGN_MONITOR_KEY, settings.CAMPAIGN_MONITOR_CLIENT) try: return cm.subscribers_get_active(list_id) except CampaignMonitorApi.CampaignMonitorApiException, e: assert False, e
def synchronize_lists(self, restricted=False): """Synchronizes the list of Lists of the given Campaign Monitor account with the site's database. The method queries Campaing Monitor API, retrieving the list of Lists for the indicated account and comparing it with the set of already known Lists (from previous executions of this method). The local database will be updated as follows: * Lists declared by Campaing Monitor that are not present in the database will generate new instances. * Lists that exist on both ends will be updated with the data provided by the Campaing Monitor service (only non editable members will be updated, so that data entered by users in the backoffice is preserved). * Lists that were instantiated in a previous run but which have been deleted at the Campaign Monitor side will be removed from the database. @param restricted: Indicates if access control should be applied to the operations performed by the method. @type restricted: bool """ from campaign_monitor_api import CampaignMonitorApi from cocktail.controllers import context from cocktail.controllers.location import Location from woost.extensions.campaignmonitor.campaignmonitorlist import \ CampaignMonitorList if restricted: user = get_current_user() api = CampaignMonitorApi(self.api_key, self.client_id) remote_lists = set() for list_data in api.client_get_lists(): list_id = list_data["ListID"] cmlist = CampaignMonitorList.get_instance(list_id=list_id) remote_lists.add(list_id) # Check permissions if restricted and not user.has_permission( CreatePermission if cmlist is None else ModifyPermission, target=(cmlist or CampaignMonitorList)): continue # Create new lists if cmlist is None: cmlist = CampaignMonitorList() cmlist.insert() cmlist.list_id = list_id self.lists.append(cmlist) # Modify new or updated lists with remote data cmlist.title = list_data.get("Name") list_detail_data = api.list_get_detail(list_id) # Modify remote lists with page urls def absolute_uri(publishable, *args, **kwargs): location = Location.get_current_host() location.path_info = context["cms"].uri( publishable, *args, **kwargs) return str(location) if cmlist.unsubscribe_page: unsubscribe_page = "%s?user=[email]" % absolute_uri( cmlist.unsubscribe_page) else: unsubscribe_page = list_detail_data.get("UnsubscribePage") if cmlist.confirmation_success_page: confirmation_success_page = absolute_uri( cmlist.confirmation_success_page) else: confirmation_success_page = list_detail_data.get( "ConfirmationSuccessPage") api.list_update(list_id, list_detail_data.get("Title"), unsubscribe_page, list_detail_data.get("ConfirmOptIn"), confirmation_success_page) # Delete lists that have been deleted from the user account missing_lists = CampaignMonitorList.select( CampaignMonitorList.list_id.not_one_of(remote_lists), ) if restricted: missing_lists.add_filter( PermissionExpression(user, DeletePermission)) missing_lists.delete_items()
def resubscribe(self, email): extension = CampaignMonitorExtension.instance api = CampaignMonitorApi(extension.api_key, extension.client_id) lists = api.client_get_lists() resubscribed_lists = 0 cm_context = {"email": email, "lists": []} for i, list in enumerate(lists): try: response = api.subscribers_get_single_subscriber( list.get("ListID"), email.encode("utf-8")) except CampaignMonitorApi.CampaignMonitorApiException: continue else: subscriber = response.get("Subscribers.GetSingleSubscriber") name = subscriber[0].get("Name") date = subscriber[0].get("Date") state = subscriber[0].get("State") cm_context["lists"].append({ "list_id": list.get("ListID"), "name": name, "state": state, "date": date }) if state == "Unsubscribed": date = datetime.strptime(date, '%Y-%m-%d %H:%M:%S') now = datetime.now() diff = now - date if date > now or diff.seconds < self.max_seconds: custom_fields = subscriber[0].get("CustomFields") # Encode custom fields encoded_custom_fields = {} for key, value in custom_fields.items(): encoded_key = (key.encode("utf-8") if isinstance( key, unicode) else key) encoded_value = (value.encode("utf-8") if isinstance(value, unicode) else value) encoded_custom_fields[encoded_key] = encoded_value cm_context["lists"][i].update( **encoded_custom_fields) try: # Resubscribe resubscribed_lists += 1 api.subscriber_add_and_resubscribe( list.get("ListID"), email.encode("utf-8"), name.encode("utf-8") if name else name, encoded_custom_fields) except CampaignMonitorApi.CampaignMonitorApiException: self.campaign_monitor_errors = True uri = None if resubscribed_lists == 0: uri = self.get_subscription_uri(**cm_context) else: uri = self.get_pending_uri(**cm_context) if uri is None: uri = get_current_website().home.get_uri() raise cherrypy.HTTPRedirect(uri.encode("utf-8"))