Пример #1
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 = _(u'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 = _(u'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))
Пример #2
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 = _(u'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 = _(
        u'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))
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,
        'LOCALE_URI': sufix,
        'USER_NAME': user_name,
        'FULL_NAME': full_name,
        'DEBUG': DEBUG or DEVEL,
    }
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,
        'LOCALE_URI': sufix,
        'USER_NAME': user_name,
        'FULL_NAME': full_name,
        'DEBUG': DEBUG or DEVEL,
    }
Пример #5
0
def changepassword(request):
    """Change Password page"""

    site_configuration = siteConfiguration(SITE_ID)

    title = _(u'Change password')
    metadescription = _(u'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': get_live_url(request)
                    }
                    email = EmailMessage(subject,
                                         body,
                                         to=[request.user.email])
                    try:
                        email.send()
                    except Exception, e:
                        logging.error(
                            "Error sending new password to user email.\nException: %s"
                            % str(e))
                        error = _(
                            "Error sending new password. Try again, or contact with the Administrator."
                        )
                    else:
                        error = _("New password is added.")
                else:
                    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.")
Пример #6
0
def index(request):
    """
    Sermepa (Servired)
    OpenERP Payment Type App is: sermepa
    Sale Order Reference:
        - Only numbers, not SO0001
        - Minimium 4, Maximun 12
    """

    title = _(u'Payment Credit Card Servired')

    if not 'sale_order' in request.session:
        error = _('Order number is not available. Use navigation menu.')
        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))

    payment_type = conn.ZoookSaleShopPaymentType.filter(app_payment='sermepa')
    orders = conn.SaleOrder.filter(name=request.session['sale_order'])
        
    if (len(payment_type) > 0) and len(orders) > 0:
        #change payment_type = done
        order = orders[0]
        order.payment_state = 'done'
        order.save()

        site = Site.objects.get_current()
        site_configuration = siteConfiguration(SITE_ID)

        sermepa_dict = {
            "Ds_Merchant_Titular": SERMEPA_MERCHANT_NAME,
            "Ds_Merchant_MerchantData": '',
            "Ds_Merchant_MerchantName": SERMEPA_MERCHANT_NAME,
            "Ds_Merchant_ProductDescription": site_configuration.site_title,
            "Ds_Merchant_Amount": int(order.amount_total* 100),
            "Ds_Merchant_TransactionType": SERMEPA_TRANS_TYPE,
            "Ds_Merchant_Terminal": SERMEPA_TERMINAL,
            "Ds_Merchant_MerchantCode": SERMEPA_MERCHANT_CODE,
            "Ds_Merchant_Order": order.name,
            "Ds_Merchant_Currency": SERMEPA_CURRENCY,
            "Ds_Merchant_MerchantURL": SERMEPA_MERCHANT_URL,
            "Ds_Merchant_UrlOK": "http://%s%s" % (site.domain, '/payment/sermepa/confirm'),
            "Ds_Merchant_UrlKO": "http://%s%s" % (site.domain, '/payment/sermepa/error'),
        }

        form = SermepaPaymentForm(initial=sermepa_dict)
        debug = DEBUG
        logging.info('Order %s: sermepa form and redirect' % order.name)
        return HttpResponse(render_to_response('sermepa/form.html', locals(), context_instance=RequestContext(request)))

    else:
        return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))
Пример #7
0
def profile(request):
    """Profile page"""
    
    site_configuration = siteConfiguration(SITE_ID)

    full_name = checkFullName(request)

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

    return render_to_response("partner/profile.html", locals(), context_instance=RequestContext(request))
