Exemplo n.º 1
0
def site_configuration(request):
    """
    Get Site Configuration values
    :SITE_CONF:  Object Site Configuration
    :LIVE_URL: Str URL Site
    :LOCALE_URI: Available locale uri
    Return dicc
    """

    site_configuration = siteConfiguration(SITE_ID)

    sufix = ''
    if LOCALE_URI:
        sufix = "/%s" % get_language()

    user_name = False
    full_name = False
    if request.user.is_active:
        user_name = request.user
        full_name = request.user.get_full_name()
        if not full_name:
            full_name = user_name

    return {
        'SITE_CONF': site_configuration,
        'SITE_URI': LIVE_URL,
        'LOCALE_URI': sufix,
        'USER_NAME': user_name,
        'FULL_NAME': full_name,
    }
Exemplo n.º 2
0
def login(request):
    """Login Page and authenticate. If exists session, redirect profile"""

    context_instance=RequestContext(request)

    if request.user.is_authenticated(): #redirect profile
        return HttpResponseRedirect("%s/partner/profile/" % context_instance['LOCALE_URI'])

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Login')
    metadescription = _('Account frontpage of %(site)s') % {'site':site_configuration.site_title}

    if 'username' in request.POST and 'password1' in request.POST:
        username = request.POST['username']
        password = request.POST['password1']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                auth_login(request, user)
                redirect = '%s/partner/profile/' % (context_instance['LOCALE_URI'])
                if 'redirect' in request.POST:
                    redirect = base64.b64decode(request.POST['redirect'])
                return HttpResponseRedirect(redirect)
            else:
                error = _('Sorry. Your user is not active.')
        else:
            error = _('Sorry. Your username or password is not valid.')

    form = UserCreationForm()
    if request.GET.get('next'):
        redirect = base64.b64encode(request.GET.get('next'))

    return render_to_response("partner/login.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 3
0
def manufacturers(request, key=False):
    """All Manufacturers
    List all manufacturers. Available with Pagination
    :param request
    :return render_to_response
    """

    site_configuration = siteConfiguration(SITE_ID)

    manufacturers = ResManufacturer.objects.all()
    manufacturers = ResManufacturer.objects.filter(active=True).order_by('name')

    num_pages = get_num_pages(manufacturers, PAGINATOR_MANUFACTURER_TOTAL)
    title = _('Manufacturers on %(site)s - Page %(page)s of %(total)s') % {
                            'site': site_configuration.site_title,
                            'page': int(request.GET.get('page', '1')),
                            'total': num_pages
                        }
    metadescription = _('Manufacturers of %(site)s - Page %(page)s of %(total)s') % {
                            'site': site_configuration.site_title,
                            'page': int(request.GET.get('page', '1')),
                            'total': num_pages
                        }
    return render_to_response("catalog/manufacturers.html", {
                            'title':title, 
                            'metadescription': metadescription,
                            'site': site_configuration.site_title,
                            'manufacturers': manufacturers,
                        },
                        context_instance=RequestContext(request))
Exemplo n.º 4
0
def manufacturers(request, key=False):
    """All Manufacturers
    List all manufacturers. Available with Pagination
    :param request
    :return render_to_response
    """

    site_configuration = siteConfiguration(SITE_ID)

    manufacturers = ResManufacturer.objects.all()
    manufacturers = ResManufacturer.objects.filter(
        active=True).order_by('name')

    num_pages = get_num_pages(manufacturers, PAGINATOR_MANUFACTURER_TOTAL)
    title = _('Manufacturers on %(site)s - Page %(page)s of %(total)s') % {
        'site': site_configuration.site_title,
        'page': int(request.GET.get('page', '1')),
        'total': num_pages
    }
    metadescription = _(
        'Manufacturers of %(site)s - Page %(page)s of %(total)s') % {
            'site': site_configuration.site_title,
            'page': int(request.GET.get('page', '1')),
            'total': num_pages
        }
    return render_to_response("catalog/manufacturers.html", {
        'title': title,
        'metadescription': metadescription,
        'site': site_configuration.site_title,
        'manufacturers': manufacturers,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 5
0
def partner(request):
    """Partner page"""

    partner_id = checkPartnerID(request)
    if not partner_id:
        error = _(
            'Are you a customer? Please, contact us. We will create a new role'
        )
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))
    conn = connOOOP()
    if not conn:
        error = _(
            'Error when connecting with our ERP. Try again or cantact us')
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    site_configuration = siteConfiguration(SITE_ID)

    partner = conn.ResPartner.get(partner_id)
    address_invoice = conn.ResPartnerAddress.filter(type='invoice',
                                                    partner_id=partner_id)
    address_delivery = conn.ResPartnerAddress.filter(type='delivery',
                                                     partner_id=partner_id)

    title = _('User Profile')
    metadescription = _('User profile of %(site)s') % {
        'site': site_configuration.site_title
    }

    return render_to_response("partner/partner.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 6
0
def site_configuration(request):
    """
    Get Site Configuration values
    :SITE_CONF:  Object Site Configuration
    :LIVE_URL: Str URL Site
    :LOCALE_URI: Available locale uri
    Return dicc
    """

    site_configuration = siteConfiguration(SITE_ID)

    sufix = ''
    if LOCALE_URI:
        sufix = "/%s" % get_language()

    user_name = False
    full_name = False
    if request.user.is_active:
        user_name = request.user
        full_name = request.user.get_full_name()
        if not full_name:
            full_name = user_name

    return {
        'SITE_CONF': site_configuration,
        'SITE_URI': LIVE_URL,
        'LOCALE_URI': sufix,
        'USER_NAME': user_name,
        'FULL_NAME': full_name,
    }
Exemplo n.º 7
0
def changepassword(request):
    """Change Password page"""

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Change password')
    metadescription = _('Change password of %(site)s') % {
        'site': site_configuration.site_title
    }

    if request.method == "POST":
        error = ''

        form = UserCreationForm(request.POST)
        data = request.POST.copy()

        if data['password1'] == data['password2']:
            if len(data['password1']) >= KEY_LENGHT:
                # update password
                request.user.set_password(data['password1'])
                request.user.save()
                if request.user.email:
                    # send email
                    subject = _('New password is added - %(name)s') % {
                        'name': site_configuration.site_title
                    }
                    body = _(
                        "This email is generated  automatically from %(site)s\n\nNew password: %(password)s\n\n%(live_url)s\n\nPlease, do not answer the email"
                    ) % {
                        'site': site_configuration.site_title,
                        'password': data['password1'],
                        'live_url': LIVE_URL
                    }
                    try:
                        email = EmailMessage(
                            subject,
                            body,
                            EMAIL_FROM,
                            to=[request.user.email],
                            headers={'Reply-To': EMAIL_REPPLY})
                        email.send()
                    except:
                        pass
                error = _("New password is added")
            else:
                error = _(
                    "Sorry. Passwords need %(size)s characters or more. Try again"
                ) % {
                    'size': KEY_LENGHT
                }
        else:
            error = _("Sorry. Passwords don't match. Try again")

    form = UserCreationForm()
    return render_to_response("partner/changepassword.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 8
0
def profile(request):
    """Profile page"""
    
    site_configuration = siteConfiguration(SITE_ID)

    full_name = checkFullName(request)

    title = _('Profile %(full_name)s') % {'full_name':full_name}
    metadescription = _('Account frontpage of %(site)s') % {'site':site_configuration.site_title}

    return render_to_response("partner/profile.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 9
0
def theme(request):
    """
    Params context template:
     - SITE_TITLE: Site name (title html pages)
     - THEME: name template teme
    Return dicc
    """

    site_configuration = siteConfiguration(SITE_ID)

    return {
        'SITE_TITLE': site_configuration.site_title,
        'THEME': BASE_TEMPLATE,
    }
Exemplo n.º 10
0
def theme(request):
    """
    Params context template:
     - SITE_TITLE: Site name (title html pages)
     - THEME: name template teme
    Return dicc
    """

    site_configuration = siteConfiguration(SITE_ID)

    return {
        'SITE_TITLE': site_configuration.site_title,
        'THEME': BASE_TEMPLATE,
    }
Exemplo n.º 11
0
def remember(request):
    """Remember password"""

    message = []
    site_configuration = siteConfiguration(SITE_ID)

    title = _('Remember')
    metadescription = _('Remember account of %(site)s') % {'site':site_configuration.site_title}

    if request.method == "POST":
        form = UserCreationForm(request.POST)
        data = request.POST.copy()

        email = data['email']

        check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        if check_captcha.is_valid is False: # captcha not valid
            msg = _('Error with captcha number. Copy the same number.')
            message.append(msg)
        else:
            if is_valid_email(email):
                # check if user  exist
                users = User.objects.filter(email__exact=email)
                if len(users) > 0:
                    #create new password
                    key = User.objects.make_random_password(length=KEY_LENGHT)
                    # update password
                    user = User.objects.get(id=users[0].id)
                    user.set_password(key)
                    user.save()
                    # send email
                    subject = _('Remember username - %(name)s') % {'name':site_configuration.site_title}
                    body = _("This email is generated  automatically from %(site)s\n\nUsername: %(username)s\nPassword: %(password)s\n\n%(live_url)s\n\nPlease, do not answer the email") % {'site':site_configuration.site_title,'username':user.username,'password':key,'live_url':LIVE_URL}
                    email = EmailMessage(subject, body, EMAIL_FROM, to=[user.email], headers = {'Reply-To': EMAIL_REPPLY})
                    email.send()
                    email = ''
                    msg = _('A new password are sent to %(email)s') % {'email':user.email}
                    message.append(msg)
                else:
                    msg = _('Sorry. This email not exist. Try again')
                    message.append(msg)
            else:
                msg = _('Sorry. This email is not valid. Try again')
                message.append(msg)

    form = UserCreationForm()
    html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)

    return render_to_response("partner/remember.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 12
0
def profile(request):
    """Profile page"""

    site_configuration = siteConfiguration(SITE_ID)

    full_name = checkFullName(request)

    title = _('Profile %(full_name)s') % {'full_name': full_name}
    metadescription = _('Account frontpage of %(site)s') % {
        'site': site_configuration.site_title
    }

    return render_to_response("partner/profile.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 13
0
def index(request):
    """
    Catalog Index
    All Categories list
    """

    values = ProductCategory.get_categories_list()

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Categories')
    metadescription = _('List all categories of %s') % site_configuration.site_title
    return render_to_response("catalog/index.html", {
                    'title': title,
                    'metadescription': metadescription, 
                    'values': values,
                }, context_instance=RequestContext(request))
Exemplo n.º 14
0
def index(request):
    """
    Catalog Index
    All Categories list
    """

    values = ProductCategory.get_categories_list()

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Categories')
    metadescription = _(
        'List all categories of %s') % site_configuration.site_title
    return render_to_response("catalog/index.html", {
        'title': title,
        'metadescription': metadescription,
        'values': values,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 15
0
class BlogFeed(Feed):
    site_configuration = siteConfiguration(SITE_ID)

    title = site_configuration.site_title
    if LOCALE_URI:
        link = "/%s/blog/" % get_language()
    else:
        link = ''
    description = site_configuration.site_metadescription

    def items(self):
        site_configuration = siteConfiguration(SITE_ID)
        return Blog.objects.order_by(
            '-created_on')[:site_configuration.rss_max]

    def item_title(self, item):
        return item.name

    def item_description(self, item):
        return item.description
Exemplo n.º 16
0
def login(request):
    """Login Page and authenticate. If exists session, redirect profile"""

    context_instance = RequestContext(request)

    if request.user.is_authenticated():  #redirect profile
        return HttpResponseRedirect("%s/partner/profile/" %
                                    context_instance['LOCALE_URI'])

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Login')
    metadescription = _('Account frontpage of %(site)s') % {
        'site': site_configuration.site_title
    }

    if 'username' in request.POST and 'password1' in request.POST:
        username = request.POST['username']
        password = request.POST['password1']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                auth_login(request, user)
                redirect = '%s/partner/profile/' % (
                    context_instance['LOCALE_URI'])
                if 'redirect' in request.POST:
                    redirect = base64.b64decode(request.POST['redirect'])
                return HttpResponseRedirect(redirect)
            else:
                error = _('Sorry. Your user is not active.')
        else:
            error = _('Sorry. Your username or password is not valid.')

    form = UserCreationForm()
    if request.GET.get('next'):
        redirect = base64.b64encode(request.GET.get('next'))

    return render_to_response("partner/login.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 17
0
def blog_list(request, key=False):
    """All Blog
    List all blog. Available with Pagination
    :param request
    :return render_to_response
    """

    site_configuration = siteConfiguration(SITE_ID)

    blogs = Blog.objects.all().order_by('-created_on')
    blogs = blogs.filter(status=True)
    if key:
        kwargs = {
            'metakey_' + get_language() + "__icontains": key,
        }
        query = Q(**kwargs)
        blogs = blogs.filter(query)

    num_pages = get_num_pages(blogs, PAGINATOR_BLOG_TOTAL)
    title = _('Blog :: All Posts %(key)s - Page %(page)s of %(total)s') % {
        'key': key and key or '',
        'page': int(request.GET.get('page', '1')),
        'total': num_pages
    }
    metadescription = _(
        'List all post %(key)s blog of %(site)s. Page %(page)s of %(total)s'
    ) % {
        'key': key and key or '',
        'site': site_configuration.site_title,
        'page': int(request.GET.get('page', '1')),
        'total': num_pages
    }

    return render_to_response("blog/list.html", {
        'title': title,
        'metadescription': metadescription,
        'blogs': blogs
    },
                              context_instance=RequestContext(request))
Exemplo n.º 18
0
def partner(request):
    """Partner page"""

    partner_id = checkPartnerID(request)
    if not partner_id:
        error = _('Are you a customer? Please, contact us. We will create a new role')
        return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))
    conn = connOOOP()
    if not conn:
        error = _('Error when connecting with our ERP. Try again or cantact us')
        return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))
        
    site_configuration = siteConfiguration(SITE_ID)

    partner = conn.ResPartner.get(partner_id)
    address_invoice = conn.ResPartnerAddress.filter(type='invoice',partner_id=partner_id)
    address_delivery = conn.ResPartnerAddress.filter(type='delivery',partner_id=partner_id)

    title = _('User Profile')
    metadescription = _('User profile of %(site)s') % {'site':site_configuration.site_title}
    
    return render_to_response("partner/partner.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 19
0
class ProductFeed(Feed):
    """
    Product Feed
    """

    site_configuration = siteConfiguration(SITE_ID)

    title = site_configuration.site_title
    if LOCALE_URI:
        link = "/%s/" % (catalog_url[get_language()])
    else:
        link = ''
    description = site_configuration.site_metadescription

    def items(self):
        site_configuration = siteConfiguration(SITE_ID)
        return ProductTemplate.objects.order_by('-created_on')[:site_configuration.rss_max]

    def item_title(self, item):
        return item.name

    def item_description(self, item):
        return stripwiki(item.shortdescription)
Exemplo n.º 20
0
def blog_list(request, key=False):
    """All Blog
    List all blog. Available with Pagination
    :param request
    :return render_to_response
    """

    site_configuration = siteConfiguration(SITE_ID)

    blogs = Blog.objects.all().order_by('-created_on')
    blogs = blogs.filter(status=True)
    if key:
        kwargs = {
            'metakey_'+get_language()+"__icontains": key,
        }
        query = Q(**kwargs)
        blogs = blogs.filter(query)

    num_pages = get_num_pages(blogs, PAGINATOR_BLOG_TOTAL)
    title = _('Blog :: All Posts %(key)s - Page %(page)s of %(total)s') % {
                            'key': key and key or '',
                            'page': int(request.GET.get('page', '1')),
                            'total': num_pages
                        }
    metadescription = _('List all post %(key)s blog of %(site)s. Page %(page)s of %(total)s') % {
                            'key': key and key or '',
                            'site':site_configuration.site_title, 
                            'page':int(request.GET.get('page', '1')),
                            'total':num_pages
                        }

    return render_to_response("blog/list.html", {
                            'title':title, 
                            'metadescription': metadescription,
                            'blogs': blogs
                        },
                        context_instance=RequestContext(request))
Exemplo n.º 21
0
def changepassword(request):
    """Change Password page"""

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Change password')
    metadescription = _('Change password of %(site)s') % {'site':site_configuration.site_title}

    if request.method == "POST":
        error = ''

        form = UserCreationForm(request.POST)
        data = request.POST.copy()

        if data['password1'] == data['password2']:
            if len(data['password1']) >= KEY_LENGHT:
                # update password
                request.user.set_password(data['password1'])
                request.user.save()
                if request.user.email:
                    # send email
                    subject = _('New password is added - %(name)s') % {'name':site_configuration.site_title}
                    body = _("This email is generated  automatically from %(site)s\n\nNew password: %(password)s\n\n%(live_url)s\n\nPlease, do not answer the email") % {'site':site_configuration.site_title,'password':data['password1'],'live_url':LIVE_URL}
                    try:
                        email = EmailMessage(subject, body, EMAIL_FROM, to=[request.user.email], headers = {'Reply-To': EMAIL_REPPLY})
                        email.send()
                    except:
                        pass
                error = _("New password is added")
            else:
                error = _("Sorry. Passwords need %(size)s characters or more. Try again") % {'size':KEY_LENGHT}
        else:
            error = _("Sorry. Passwords don't match. Try again")

    form = UserCreationForm()
    return render_to_response("partner/changepassword.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 22
0
def contactForm(request, contact = 'default'):
    """Contact Form"""

    message = False
    contact_detail = False

    contacts = Contact.objects.all()
    if contact == 'default':
        contacts = contacts.filter(default=True, status=True)
    else:
        contacts = contacts.filter(slug=contact)

    if not contacts.count() > 0:
        raise Http404

    contact_detail = contacts[0]

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            site_configuration = siteConfiguration(SITE_ID)

            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            contact_text = form.cleaned_data['contact_text']

            try:
                check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
            except:
                error = _('Error with captcha system. Try again.')
                return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))

            if check_captcha.is_valid is False:
                # Captcha is wrong show a error ...
                message = _('Error with captcha number. Copy the same number.')
            else:
                subject = _('Contact - %(name)s') % {'name':site_configuration.site_title}
                body = _('This email is generated with Contact Module from %(site)s\n\n%(name)s - %(email)s\n%(message)s') % {
                                            'site':site_configuration.site_title,
                                            'name':name,
                                            'email':email,
                                            'message':contact_text
                                        }

                emails = contact_detail.email and contact_detail.email or site_configuration.contact_email
                contact_email = emails.split(',')
                if len(contact_email)==0:
                    contact_email = [contact_email]

                try:
                    emailobj = EmailMessage(subject, body, EMAIL_FROM, to=contact_email, headers = {'Reply-To': EMAIL_REPPLY})
                    emailobj.send()
                    message = _('%(name)s. Thanks for your message. We will answer soon.') % {'name': contact_detail.name}
                except:
                    message = _('Error SMTP server send email. Sorry. Can you try later?')
        else:
            message = _('Sorry! This form is not valid. Try again.')

    html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)
    
    title = _('Contact %(name)s') % {'name': contact_detail.name}
    metakeywords = contact_detail.name
    metadescription = _('Contact %(name)s details') % {'name': contact_detail.name}

    return render_to_response("contact/form.html", {
                                        'contact': contact_detail,
                                        'title': title,
                                        'metakeywords': metakeywords,
                                        'metadescription': metadescription,
                                        'message': message,
                                        'html_captcha': html_captcha,
                                        }, context_instance=RequestContext(request))
Exemplo n.º 23
0
def compare(request):
    """
    Compare products
    """

    site_configuration = siteConfiguration(SITE_ID)

    values = []
    products = []

    if 'compare' in request.session:
        products = request.session['compare']

    path = request.path_info.split('/')
    if 'remove' in path:
        kwargs = {
            'slug_' + get_language(): path[-1],  #slug is unique
        }
        tplproduct = ProductTemplate.objects.filter(**kwargs)
        if tplproduct.count() > 0:
            try:
                products.remove(tplproduct[0].id)
            except:
                pass

    if 'add' in path:
        kwargs = {
            'slug_' + get_language(): path[-1],  #slug is unique
        }
        tplproduct = ProductTemplate.objects.filter(**kwargs)
        if tplproduct.count() > 0:
            products.append(tplproduct[0].id)

    products = [x for x in set(products)]
    products = request.session['compare'] = products

    products_tmpl = ProductTemplate.objects.filter(id__in=products)

    # get price and base_image product
    for tplproduct in products_tmpl:
        product_products = tplproduct.product_product_set.order_by('price')
        if not product_products.count():
            continue
        base_image = product_products[0].get_base_image()
        values.append({
            'product': tplproduct,
            'name': tplproduct.name.lower(),
            'product_variant': product_products.count(),
            'price': product_products[0].price,
            'price_normal': product_products[0].price,
            'price_special': product_products[0].price_special,
            'position': tplproduct.position,
            'base_image': base_image,
        })

    title = _('Compare Products')
    metadescription = _(
        'Compare products of %s') % site_configuration.site_title

    return render_to_response("catalog/compare.html", {
        'title': title,
        'metadescription': metadescription,
        'products': values,
        'currency': DEFAULT_CURRENCY,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 24
0
def checkout(request):
    """
    Checkout. Order Cart
    """

    context_instance = RequestContext(request)

    if 'sale_order' in request.session:
        return HttpResponseRedirect(
            "%s/sale/order/%s" %
            (context_instance['LOCALE_URI'], request.session['sale_order']))

    site_configuration = siteConfiguration(SITE_ID)

    message = False
    partner_id = checkPartnerID(request)
    if not partner_id:
        error = _(
            'Are you a customer? Please, contact us. We will create a new role'
        )
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))
    full_name = checkFullName(request)
    conn = connOOOP()
    if not conn:
        error = _(
            'Error when connecting with our ERP. Try again or cantact us')
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    order = check_order(conn, partner_id, OERP_SALE)

    if order == 'error':
        return HttpResponseRedirect("%s/partner/partner/" %
                                    (context_instance['LOCALE_URI']))

    if request.method == 'POST':
        qty = int(request.POST['qty'])
        code = request.POST['code']
        #check product is available to add to cart
        product = check_product(conn, code)
        if product:
            #check if this product exist
            product_line = conn.SaleOrderLine.filter(order_id=order.id,
                                                     product_id=product.id)
            product = conn.ProductProduct.get(product.id)
            partner = conn.ResPartner.get(partner_id)

            if len(product_line) > 0:  #product line exist -> update
                order_line = conn.SaleOrderLine.get(product_line[0].id)
                order_line.product_uom_qty = qty + product_line[
                    0].product_uom_qty
                order_line.save()
            else:  #product line not exist -> create
                if partner.property_product_pricelist:
                    pricelist = partner.property_product_pricelist.id
                else:
                    shop = conn.SaleShop.get(OERP_SALE)
                    pricelist = shop.pricelist_id.id
                values = [
                    [order.id],  #ids
                    pricelist,  #pricelist
                    product.id,  #product
                    qty,  #qty
                    False,  #uom
                    0,  #qty_uos
                    False,  #uos
                    '',  #name
                    partner_id,  #partner_id
                ]
                product_id_change = conn_webservice('sale.order.line',
                                                    'product_id_change',
                                                    values)

                sale_order_add_product = True
                if product_id_change['warning'] and SALE_ORDER_PRODUCT_CHECK:
                    not_enought_stock = _('Not enough stock !')
                    sale_order_add_product = False

                if sale_order_add_product:
                    product_value = product_id_change['value']
                    order_line = conn.SaleOrderLine.new()
                    order_line.order_id = order
                    order_line.name = product_id_change['value']['name']
                    if 'notes' in product_value:
                        order_line.notes = product_id_change['value']['notes']
                    order_line.product_id = product
                    order_line.product_uom_qty = qty
                    order_line.product_uom = product.product_tmpl_id.uom_id
                    order_line.delay = product_id_change['value']['delay']
                    order_line.th_weight = product_id_change['value'][
                        'th_weight']
                    order_line.type = product_id_change['value']['type']
                    order_line.price_unit = product_id_change['value'][
                        'price_unit']
                    order_line.purchase_price = product_id_change['value'][
                        'purchase_price']
                    order_line.tax_id = [
                        conn.AccountTax.get(t_id)
                        for t_id in product_id_change['value']['tax_id']
                    ]
                    order_line.product_packaging = ''
                    order_line.save()
                else:
                    message = product_id_change['warning']

                if message and 'title' in message:
                    message = message['title']

            #recalcule order (refresh amount)
            order = check_order(conn, partner_id, OERP_SALE)

    #list order lines
    lines = conn.SaleOrderLine.filter(order_id=order.id)

    title = _('Checkout')
    metadescription = _('Checkout order %s') % (site_configuration.site_title)

    values = {
        'title': title,
        'metadescription': metadescription,
        'message': message,
        'order': order,
        'lines': lines,
    }

    if len(lines) > 0:
        #delivery
        try:
            values['deliveries'] = conn_webservice('sale.order',
                                                   'delivery_cost', [order.id])
            delivery = True
        except:
            logging.basicConfig(filename=LOGFILE, level=logging.INFO)
            logging.info('[%s] %s' % (time.strftime(
                '%Y-%m-%d %H:%M:%S'
            ), 'Need configure grid delivery in this shop or delivery grid not available'
                                      ))
            values['deliveries'] = []

        #Address invoice/delivery
        values['address_invoices'] = conn.ResPartnerAddress.filter(
            partner_id=partner_id, type='invoice')
        values['address_deliveries'] = conn.ResPartnerAddress.filter(
            partner_id=partner_id, type='delivery')
        sale_shop = conn.SaleShop.filter(id=OERP_SALE)[0]

        #order payment by sequence
        payments = []
        if sale_shop.zoook_payment_types:
            payment_commission = False
            for payment_type in sale_shop.zoook_payment_types:
                if payment_type.commission:
                    payment_commission = True
                payments.append({
                    'sequence': payment_type.sequence,
                    'app_payment': payment_type.app_payment,
                    'name': payment_type.payment_type_id.name
                })
            #if payment commission is available, recalculate extra price
            if payment_commission:
                payments = conn_webservice('zoook.sale.shop.payment.type',
                                           'get_payment_commission',
                                           [order.id])
        else:
            logging.basicConfig(filename=LOGFILE, level=logging.INFO)
            logging.info('[%s] %s' %
                         (time.strftime('%Y-%m-%d %H:%M:%S'),
                          'Need configure payment available in this shop'))

        values['payments'] = sorted(payments, key=lambda k: k['sequence'])

    values['countries'] = ResCountry.objects.all()
    values['country_default'] = COUNTRY_DEFAULT

    return render_to_response("sale/checkout.html",
                              values,
                              context_instance=RequestContext(request))
Exemplo n.º 25
0
 def items(self):
     site_configuration = siteConfiguration(SITE_ID)
     return ProductTemplate.objects.order_by('-created_on')[:site_configuration.rss_max]
Exemplo n.º 26
0
def manufacturer(request, manufacturer):
    """Manufacturer Detail and Products
    :param request
    :param manufacturer
    :return render_to_response
    """

    values = []

    site_configuration = siteConfiguration(SITE_ID)

    kwargs = {
        'slug': manufacturer,  #slug is unique
    }
    if not request.user.is_staff:
        kwargs['active'] = True
    manufacturer = get_object_or_404(ResManufacturer, **kwargs)

    default = 'position'
    set_paginator_options(request, default)

    #top category manufacturer
    categories_manufacturer = []
    top = ProductCategory.objects.filter(parent=None)
    categories = ProductCategory.objects.filter(
        parent=top[0], status=True).order_by('position')
    for category in categories:
        products_tmpl = ProductTemplate.objects.filter(
            Q(manufacturer=manufacturer), Q(product_product_set__active=True),
            Q(categ=category),
            Q(visibility='all') | Q(visibility='catalog'))
        total = products_tmpl.count()
        categories_manufacturer.append([category, total])

    qtmpl, qprod = ProductTemplate.get_qattributes(request)

    products_tmpl = ProductTemplate.objects.filter(
        Q(**qtmpl), Q(**qprod), Q(manufacturer=manufacturer),
        Q(product_product_set__active=True),
        Q(visibility='all') | Q(visibility='catalog'))
    total = products_tmpl.count()

    # get price and base_image product
    for tplproduct in products_tmpl:
        product_products = tplproduct.product_product_set.order_by('price')
        if not product_products.count():
            continue
        base_image = product_products[0].get_base_image()
        values.append({
            'product': tplproduct,
            'name': tplproduct.name.lower(),
            'product_variant': product_products.count(),
            'price': product_products[0].get_price(),
            'price_normal': product_products[0].price,
            'price_special': product_products[0].price_special,
            'position': tplproduct.position,
            'base_image': base_image
        })

    # == order by position, name or price ==
    values.sort(key=lambda x: x[request.session['order']],
                reverse=request.session['order_by'] == 'desc')

    num_pages = get_num_pages(products_tmpl, request.session['paginator'])

    title = _("%(manufacturer)s - %(site)s - Page %(page)s of %(total)s") % {
        'manufacturer': manufacturer.name,
        'site': site_configuration.site_title,
        'page': int(request.GET.get('page', '1')),
        'total': num_pages,
    }
    metadescription = _(
        'Buy %(name)s on %(site)s. Page %(page)s of %(total)s') % {
            'name': manufacturer.name,
            'site': site_configuration.site_title,
            'page': int(request.GET.get('page', '1')),
            'total': num_pages,
        }
    metakeywords = manufacturer.name

    change_manufacturer = request.user.has_perm(
        'catalog.change_resmanufacturer')

    values = {
        'title': title,
        'metakeywords': metakeywords,
        'metadescription': metadescription,
        'manufacturer': manufacturer,
        'categories': categories_manufacturer,
        'values': values,
        'total': total,
        'order_option': request.session['order'],
        'order_by_option': request.session['order_by'],
        'paginator_option': request.session['paginator'],
        'paginator_items': PAGINATOR_ITEMS,
        'currency': DEFAULT_CURRENCY,
        'catalog_orders': CATALOG_ORDERS,
        'change_manufacturer': change_manufacturer,
    }

    return render_to_response("catalog/manufacturer.html",
                              values,
                              context_instance=RequestContext(request))
Exemplo n.º 27
0
def manufacturer(request, manufacturer):
    """Manufacturer Detail and Products
    :param request
    :param manufacturer
    :return render_to_response
    """

    values = []

    site_configuration = siteConfiguration(SITE_ID)

    kwargs = {
        'slug': manufacturer, #slug is unique
    }
    if not request.user.is_staff:
        kwargs['active'] = True
    manufacturer = get_object_or_404(ResManufacturer, **kwargs)

    default = 'position'
    set_paginator_options(request, default)

    #top category manufacturer
    categories_manufacturer = []
    top = ProductCategory.objects.filter(parent=None)
    categories = ProductCategory.objects.filter(parent=top[0],status=True).order_by('position')
    for category in categories:
        products_tmpl = ProductTemplate.objects.filter(
            Q(manufacturer=manufacturer),
            Q(product_product_set__active=True),
            Q(categ=category),
            Q(visibility='all') | 
            Q(visibility='catalog')
        )
        total = products_tmpl.count()
        categories_manufacturer.append([category,total])

    qtmpl, qprod = ProductTemplate.get_qattributes(request)

    products_tmpl = ProductTemplate.objects.filter(
        Q(**qtmpl),
        Q(**qprod),
        Q(manufacturer=manufacturer),
        Q(product_product_set__active=True),
        Q(visibility='all') | 
        Q(visibility='catalog')
    )
    total = products_tmpl.count()

    # get price and base_image product
    for tplproduct in products_tmpl:
        product_products = tplproduct.product_product_set.order_by('price')
        if not product_products.count():
            continue
        base_image = product_products[0].get_base_image()
        values.append({
                'product': tplproduct,
                'name': tplproduct.name.lower(), 
                'product_variant': product_products.count(),
                'price': product_products[0].get_price(),
                'price_normal': product_products[0].price,
                'price_special': product_products[0].price_special,
                'position': tplproduct.position,
                'base_image': base_image
            })

    # == order by position, name or price ==
    values.sort(key=lambda x: x[request.session['order']], reverse = request.session['order_by'] == 'desc')

    num_pages = get_num_pages(products_tmpl, request.session['paginator'])

    title = _("%(manufacturer)s - %(site)s - Page %(page)s of %(total)s") % {
        'manufacturer': manufacturer.name,
        'site': site_configuration.site_title,
        'page': int(request.GET.get('page', '1')),
        'total': num_pages,
    }
    metadescription = _('Buy %(name)s on %(site)s. Page %(page)s of %(total)s') % {
            'name': manufacturer.name,
            'site': site_configuration.site_title,
            'page': int(request.GET.get('page', '1')),
            'total': num_pages,
    }
    metakeywords = manufacturer.name
    
    change_manufacturer = request.user.has_perm('catalog.change_resmanufacturer')

    values = {
        'title':title,
        'metakeywords':metakeywords,
        'metadescription':metadescription,
        'manufacturer':manufacturer,
        'categories': categories_manufacturer,
        'values': values,
        'total': total,
        'order_option': request.session['order'],
        'order_by_option': request.session['order_by'],
        'paginator_option': request.session['paginator'],
        'paginator_items': PAGINATOR_ITEMS,
        'currency': DEFAULT_CURRENCY,
        'catalog_orders': CATALOG_ORDERS,
        'change_manufacturer': change_manufacturer,
    }

    return render_to_response("catalog/manufacturer.html", values, context_instance=RequestContext(request))
Exemplo n.º 28
0
def contactForm(request, contact='default'):
    """Contact Form"""

    message = False
    contact_detail = False

    contacts = Contact.objects.all()
    if contact == 'default':
        contacts = contacts.filter(default=True, status=True)
    else:
        contacts = contacts.filter(slug=contact)

    if not contacts.count() > 0:
        raise Http404

    contact_detail = contacts[0]

    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            site_configuration = siteConfiguration(SITE_ID)

            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            contact_text = form.cleaned_data['contact_text']

            try:
                check_captcha = captcha.submit(
                    request.POST['recaptcha_challenge_field'],
                    request.POST['recaptcha_response_field'],
                    RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
            except:
                error = _('Error with captcha system. Try again.')
                return render_to_response(
                    "partner/error.html",
                    locals(),
                    context_instance=RequestContext(request))

            if check_captcha.is_valid is False:
                # Captcha is wrong show a error ...
                message = _('Error with captcha number. Copy the same number.')
            else:
                subject = _('Contact - %(name)s') % {
                    'name': site_configuration.site_title
                }
                body = _(
                    'This email is generated with Contact Module from %(site)s\n\n%(name)s - %(email)s\n%(message)s'
                ) % {
                    'site': site_configuration.site_title,
                    'name': name,
                    'email': email,
                    'message': contact_text
                }

                emails = contact_detail.email and contact_detail.email or site_configuration.contact_email
                contact_email = emails.split(',')
                if len(contact_email) == 0:
                    contact_email = [contact_email]

                try:
                    emailobj = EmailMessage(subject,
                                            body,
                                            EMAIL_FROM,
                                            to=contact_email,
                                            headers={'Reply-To': EMAIL_REPPLY})
                    emailobj.send()
                    message = _(
                        '%(name)s. Thanks for your message. We will answer soon.'
                    ) % {
                        'name': contact_detail.name
                    }
                except:
                    message = _(
                        'Error SMTP server send email. Sorry. Can you try later?'
                    )
        else:
            message = _('Sorry! This form is not valid. Try again.')

    html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)

    title = _('Contact %(name)s') % {'name': contact_detail.name}
    metakeywords = contact_detail.name
    metadescription = _('Contact %(name)s details') % {
        'name': contact_detail.name
    }

    return render_to_response("contact/form.html", {
        'contact': contact_detail,
        'title': title,
        'metakeywords': metakeywords,
        'metadescription': metadescription,
        'message': message,
        'html_captcha': html_captcha,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 29
0
def compare(request):
    """
    Compare products
    """

    site_configuration = siteConfiguration(SITE_ID)

    values = []
    products = []

    if 'compare' in request.session:
        products = request.session['compare']

    path = request.path_info.split('/')
    if 'remove' in path:
        kwargs = {
            'slug_'+get_language(): path[-1], #slug is unique
        }
        tplproduct = ProductTemplate.objects.filter(**kwargs)
        if tplproduct.count() > 0:
            try:
                products.remove(tplproduct[0].id)
            except:
                pass

    if 'add' in path:
        kwargs = {
            'slug_'+get_language(): path[-1], #slug is unique
        }
        tplproduct = ProductTemplate.objects.filter(**kwargs)
        if tplproduct.count() > 0:
            products.append(tplproduct[0].id)

    products = [x for x in set(products)]
    products = request.session['compare'] = products

    products_tmpl = ProductTemplate.objects.filter(id__in=products)

    # get price and base_image product
    for tplproduct in products_tmpl:
        product_products = tplproduct.product_product_set.order_by('price')
        if not product_products.count():
            continue
        base_image = product_products[0].get_base_image()
        values.append({
                'product': tplproduct,
                'name': tplproduct.name.lower(), 
                'product_variant': product_products.count(),
                'price': product_products[0].price,
                'price_normal': product_products[0].price,
                'price_special': product_products[0].price_special,
                'position': tplproduct.position,
                'base_image': base_image,
            })

    title = _('Compare Products')
    metadescription = _('Compare products of %s') % site_configuration.site_title

    return render_to_response("catalog/compare.html", {
                    'title': title,
                    'metadescription': metadescription,
                    'products': values,
                    'currency': DEFAULT_CURRENCY,
                }, context_instance=RequestContext(request))
Exemplo n.º 30
0
def register(request):
    """Registration page. If exists session, redirect profile"""

    context_instance=RequestContext(request)

    if request.user.is_authenticated(): #redirect profile
        return HttpResponseRedirect("%s/partner/profile/" % context_instance['LOCALE_URI'])

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Create an Account')
    metadescription = _('Create an Account of %(site)s') % {'site':site_configuration.site_title}

    if request.method == "POST":
        message = []
        users = ''
        emails = ''
        error = []
        country = False

        form = UserCreationForm(request.POST)
        data = request.POST.copy()

        username = data['username']
        email = data['email']
        password = data['password1']
        name = data['name']
        vat_code = data['vat_code']
        vat = data['vat']
        street = data['street']
        zip = data['zip']
        city = data['city']
        
        countries = ResCountry.objects.filter(code=vat_code)
        if len(countries)>0:
            country = countries[0].id
            
        if (data['password1'] == data['password2']) and country:
            if form.is_valid():
                if len(username) < USER_LENGHT:
                    msg = _('Username is short. Minimum %(size)s characters') % {'size': USER_LENGHT}
                    message.append(msg)
                if len(password) < KEY_LENGHT:
                    msg = _('Password is short. Minimum %(size)s characters') % {'size': KEY_LENGHT}
                    message.append(msg)

                if is_valid_email(email):
                    # check if user not exist
                    users = User.objects.filter(username__exact=username)
                    emails = User.objects.filter(email__exact=email)
                else:
                    msg = _('Sorry. This email is not valid. Try again')
                    message.append(msg)

                try:
                    check_captcha = captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
                except:
                    error = _('Error with captcha system. Try again.')
                    return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))

                if check_captcha.is_valid is False: # captcha not valid
                    msg = _('Error with captcha number. Copy same number.')
                    message.append(msg)

                if users:
                    msg = _('Sorry. This user already exists. Use another username')
                    message.append(msg)
                if emails:
                    msg = _('Sorry. This email already exists. Use another email or remember password')
                    message.append(msg)

                #check if this vat exists ERP
                if not message:
                    conn = connOOOP()
                    if not conn:
                        error = _('Error when connecting with our ERP. Try again or cantact us')
                        return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))

                    partner = conn.ResPartner.filter(vat__ilike=data['vat_code']+data['vat'])
                    if len(partner) > 0:
                        msg = _('Sorry. This VAT already exists our ERP. Contact Us for create a new user')
                        message.append(msg)

                #check if this vat valid
                if not message:
                    checkvat = data['vat_code']+data['vat']
                    checkvat = checkvat.upper()
                    check_vat = conn_webservice('res.partner', 'dj_check_vat', [checkvat, OERP_SALE])

                    if not check_vat:
                        msg = _('Vat not valid. Check if vat is correct')
                        message.append(msg)
                
                #create new partner and user
                if len(message) == 0:
                    # create partner
                    partner = conn.ResPartner.new()
                    partner.name = data['name']
                    partner.vat = checkvat
                    partner.dj_username = data['username']
                    partner.dj_email = data['email']
                    partner_id = partner.save()
                    
                    # create address partner
                    address_types = ['contact','invoice','delivery']
                    for address_type in address_types:
                        address = conn.ResPartnerAddress.new()
                        address.name = data['name']
                        address.partner_id = conn.ResPartner.get(partner_id)
                        address.type = address_type
                        address.street = data['street']
                        address.zip = data['zip']
                        address.city = data['city']
                        address.country_id = conn.ResCountry.get(country)
                        address.email = data['email']
                        address.phone = data['phone']
                        address_id = address.save()
                    
                    # create user
                    # split name: first_name + last name
                    name = data['name'].split(' ')
                    if len(name) > 1:
                        first_name = name[0]
                        del name[0]
                        last_name = " ".join(name)
                    else:
                        first_name = ''
                        last_name = data['name']
                    user = User.objects.create_user(username, email, password)
                    user.first_name = first_name
                    user.last_name = last_name
                    user.is_staff = False
                    user.save()

                    # create authProfile
                    authProfile = AuthProfile(user=user,partner_id=partner_id)
                    authProfile.save()

                    try:
                        # send email
                        subject = _('New user is added - %(name)s') % {'name':site_configuration.site_title}
                        body = _("This email is generated automatically from %(site)s\n\nUsername: %(username)s\nPassword: %(password)s\n\n%(live_url)s\n\nPlease, don't answer this email") % {'site':site_configuration.site_title,'username':username,'password':password,'live_url':LIVE_URL}
                        emailobj = EmailMessage(subject, body, EMAIL_FROM, to=[email], headers = {'Reply-To': EMAIL_REPPLY})
                        emailobj.send()
                    finally:
                        # authentification / login user
                        user = authenticate(username=username, password=password)
                        auth_login(request, user)
                        return HttpResponseRedirect("%s/partner/profile/" % context_instance['LOCALE_URI'])
            else:
                msg = _("Sorry. Error form values. Try again")
                message.append(msg)
        else:
            msg = _("Sorry. Passwords do not match. Try again")
            message.append(msg)

    form = UserCreationForm()
    html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)

    countries = ResCountry.objects.all()
    country_default = COUNTRY_DEFAULT
    
    return render_to_response("partner/register.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 31
0
def register(request):
    """Registration page. If exists session, redirect profile"""

    context_instance = RequestContext(request)

    if request.user.is_authenticated():  #redirect profile
        return HttpResponseRedirect("%s/partner/profile/" %
                                    context_instance['LOCALE_URI'])

    site_configuration = siteConfiguration(SITE_ID)

    title = _('Create an Account')
    metadescription = _('Create an Account of %(site)s') % {
        'site': site_configuration.site_title
    }

    if request.method == "POST":
        message = []
        users = ''
        emails = ''
        error = []
        country = False

        form = UserCreationForm(request.POST)
        data = request.POST.copy()

        username = data['username']
        email = data['email']
        password = data['password1']
        name = data['name']
        vat_code = data['vat_code']
        vat = data['vat']
        street = data['street']
        zip = data['zip']
        city = data['city']

        countries = ResCountry.objects.filter(code=vat_code)
        if len(countries) > 0:
            country = countries[0].id

        if (data['password1'] == data['password2']) and country:
            if form.is_valid():
                if len(username) < USER_LENGHT:
                    msg = _(
                        'Username is short. Minimum %(size)s characters') % {
                            'size': USER_LENGHT
                        }
                    message.append(msg)
                if len(password) < KEY_LENGHT:
                    msg = _(
                        'Password is short. Minimum %(size)s characters') % {
                            'size': KEY_LENGHT
                        }
                    message.append(msg)

                if is_valid_email(email):
                    # check if user not exist
                    users = User.objects.filter(username__exact=username)
                    emails = User.objects.filter(email__exact=email)
                else:
                    msg = _('Sorry. This email is not valid. Try again')
                    message.append(msg)

                try:
                    check_captcha = captcha.submit(
                        request.POST['recaptcha_challenge_field'],
                        request.POST['recaptcha_response_field'],
                        RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
                except:
                    error = _('Error with captcha system. Try again.')
                    return render_to_response(
                        "partner/error.html",
                        locals(),
                        context_instance=RequestContext(request))

                if check_captcha.is_valid is False:  # captcha not valid
                    msg = _('Error with captcha number. Copy same number.')
                    message.append(msg)

                if users:
                    msg = _(
                        'Sorry. This user already exists. Use another username'
                    )
                    message.append(msg)
                if emails:
                    msg = _(
                        'Sorry. This email already exists. Use another email or remember password'
                    )
                    message.append(msg)

                #check if this vat exists ERP
                if not message:
                    conn = connOOOP()
                    if not conn:
                        error = _(
                            'Error when connecting with our ERP. Try again or cantact us'
                        )
                        return render_to_response(
                            "partner/error.html",
                            locals(),
                            context_instance=RequestContext(request))

                    partner = conn.ResPartner.filter(
                        vat__ilike=data['vat_code'] + data['vat'])
                    if len(partner) > 0:
                        msg = _(
                            'Sorry. This VAT already exists our ERP. Contact Us for create a new user'
                        )
                        message.append(msg)

                #check if this vat valid
                if not message:
                    checkvat = data['vat_code'] + data['vat']
                    checkvat = checkvat.upper()
                    check_vat = conn_webservice('res.partner', 'dj_check_vat',
                                                [checkvat, OERP_SALE])

                    if not check_vat:
                        msg = _('Vat not valid. Check if vat is correct')
                        message.append(msg)

                #create new partner and user
                if len(message) == 0:
                    # create partner
                    partner = conn.ResPartner.new()
                    partner.name = data['name']
                    partner.vat = checkvat
                    partner.dj_username = data['username']
                    partner.dj_email = data['email']
                    partner_id = partner.save()

                    # create address partner
                    address_types = ['contact', 'invoice', 'delivery']
                    for address_type in address_types:
                        address = conn.ResPartnerAddress.new()
                        address.name = data['name']
                        address.partner_id = conn.ResPartner.get(partner_id)
                        address.type = address_type
                        address.street = data['street']
                        address.zip = data['zip']
                        address.city = data['city']
                        address.country_id = conn.ResCountry.get(country)
                        address.email = data['email']
                        address.phone = data['phone']
                        address_id = address.save()

                    # create user
                    # split name: first_name + last name
                    name = data['name'].split(' ')
                    if len(name) > 1:
                        first_name = name[0]
                        del name[0]
                        last_name = " ".join(name)
                    else:
                        first_name = ''
                        last_name = data['name']
                    user = User.objects.create_user(username, email, password)
                    user.first_name = first_name
                    user.last_name = last_name
                    user.is_staff = False
                    user.save()

                    # create authProfile
                    authProfile = AuthProfile(user=user, partner_id=partner_id)
                    authProfile.save()

                    try:
                        # send email
                        subject = _('New user is added - %(name)s') % {
                            'name': site_configuration.site_title
                        }
                        body = _(
                            "This email is generated automatically from %(site)s\n\nUsername: %(username)s\nPassword: %(password)s\n\n%(live_url)s\n\nPlease, don't answer this email"
                        ) % {
                            'site': site_configuration.site_title,
                            'username': username,
                            'password': password,
                            'live_url': LIVE_URL
                        }
                        emailobj = EmailMessage(
                            subject,
                            body,
                            EMAIL_FROM,
                            to=[email],
                            headers={'Reply-To': EMAIL_REPPLY})
                        emailobj.send()
                    finally:
                        # authentification / login user
                        user = authenticate(username=username,
                                            password=password)
                        auth_login(request, user)
                        return HttpResponseRedirect(
                            "%s/partner/profile/" %
                            context_instance['LOCALE_URI'])
            else:
                msg = _("Sorry. Error form values. Try again")
                message.append(msg)
        else:
            msg = _("Sorry. Passwords do not match. Try again")
            message.append(msg)

    form = UserCreationForm()
    html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)

    countries = ResCountry.objects.all()
    country_default = COUNTRY_DEFAULT

    return render_to_response("partner/register.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 32
0
def remember(request):
    """Remember password"""

    message = []
    site_configuration = siteConfiguration(SITE_ID)

    title = _('Remember')
    metadescription = _('Remember account of %(site)s') % {
        'site': site_configuration.site_title
    }

    if request.method == "POST":
        form = UserCreationForm(request.POST)
        data = request.POST.copy()

        email = data['email']

        check_captcha = captcha.submit(
            request.POST['recaptcha_challenge_field'],
            request.POST['recaptcha_response_field'], RECAPTCHA_PRIVATE_KEY,
            request.META['REMOTE_ADDR'])
        if check_captcha.is_valid is False:  # captcha not valid
            msg = _('Error with captcha number. Copy the same number.')
            message.append(msg)
        else:
            if is_valid_email(email):
                # check if user  exist
                users = User.objects.filter(email__exact=email)
                if len(users) > 0:
                    #create new password
                    key = User.objects.make_random_password(length=KEY_LENGHT)
                    # update password
                    user = User.objects.get(id=users[0].id)
                    user.set_password(key)
                    user.save()
                    # send email
                    subject = _('Remember username - %(name)s') % {
                        'name': site_configuration.site_title
                    }
                    body = _(
                        "This email is generated  automatically from %(site)s\n\nUsername: %(username)s\nPassword: %(password)s\n\n%(live_url)s\n\nPlease, do not answer the email"
                    ) % {
                        'site': site_configuration.site_title,
                        'username': user.username,
                        'password': key,
                        'live_url': LIVE_URL
                    }
                    email = EmailMessage(subject,
                                         body,
                                         EMAIL_FROM,
                                         to=[user.email],
                                         headers={'Reply-To': EMAIL_REPPLY})
                    email.send()
                    email = ''
                    msg = _('A new password are sent to %(email)s') % {
                        'email': user.email
                    }
                    message.append(msg)
                else:
                    msg = _('Sorry. This email not exist. Try again')
                    message.append(msg)
            else:
                msg = _('Sorry. This email is not valid. Try again')
                message.append(msg)

    form = UserCreationForm()
    html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)

    return render_to_response("partner/remember.html",
                              locals(),
                              context_instance=RequestContext(request))