Пример #8
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)
    vat = format_vat(partner.vat)
    partnet_title = False
    if partner.title:
        partnet_title = partner.title.name

    if request.method == 'POST':
        data = get_contact_data(request.POST.copy())
        for contact_id in data.keys():
            if contact_id == 'newaddress':
                address = conn.ResPartnerAddress.new()
                address.partner_id = partner
            else:
                address = conn.ResPartnerAddress.get(contact_id)
            address.street = data[contact_id]['street']
            address.zip = data[contact_id]['zip']
            address.city = data[contact_id]['city']
            address.phone = data[contact_id]['phone']
            address.type = data[contact_id]['type']
            address_id = address.save()
        message = [_('Successfully saved profile.')]

    addresses = conn.ResPartnerAddress.filter(partner_id=partner_id, type__in=['delivery', 'invoice', 'default', False], order='id')
    del_have = False
    inv_have = False
    i = 0
    while i<len(addresses) and (not del_have or not inv_have):
        if (not del_have or not inv_have) and addresses[i].type in ['default', False]:
            del_have = True
            inv_have = True
        if not del_have and addresses[i].type == 'delivery':
            del_have = True
        if not inv_have and addresses[i].type == 'invoice':
            inv_have = True
        i+=1

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

    return render_to_response("partner/partner.html", locals(), context_instance=RequestContext(request))
Пример #9
0
def index(request):
    """All root category products (Featured Products)"""

    site_configuration = siteConfiguration(SITE_ID)
    title = site_configuration.site_title
    metadescription = site_configuration.site_metadescription
    metakeywords = site_configuration.site_metakeywords

    values = []

    categories = ProductCategory.objects.filter(parent=None)
    root_category = categories[0]

    if len(categories)>0:
        products = ProductTemplate.objects.filter(
                            Q(product_product_set__active=True),
                            Q(categ=root_category),
                            Q(visibility='all') | Q(visibility='catalog')
                        ).distinct()

        # get price and base_image product            
        for tplproduct in products:
            prods = ProductProduct.objects.filter(product_tmpl=tplproduct.id)

            i = 0
            prod_images = []
            while i<len(prods) and len(prod_images)==0: 
                prod_images = ProductImages.objects.filter(product=prods[i].id,base_image=True)
                i+=1

            base_image = False
            if len(prod_images) > 0:
                base_image = prod_images[0]

            values.append({'product': tplproduct, 'name': tplproduct.name.lower(), 'product_variant': len(prods), 'prods': prods, 'base_image': base_image})

        # == template values ==
        category_values = {
            'title': title,
            'metadescription': metadescription,
            'metakeywords': metakeywords,
            'values': values,
            'products': products,
            'currency': DEFAULT_CURRENCY,
            'currency_position': CURRENCY_LABEL_POSITION,
            'compare_on': COMPARE_ON,
            'category_decription': root_category.description if root_category.description != 'False' else None,
            'update_price': UPDATE_PRICE,
        }
        return render_to_response("index.html", category_values, context_instance=RequestContext(request))
    else:
        raise Http404(_('This category is not available because you navigate with bookmarks or search engine. Use navigation menu'))
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,
    }
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,
    }
Пример #12
0
def remember(request):
    """Remember password"""

    message = []
    site_configuration = siteConfiguration(SITE_ID)

    title = _(u'Remember')
    metadescription = _(u'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']

        if RECAPTCHA_PUB_KEY != '':
            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)
        if RECAPTCHA_PUB_KEY == '' or len(message)==0:
            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':get_live_url(request)}
                    email = EmailMessage(subject, body, to=[user.email])
                    try:
                        email.send()
                    except Exception, e:
                        logging.error("Error sending new password to user email.\nException: %s" % str(e))
                        msg = _("Error sending new password. Try again, or contact with the Administrator.")
                    else:
                        msg = _('A new password are sent to %(email)s') % {'email':user.email}
                    email = ''
                    message.append(msg)
                else:
                    msg = _('Sorry. This email not exist. Try again.')
                    message.append(msg)
            else:
                msg = _('Sorry. The email is not valid. Try again.')
                message.append(msg)
Пример #13
0
def profile(request):
    """Profile page"""

    site_configuration = siteConfiguration(SITE_ID)

    full_name = checkFullName(request)

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

    return render_to_response("partner/profile.html",
                              locals(),
                              context_instance=RequestContext(request))
Пример #14
0
def index(request):
    """
    Catalog Index
    All Categories list
    """

    values = ProductCategory.get_categories_list()

    site_configuration = siteConfiguration(SITE_ID)

    title = _(u'Categories')
    metadescription = _(u'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))
Пример #15
0
def index(request):
    """
    Paypal
    OpenERP Payment Type App is: paypal
    """

    title = _(u'Payment Paypal')

    if not 'sale_order' in request.session:
        error = _('Order number is not available. Use navigation menu.')
        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))

    payment_type = conn.ZoookSaleShopPaymentType.filter(app_payment='paypal')
    orders = conn.SaleOrder.filter(name=request.session['sale_order'])
        
    if (len(payment_type) > 0) and len(orders) > 0:
        #change payment_type = done
        order = orders[0]
        order.payment_state = 'done'
        order.save()

        site = Site.objects.get_current()
        site_configuration = siteConfiguration(SITE_ID)

        paypal_dict = {
            "business": PAYPAL_RECEIVER_EMAIL,
            "amount": order.amount_total,
            "item_name": site_configuration.site_title,
            "invoice": order.name,
            "currency_code": PAYPAL_CURRENCY,
            "notify_url": "http://%s%s" % (site.domain, '/payment/paypal/ipn'),
            "return_url": "http://%s%s" % (site.domain, '/saas/invoice/confirm'),
            "cancel_return": "http://%s%s" % (site.domain, '/payment/paypal/error'),
        }

        form = PayPalPaymentsForm(initial=paypal_dict)
        logging.info('Order %s: paypal form and redirect' % (order.name))
        return render_to_response("paypal/form.html", {'form':form, 'debug':DEBUG}, context_instance=RequestContext(request))

    else:
        return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))
Пример #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 = _(u'Login')
    metadescription = _(u'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.POST.get('redirect'):
        redirect = request.POST.get('redirect')
    if request.GET.get('next'):
        next_url = request.GET.get('next')
        redirect = base64.b64encode(request.GET.get('next'))

    return render_to_response("partner/login.html",
                              locals(),
                              context_instance=RequestContext(request))
Пример #17
0
def index(request):
    """
    Catalog Index
    All Categories list
    """

    values = ProductCategory.get_categories_list()

    site_configuration = siteConfiguration(SITE_ID)

    title = _(u'Categories')
    metadescription = _(
        u'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))
Пример #18
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
Пример #19
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 = _(u'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 = _(
        u'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))
Пример #20
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 = _(u'Login')
    metadescription = _(u'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.POST.get('redirect'):
        redirect = request.POST.get('redirect')
    if request.GET.get('next'):
        next_url = request.GET.get('next')
        redirect = base64.b64encode(request.GET.get('next'))

    return render_to_response("partner/login.html", locals(), context_instance=RequestContext(request))
Пример #21
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)
    vat = format_vat(partner.vat)
    partnet_title = False
    if partner.title:
        partnet_title = partner.title.name

    if request.method == 'POST':
        data = get_contact_data(request.POST.copy())
        for contact_id in data.keys():
            address = conn.ResPartnerAddress.get(contact_id)
            address.street = data[contact_id]['street']
            address.zip = data[contact_id]['zip']
            address.city = data[contact_id]['city']
            address.phone = data[contact_id]['phone']
            address.save()
        message = [_('Successfully saved profile.')]

    address_invoice = conn.ResPartnerAddress.filter(type='invoice',partner_id=partner_id)
    address_delivery = conn.ResPartnerAddress.filter(type='delivery',partner_id=partner_id)
    
    title = _(u'User Profile')
    metadescription = _(u'User profile of %(site)s') % {'site':site_configuration.site_title}
    
    return render_to_response("partner/partner.html", locals(), context_instance=RequestContext(request))
Пример #22
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 = _(u'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 = _(u'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))
Пример #23
0
def changepassword(request):
    """Change Password page"""

    site_configuration = siteConfiguration(SITE_ID)

    title = _(u'Change password')
    metadescription = _(u'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':get_live_url(request)}
                    email = EmailMessage(subject, body, to=[request.user.email])
                    try:
                        email.send()
                    except Exception, e:
                        logging.error("Error sending new password to user email.\nException: %s" % str(e))
                        error = _("Error sending new password. Try again, or contact with the Administrator.")
                    else:
                        error = _("New password is added.")
                else:
                    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.")
Пример #24
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 item.shortdescription
Пример #25
0
 def items(self):
     site_configuration = siteConfiguration(SITE_ID)
     return ProductTemplate.objects.order_by('-created_on')[:site_configuration.rss_max]
Пример #26
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' or request.GET.get('code'):
        if request.POST.get('code'):
            code = request.POST['code']
            qty = int(request.POST['qty'])
        else:
            code = request.GET['code']
            qty = int(request.GET['qty'])
        #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
                    partner.property_product_pricelist.id, #pricelist
                    product.id, #product
                    qty, #qty
                    False, #uom
                    0, #qty_uos
                    False, #uos
                    '', #name
                    partner_id, #partner_id
                ]
                try:
                    product_id_change = conn_webservice('sale.order.line','product_id_change', values)
                except Exception, e:
                    logging.error("Error creating/modifying the order.\nValues: %s\nException: %s" % (str(values),str(e)))
                    values = {
                            'title': _('Checkout Error'),
                            'error':_("Error creating/modifying the order. Try again, or contact with us."),
                        }
                    return render_to_response("sale/checkout.html", values, context_instance=RequestContext(request))

                sale_order_add_product = True
                not_enought_stock = None
                if product_id_change['warning'] and SALE_ORDER_PRODUCT_CHECK:
                    if SALE_ORDER_PRODUCE_PRODUCT_CHECK or product.supply_method != 'produce':
                        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:
                    if not_enought_stock != None:
                        message = not_enought_stock
                    else:
                        message = message['title']

            #recalcule order (refresh amount)
            order = check_order(conn, partner_id, OERP_SALE)
Пример #27
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 = _(u'Contact %(name)s') % {'name': contact_detail.name}
    metakeywords = contact_detail.name
    metadescription = _(u'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))
Пример #28
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 = _(u"%(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 = _(
        u'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))
Пример #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 = _(u'Compare Products')
    metadescription = _(
        u'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))
Пример #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 = _(u'Create an Account')
    metadescription = _(u'Create an Account of %(site)s') % {
        'site': site_configuration.site_title
    }
    partner_vat_required = PARTNER_VAT_REQUIRED
    country_default = COUNTRY_DEFAULT
    title_default = ''

    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']
        country_default = vat_code
        title = data['title']
        title_default = title
        vat = data['vat']
        street = data['street']
        zip = data['zip']
        city = data['city']
        phone = data['phone']
        #mobile = data['mobile']
        same_address = 'delivery-same-address' in data
        if not same_address:
            delivery_street = data['delivery_street']
            delivery_zip = data['delivery_zip']
            delivery_city = data['delivery_city']
            delivery_phone = data['delivery_phone']
            #delivery_mobile = data['delivery_mobile']

        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. The email is not valid. Try again.')
                    message.append(msg)

                if RECAPTCHA_PUB_KEY != '':
                    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 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))

                    if partner_vat_required or vat:
                        partner = conn.ResPartner.filter(vat__ilike=vat_code +
                                                         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 and (partner_vat_required or vat):
                    checkvat = vat_code + 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 = name
                    if vat:
                        partner.vat = checkvat
                    partner.dj_username = username
                    partner.dj_email = email
                    if title:
                        res_partner_title = conn.ResPartnerTitle.get(
                            int(title))
                        partner.title = res_partner_title
                        if res_partner_title.default_pricelist_id:
                            partner.property_product_pricelist = res_partner_title.default_pricelist_id
                    partner_id = partner.save()

                    # Create contact invoice address partner
                    address = conn.ResPartnerAddress.new()
                    address.name = name
                    address.partner_id = conn.ResPartner.get(partner_id)
                    address.street = street
                    address.zip = zip
                    address.city = city
                    address.phone = phone
                    #address.mobile = mobile
                    address.country_id = conn.ResCountry.get(country)
                    address.email = email
                    if not same_address:
                        address.type = 'invoice'
                    else:
                        address.type = 'default'
                    address_id = address.save()

                    if not same_address:
                        # Create contact delivery address partner
                        address = conn.ResPartnerAddress.new()
                        address.name = name
                        address.partner_id = conn.ResPartner.get(partner_id)
                        address.street = delivery_street
                        address.zip = delivery_zip
                        address.city = delivery_city
                        address.phone = delivery_phone
                        #address.mobile = delivery_mobile
                        address.country_id = conn.ResCountry.get(country)
                        address.email = email
                        address.type = 'delivery'
                        address_id = address.save()

                    # create user
                    # split name: first_name + last name
                    if len(name.split(' ')) > 1:
                        name = name.split(' ')
                        first_name = name[0]
                        del name[0]
                        last_name = ' '.join(name)
                    else:
                        first_name = name
                        last_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': get_live_url(request)
                        }
                        emailobj = EmailMessage(subject, body, to=[email])
                        emailobj.send()
                    finally:
                        # authentification / login user
                        user = authenticate(username=username,
                                            password=password)
                        auth_login(request, user)
                        if 'redirect' in request.POST:
                            redirect = base64.b64decode(
                                request.POST['redirect'])
                            return HttpResponseRedirect(redirect)

                        return HttpResponseRedirect(
                            "%s/partner/profile/" %
                            context_instance['LOCALE_URI'])
            else:
                for field in form:
                    for error in field.errors:
                        message.append(error)
        else:
            msg = _("Sorry. Passwords do not match. Try again.")
            message.append(msg)

    form = UserCreationForm()
    if RECAPTCHA_PUB_KEY != '':
        html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)
    if request.POST.get('redirect'):
        redirect = request.POST.get('redirect')
    if request.GET.get('next'):
        if request.GET.get('qty'):
            redirect = base64.b64encode(
                request.GET.get('next') + '&qty=' + request.GET.get('qty'))
        else:
            redirect = base64.b64encode(request.GET.get('next'))

    countries = ResCountry.objects.all()
    titles = ResPartnerTitle.objects.all()

    return render_to_response("partner/register.html",
                              locals(),
                              context_instance=RequestContext(request))
Пример #31
0
def index(request):
    """
    Sermepa (Servired)
    OpenERP Payment Type App is: sermepa
    Sale Order Reference:
        - Only numbers, not SO0001
        - Minimium 4, Maximun 12
    """

    title = _(u'Payment Credit Card Servired')

    if not 'sale_order' in request.session:
        error = _('Order number is not available. Use navigation menu.')
        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))

    payment_type = conn.ZoookSaleShopPaymentType.filter(app_payment='sermepa')
    orders = conn.SaleOrder.filter(name=request.session['sale_order'])

    if (len(payment_type) > 0) and len(orders) > 0:
        #change payment_type = done
        order = orders[0]
        order.payment_state = 'done'
        order.save()

        site = Site.objects.get_current()
        site_configuration = siteConfiguration(SITE_ID)

        sermepa_dict = {
            "Ds_Merchant_Titular":
            SERMEPA_MERCHANT_NAME,
            "Ds_Merchant_MerchantData":
            '',
            "Ds_Merchant_MerchantName":
            SERMEPA_MERCHANT_NAME,
            "Ds_Merchant_ProductDescription":
            site_configuration.site_title,
            "Ds_Merchant_Amount":
            int(order.amount_total * 100),
            "Ds_Merchant_TransactionType":
            SERMEPA_TRANS_TYPE,
            "Ds_Merchant_Terminal":
            SERMEPA_TERMINAL,
            "Ds_Merchant_MerchantCode":
            SERMEPA_MERCHANT_CODE,
            "Ds_Merchant_Order":
            order.name,
            "Ds_Merchant_Currency":
            SERMEPA_CURRENCY,
            "Ds_Merchant_MerchantURL":
            SERMEPA_MERCHANT_URL,
            "Ds_Merchant_UrlOK":
            "http://%s%s" % (site.domain, '/payment/sermepa/confirm'),
            "Ds_Merchant_UrlKO":
            "http://%s%s" % (site.domain, '/payment/sermepa/error'),
        }

        form = SermepaPaymentForm(initial=sermepa_dict)
        debug = DEBUG
        logging.info('Order %s: sermepa form and redirect' % order.name)
        return HttpResponse(
            render_to_response('sermepa/form.html',
                               locals(),
                               context_instance=RequestContext(request)))

    else:
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))
Пример #32
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 = _(u'Create an Account')
    metadescription = _(u'Create an Account of %(site)s') % {'site':site_configuration.site_title}
    partner_vat_required = PARTNER_VAT_REQUIRED
    country_default = COUNTRY_DEFAULT
    title_default = ''

    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']
        country_default = vat_code
        title = data['title']
        title_default = title
        vat = data['vat']
        street = data['street']
        zip = data['zip']
        city = data['city']
        phone = data['phone']
        #mobile = data['mobile']
        same_address = 'delivery-same-address' in data
        if not same_address:
            delivery_street = data['delivery_street']
            delivery_zip = data['delivery_zip']
            delivery_city = data['delivery_city']
            delivery_phone = data['delivery_phone']
            #delivery_mobile = data['delivery_mobile']

        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. The email is not valid. Try again.')
                    message.append(msg)

                if RECAPTCHA_PUB_KEY != '':
                    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 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))

                    if partner_vat_required or vat:
                        partner = conn.ResPartner.filter(vat__ilike = vat_code+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 and (partner_vat_required or vat):
                    checkvat = vat_code + 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 = name
                    if vat:
                        partner.vat = checkvat
                    partner.dj_username = username
                    partner.dj_email = email
                    if title:
                        res_partner_title = conn.ResPartnerTitle.get(int(title))
                        partner.title = res_partner_title
                        if res_partner_title.default_pricelist_id:
                            partner.property_product_pricelist = res_partner_title.default_pricelist_id
                    partner_id = partner.save()

                    # Create contact invoice address partner
                    address = conn.ResPartnerAddress.new()
                    address.name = name
                    address.partner_id = conn.ResPartner.get(partner_id)
                    address.street = street
                    address.zip = zip
                    address.city = city
                    address.phone = phone
                    #address.mobile = mobile
                    address.country_id = conn.ResCountry.get(country)
                    address.email = email
                    if not same_address:
                        address.type = 'invoice'
                    else:
                        address.type = 'default'
                    address_id = address.save()

                    if not same_address:
                        # Create contact delivery address partner
                        address = conn.ResPartnerAddress.new()
                        address.name = name
                        address.partner_id = conn.ResPartner.get(partner_id)
                        address.street = delivery_street
                        address.zip = delivery_zip
                        address.city = delivery_city
                        address.phone = delivery_phone
                        #address.mobile = delivery_mobile
                        address.country_id = conn.ResCountry.get(country)
                        address.email = email
                        address.type = 'delivery'
                        address_id = address.save()

                    # create user
                    # split name: first_name + last name
                    if len(name.split(' ')) > 1:
                        name = name.split(' ')
                        first_name = name[0]
                        del name[0]
                        last_name = ' '.join(name)
                    else:
                        first_name = name
                        last_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':get_live_url(request)}
                        emailobj = EmailMessage(subject, body, to=[email])
                        emailobj.send()
                    finally:
                        # authentification / login user
                        user = authenticate(username=username, password=password)
                        auth_login(request, user)
                        if 'redirect' in request.POST:
                            redirect = base64.b64decode(request.POST['redirect'])
                            return HttpResponseRedirect(redirect)

                        return HttpResponseRedirect("%s/partner/profile/" % context_instance['LOCALE_URI'])
            else:
                for field in form:
                    for error in field.errors:
                        message.append(error)
        else:
            msg = _("Sorry. Passwords do not match. Try again.")
            message.append(msg)

    form = UserCreationForm()
    if RECAPTCHA_PUB_KEY != '':
        html_captcha = captcha.displayhtml(RECAPTCHA_PUB_KEY)
    if request.POST.get('redirect'):
        redirect = request.POST.get('redirect')
    if request.GET.get('next'):
        if request.GET.get('qty'):
            redirect = base64.b64encode(request.GET.get('next') + '&qty=' + request.GET.get('qty'))
        else:
            redirect = base64.b64encode(request.GET.get('next'))

    countries = ResCountry.objects.all()
    titles = ResPartnerTitle.objects.all()
    
    return render_to_response("partner/register.html", locals(), context_instance=RequestContext(request))
Пример #33
0
def remember(request):
    """Remember password"""

    message = []
    site_configuration = siteConfiguration(SITE_ID)

    title = _(u'Remember')
    metadescription = _(u'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']

        if RECAPTCHA_PUB_KEY != '':
            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)
        if RECAPTCHA_PUB_KEY == '' or len(message) == 0:
            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': get_live_url(request)
                    }
                    email = EmailMessage(subject, body, to=[user.email])
                    try:
                        email.send()
                    except Exception, e:
                        logging.error(
                            "Error sending new password to user email.\nException: %s"
                            % str(e))
                        msg = _(
                            "Error sending new password. Try again, or contact with the Administrator."
                        )
                    else:
                        msg = _('A new password are sent to %(email)s') % {
                            'email': user.email
                        }
                    email = ''
                    message.append(msg)
                else:
                    msg = _('Sorry. This email not exist. Try again.')
                    message.append(msg)
            else:
                msg = _('Sorry. The email is not valid. Try again.')
                message.append(msg)
Пример #34
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 = _(u'Contact %(name)s') % {'name': contact_detail.name}
    metakeywords = contact_detail.name
    metadescription = _(u'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))
Пример #35
0
def index(request):
    """All root category products (Featured Products)"""

    site_configuration = siteConfiguration(SITE_ID)
    title = site_configuration.site_title
    metadescription = site_configuration.site_metadescription
    metakeywords = site_configuration.site_metakeywords

    values = []

    categories = ProductCategory.objects.filter(parent=None)
    root_category = categories[0]

    if len(categories) > 0:
        products = ProductTemplate.objects.filter(
            Q(product_product_set__active=True), Q(categ=root_category),
            Q(visibility='all') | Q(visibility='catalog')).distinct()

        # get price and base_image product
        for tplproduct in products:
            prods = ProductProduct.objects.filter(product_tmpl=tplproduct.id)

            i = 0
            prod_images = []
            while i < len(prods) and len(prod_images) == 0:
                prod_images = ProductImages.objects.filter(product=prods[i].id,
                                                           base_image=True)
                i += 1

            base_image = False
            if len(prod_images) > 0:
                base_image = prod_images[0]

            values.append({
                'product': tplproduct,
                'name': tplproduct.name.lower(),
                'product_variant': len(prods),
                'prods': prods,
                'base_image': base_image
            })

        # == template values ==
        category_values = {
            'title':
            title,
            'metadescription':
            metadescription,
            'metakeywords':
            metakeywords,
            'values':
            values,
            'products':
            products,
            'currency':
            DEFAULT_CURRENCY,
            'currency_position':
            CURRENCY_LABEL_POSITION,
            'compare_on':
            COMPARE_ON,
            'category_decription':
            root_category.description
            if root_category.description != 'False' else None,
            'update_price':
            UPDATE_PRICE,
        }
        return render_to_response("index.html",
                                  category_values,
                                  context_instance=RequestContext(request))
    else:
        raise Http404(
            _('This category is not available because you navigate with bookmarks or search engine. Use navigation menu'
              ))
Пример #36
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)
    vat = format_vat(partner.vat)
    partnet_title = False
    if partner.title:
        partnet_title = partner.title.name

    if request.method == 'POST':
        data = get_contact_data(request.POST.copy())
        for contact_id in data.keys():
            if contact_id == 'newaddress':
                address = conn.ResPartnerAddress.new()
                address.partner_id = partner
            else:
                address = conn.ResPartnerAddress.get(contact_id)
            address.street = data[contact_id]['street']
            address.zip = data[contact_id]['zip']
            address.city = data[contact_id]['city']
            address.phone = data[contact_id]['phone']
            address.type = data[contact_id]['type']
            address_id = address.save()
        message = [_('Successfully saved profile.')]

    addresses = conn.ResPartnerAddress.filter(
        partner_id=partner_id,
        type__in=['delivery', 'invoice', 'default', False],
        order='id')
    del_have = False
    inv_have = False
    i = 0
    while i < len(addresses) and (not del_have or not inv_have):
        if (not del_have
                or not inv_have) and addresses[i].type in ['default', False]:
            del_have = True
            inv_have = True
        if not del_have and addresses[i].type == 'delivery':
            del_have = True
        if not inv_have and addresses[i].type == 'invoice':
            inv_have = True
        i += 1

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

    return render_to_response("partner/partner.html",
                              locals(),
                              context_instance=RequestContext(request))
Пример #37
0
 def items(self):
     site_configuration = siteConfiguration(SITE_ID)
     return ProductTemplate.objects.order_by(
         '-created_on')[:site_configuration.rss_max]
Пример #38
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' or request.GET.get('code'):
        if request.POST.get('code'):
            code = request.POST['code']
            qty = int(request.POST['qty'])
        else:
            code = request.GET['code']
            qty = int(request.GET['qty'])
        #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
                ]
                try:
                    product_id_change = conn_webservice(
                        'sale.order.line', 'product_id_change', values)
                except Exception, e:
                    logging.error(
                        "Error creating/modifying the order.\nValues: %s\nException: %s"
                        % (str(values), str(e)))
                    values = {
                        'title':
                        _('Checkout Error'),
                        'error':
                        _("Error creating/modifying the order. Try again, or contact with us."
                          ),
                    }
                    return render_to_response(
                        "sale/checkout.html",
                        values,
                        context_instance=RequestContext(request))

                sale_order_add_product = True
                not_enought_stock = None
                if product_id_change['warning'] and SALE_ORDER_PRODUCT_CHECK:
                    if SALE_ORDER_PRODUCE_PRODUCT_CHECK or product.supply_method != 'produce':
                        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_value['name']
                    if 'notes' in product_value:
                        order_line.notes = product_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_value['delay']
                    order_line.th_weight = product_value['th_weight']
                    order_line.type = product_value['type']
                    order_line.price_unit = product_value['price_unit']
                    if 'discount' in product_value:
                        order_line.discount = product_value['discount']
                    order_line.purchase_price = product_value['purchase_price']
                    order_line.tax_id = [
                        conn.AccountTax.get(t_id)
                        for t_id in product_value['tax_id']
                    ]
                    order_line.product_packaging = ''
                    order_line.save()
                else:
                    message = product_id_change['warning']

                if message and 'title' in message:
                    if not_enought_stock != None:
                        message = not_enought_stock
                    else:
                        message = message['title']

            #recalcule order (refresh amount)
            order = check_order(conn, partner_id, OERP_SALE)
Пример #39
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 = _(u"%(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 = _(u'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))
Пример #40
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 = _(u'Compare Products')
    metadescription = _(u'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))