Exemplo n.º 1
0
def checkout_remove(request, code):
    """
    Checkout. Order cart
    """

    context_instance = RequestContext(request)

    products = ProductProduct.objects.filter(code=code)
    if len(products) > 0:
        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)
        order_lines = conn.SaleOrderLine.filter(order.id,
                                                product_id=products[0].id)
        if len(order_lines) > 0:
            order_line = conn.SaleOrderLine.get(order_lines[0].id)
            order_line.delete()

    return HttpResponseRedirect("%s/sale/checkout/" %
                                (context_instance['LOCALE_URI']))
Exemplo n.º 2
0
def checkout_payment(request):
    """
    Redirect Payment App from Sale Order (My Account)
    """

    context_instance = RequestContext(request)
    payment = request.POST.get('payment', '')
    order = request.POST.get('order', '')

    conn = connOOOP()
    payment_type = conn.ZoookSaleShopPaymentType.filter(app_payment=payment)

    order = conn.SaleOrder.filter(name=order,
                                  state='draft',
                                  payment_state='draft')

    if (len(payment_type) > 0) and (len(order) > 0):
        request.session['sale_order'] = order[0].name
        return HttpResponseRedirect(
            "%s/payment/%s/" %
            (context_instance['LOCALE_URI'], payment_type[0].app_payment))
    else:
        error = _('This payment is not available. Use navigation menus')
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))
Exemplo n.º 3
0
def partner(request):
    """Partner page"""

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

    site_configuration = siteConfiguration(SITE_ID)

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

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

    return render_to_response("partner/partner.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 4
0
def SaleOrderEmail(order):
    """
    Send email Order
    order Int (ID)
    Return True/False
    """

    conn = connOOOP()
    shop = conn.SaleShop.get(OERP_SALE)

    context = {}
    context['active_id'] = shop.email_sale_order.id
    values = [
        [], #ids
        order, #rel_model_ref
        context, #context
    ]
    body_template = conn_webservice('poweremail.preview','on_change_ref', values)

    customer_email = body_template['value']['to']
    
    if customer_email != 'False':
        subject = body_template['value']['subject']
        body = body_template['value']['body_text']
        email = EmailMessage(subject, body, EMAIL_FROM, to=[customer_email], headers = {'Reply-To': EMAIL_REPPLY})

        try:
            email.send()
            return True
        except:
            error = _("Your order is in process but we don't send email. Check in your order customer section.")
            return False
Exemplo n.º 5
0
def payment(request, order):
    """
    Payment. Payment Order
    """

    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))

    values = conn.SaleOrder.filter(partner_id=partner_id,
                                   name=order,
                                   shop_id__in=OERP_SALES)
    if len(values) == 0:
        error = _(
            'It is not allowed to view this section or not found. Use navigation menu.'
        )
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    value = values[0]

    if value.state != 'draft' or value.payment_state != 'draft':
        error = _('Your order is in progress or this order was payed')
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    sale_shop = conn.SaleShop.filter(id=OERP_SALE)[0]
    payments = sale_shop.zoook_payment_types

    title = _('Payment Order %s') % (value.name)
    metadescription = _('Payment Order %s') % (value.name)
    currency = value.pricelist_id.currency_id.symbol

    return render_to_response("sale/payment.html", {
        'title': title,
        'metadescription': metadescription,
        'value': value,
        'payments': payments,
        'currency': currency,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 6
0
def order(request, order):
    """
    Order. Order Detail Partner
    """

    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))

    values = conn.SaleOrder.filter(partner_id=partner_id,
                                   name=order,
                                   shop_id__in=OERP_SALES)
    if len(values) == 0:
        error = _(
            'It is not allowed to view this section or not found. Use navigation menu.'
        )
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    value = values[0]
    title = _('Order %s') % (value.name)
    metadescription = _('Details order %s') % (value.name)
    currency = value.pricelist_id.currency_id.symbol

    return render_to_response("sale/order.html", {
        'title': title,
        'metadescription': metadescription,
        'value': value,
        'currency': currency,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 7
0
def orders(request):
    """
    Orders. All Orders Partner Available
    """

    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))

    values = {}
    total = len(
        conn.SaleOrder.filter(partner_id=partner_id, shop_id__in=OERP_SALES))
    offset, page_previous, page_next = paginationOOOP(request, total,
                                                      PAGINATOR_ORDER_TOTAL)

    values = conn.SaleOrder.filter(partner_id=partner_id,
                                   shop_id__in=OERP_SALES,
                                   offset=offset,
                                   limit=PAGINATOR_ORDER_TOTAL,
                                   order='date_order DESC, name DESC')

    title = _('All Orders')
    metadescription = _('List all orders of %s') % full_name

    return render_to_response("sale/orders.html", {
        'title': title,
        'metadescription': metadescription,
        'values': values,
        'page_previous': page_previous,
        'page_next': page_next,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 8
0
def invoice(request, invoice):
    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))

    values = conn.AccountInvoice.filter(partner_id=partner_id, number=invoice, state__ne='draft', type='out_invoice', company_id=OERP_COMPANY)
    if len(values) == 0:
        error = _('It is not allowed to view this section or not found. Use navigation menu.')
        return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))

    value = values[0]
    title = _('Invoice %s') % (value.number)
    metadescription = _('Details invoice %s') % (value.number)

    return render_to_response("account/invoice.html", {'title': title, 'metadescription': metadescription, 'value': value}, context_instance=RequestContext(request))
Exemplo n.º 9
0
def invoices(request):
    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))
    
    values = {}
    total = len(conn.AccountInvoice.filter(partner_id=partner_id, state__ne='draft', type='out_invoice', company_id=OERP_COMPANY))
    offset, page_previous, page_next = paginationOOOP(request, total, PAGINATOR_INVOICE_TOTAL)

    values = conn.AccountInvoice.filter(partner_id=partner_id, state__ne='draft', type='out_invoice', company_id=OERP_COMPANY, offset=offset, limit=PAGINATOR_INVOICE_TOTAL, order='name DESC')

    title = _('All Invoices')
    metadescription = _('List all invoices of %s') % full_name

    return render_to_response("account/invoices.html", {'title':title, 'metadescription':metadescription, 'values':values, 'page_previous':page_previous, 'page_next':page_next}, context_instance=RequestContext(request))
Exemplo n.º 10
0
def partner(request):
    """Partner page"""

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

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

    title = _('User Profile')
    metadescription = _('User profile of %(site)s') % {'site':site_configuration.site_title}
    
    return render_to_response("partner/partner.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 11
0
def whistlist(request):
    """
    Whistlist
    Favourites products customer
    """

    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 contact us')
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    prod_whistlist = False
    partner = conn.ResPartner.get(partner_id)
    product_obj = partner.product_whistlist_ids

    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:
                for prod in product_obj:
                    if prod.id == tplproduct[
                            0].id:  #exist this product whistlist
                        prod_whistlist = conn_webservice(
                            'res.partner', 'write', [[partner_id], {
                                'product_whistlist_ids': [(3, tplproduct[0].id)
                                                          ]
                            }])
            except:
                prod_whistlist = True

    if 'add' in path:
        kwargs = {
            'slug_' + get_language(): path[-1],  #slug is unique
        }
        tplproduct = ProductTemplate.objects.filter(**kwargs)
        if tplproduct.count() > 0:
            check_add = False
            if product_obj:
                for prod in product_obj:
                    if prod.id == tplproduct[
                            0].id:  #exist this product whistlist
                        check_add = True
            if not check_add:
                prod_whistlist = conn_webservice(
                    'res.partner', 'write', [[partner_id], {
                        'product_whistlist_ids': [(4, tplproduct[0].id)]
                    }])

    title = _('Whislist')
    metadescription = _('Whislist of %s') % full_name

    if prod_whistlist:
        partner = conn.ResPartner.get(
            partner_id)  #refresh product_whistlist_ids if add or remove
        product_obj = partner.product_whistlist_ids

    products = []
    if product_obj:
        for prod in product_obj:
            prods = ProductProduct.objects.filter(
                product_tmpl=prod.id).order_by('price')
            tplproduct = ProductTemplate.objects.get(id=prod.id)
            prod_images = ProductImages.objects.filter(product=prod.id,
                                                       exclude=False)
            base_image = False
            if prod_images.count() > 0:
                base_image = prod_images[0]

            products.append({
                'product': tplproduct,
                'name': tplproduct.name,
                'price': prods[0].price,
                'base_image': base_image
            })

    return render_to_response("catalog/whistlist.html", {
        'title': title,
        'metadescription': metadescription,
        'products': products,
        'currency': DEFAULT_CURRENCY,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 12
0
def payorder(request):
    """
    Payment Order without login
    Only Pay Order when:
      - State Draft 
      - Payment State Draft
      - Shop ID
    """

    name = request.GET.get('name', '')
    total = request.GET.get('total', '')

    title = _('Payment Order by reference')
    metadescription = _('Payment Order by reference')

    message = False
    value = False
    payments = False
    currency = DEFAULT_CURRENCY

    if request.method == 'POST':
        form = PayorderForm(request.POST)
        if form.is_valid():
            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))

            name = form.cleaned_data['name']
            total = float(form.cleaned_data['total'])

            values = conn.SaleOrder.filter(name=name,
                                           amount_total=total,
                                           state='draft',
                                           payment_state='draft',
                                           shop_id__in=OERP_SALES)

            if len(values) > 0:
                value = values[0]
                title = _('Order %s') % (value.name)
                metadescription = _('Details order %s') % (value.name)
                sale_shop = conn.SaleShop.filter(id=OERP_SALE)[0]
                payments = sale_shop.zoook_payment_types
                currency = value.pricelist_id.currency_id.symbol
            else:
                message = _(
                    'Try again. There are not some reference pending to pay or total do not match.'
                )
        else:
            message = _('Try again. Insert reference and total Order.')

    return render_to_response("sale/payorder.html", {
        'title': title,
        'metadescription': metadescription,
        'name': name,
        'total': total,
        'message': message,
        'value': value,
        'payments': payments,
        'currency': currency,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 13
0
def checkout_confirm(request):
    """
    Checkout. Confirm
    """

    logging.basicConfig(filename=LOGSALE, level=logging.INFO)
    context_instance = RequestContext(request)

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

    if request.method == 'POST':
        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))

        partner = conn.ResPartner.get(partner_id)
        order = check_order(conn, partner_id, OERP_SALE)

        if order.state != 'draft':
            return HttpResponseRedirect("%s/sale/" %
                                        (context_instance['LOCALE_URI']))

        delivery = request.POST.get('delivery') and request.POST.get(
            'delivery') or False
        payment = request.POST['payment'] and request.POST['payment'] or False
        address_invoice = request.POST['address_invoice'] and request.POST[
            'address_invoice'] or False
        address_delivery = request.POST['address_delivery'] and request.POST[
            'address_delivery'] or False

        #delivery
        if delivery:
            delivery = delivery.split('|')
            carrier = conn.DeliveryCarrier.filter(code=delivery[0])
            if len(carrier) == 0:
                return HttpResponseRedirect("%s/sale/checkout/" %
                                            (context_instance['LOCALE_URI']))
            carrier = carrier[0]

            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
                carrier.product_id.id,  #product
                1,  #qty
                False,  #uom
                0,  #qty_uos
                False,  #uos
                '',  #name
                partner.id,  #partner_id
            ]

            product_id_change = conn_webservice('sale.order.line',
                                                'product_id_change', values)
            order_line = conn.SaleOrderLine.new()
            order_line.order_id = order
            order_line.name = carrier.product_id.name
            order_line.product_id = carrier.product_id
            order_line.product_uom_qty = 1
            order_line.product_uom = carrier.product_id.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 = float(re.sub(',', '.', delivery[1]))
            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()

            #delivery
            order.carrier_id = carrier

        #payment type
        payment_type = conn.ZoookSaleShopPaymentType.filter(
            app_payment=payment)
        if len(payment_type) > 0:
            if payment_type[0].commission:  #add new order line
                payment = conn_webservice('zoook.sale.shop.payment.type',
                                          'set_payment_commission',
                                          [order.id, payment])
            order.payment_type = payment_type[0].payment_type_id
            order.picking_policy = payment_type[0].picking_policy
            order.order_policy = payment_type[0].order_policy
            order.invoice_quantity = payment_type[0].invoice_quantity
        else:
            return HttpResponseRedirect("%s/sale/checkout/" %
                                        (context_instance['LOCALE_URI']))

        #Replace invoice address and delivery address
        if address_invoice:
            #add new invoice address
            if address_invoice == 'add_invoice':
                address = conn.ResPartnerAddress.new()
                address.name = request.POST['invoice_name']
                address.partner_id = conn.ResPartner.get(partner_id)
                address.type = 'invoice'
                address.street = request.POST['invoice_street']
                address.zip = request.POST['invoice_zip']
                address.city = request.POST['invoice_city']
                countries = ResCountry.objects.filter(
                    code=request.POST['invoice_country_code'])
                if len(countries) > 0:
                    country = countries[0].id
                    address.country_id = conn.ResCountry.get(country)
                if request.user.email:
                    address.email = request.user.email
                address.phone = request.POST['invoice_phone']
                address_invoice = address.save()

            address_invoice = conn.ResPartnerAddress.get(int(address_invoice))
            if address_invoice:
                order.partner_invoice_id = address_invoice
        else:
            return HttpResponseRedirect("%s/sale/checkout/" %
                                        (context_instance['LOCALE_URI']))

        if address_delivery:
            #add new delivery address
            if address_delivery == 'add_delivery':
                address = conn.ResPartnerAddress.new()
                address.name = request.POST['delivery_name']
                address.partner_id = conn.ResPartner.get(partner_id)
                address.type = 'delivery'
                address.street = request.POST['delivery_street']
                address.zip = request.POST['delivery_zip']
                address.city = request.POST['delivery_city']
                countries = ResCountry.objects.filter(
                    code=request.POST['delivery_country_code'])
                if len(countries) > 0:
                    country = countries[0].id
                    address.country_id = conn.ResCountry.get(country)
                if request.user.email:
                    address.email = request.user.email
                address.phone = request.POST['delivery_phone']
                address_delivery = address.save()

            address_delivery = conn.ResPartnerAddress.get(
                int(address_delivery))
            if address_delivery:
                order.partner_shipping_id = address_delivery
        else:
            return HttpResponseRedirect("%s/sale/checkout/" %
                                        (context_instance['LOCALE_URI']))

        #cupon code / promotion
        code_promotion = request.POST['promotion']
        if code_promotion:
            order.coupon_code = code_promotion

        #payment state
        order.payment_state = 'checking'
        order.save()

        #apply cupon code / promotion
        if code_promotion:
            promotion = conn_webservice('promos.rules', 'apply_promotions',
                                        [order.id])
            logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'),
                                      'Apply promotion %s Order %s' %
                                      (code_promotion, order.name)))

        logging.info(
            '[%s] %s' %
            (time.strftime('%Y-%m-%d %H:%M:%S'), 'Payment %s Order %s' %
             (payment_type[0].app_payment, order.name)))

        request.session['sale_order'] = order.name

        return HttpResponseRedirect(
            "%s/payment/%s/" %
            (context_instance['LOCALE_URI'], payment_type[0].app_payment))
    else:
        return HttpResponseRedirect("%s/sale/checkout/" %
                                    (context_instance['LOCALE_URI']))
Exemplo n.º 14
0
def register(request):
    """Registration page. If exists session, redirect profile"""

    context_instance=RequestContext(request)

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

    site_configuration = siteConfiguration(SITE_ID)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    countries = ResCountry.objects.all()
    country_default = COUNTRY_DEFAULT
    
    return render_to_response("partner/register.html", locals(), context_instance=RequestContext(request))
Exemplo n.º 15
0
def checkout(request):
    """
    Checkout. Order Cart
    """

    context_instance = RequestContext(request)

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

    site_configuration = siteConfiguration(SITE_ID)

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

    order = check_order(conn, partner_id, OERP_SALE)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return render_to_response("sale/checkout.html",
                              values,
                              context_instance=RequestContext(request))
Exemplo n.º 16
0
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from settings import *
from django.utils.translation import ugettext as _
from django.template import defaultfilters
from catalog.models import ResManufacturer
from tools.zoook import connOOOP

logging.basicConfig(filename=LOGFILE,level=logging.INFO)
logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Manufacturers. Running')))

"""
manufacturers
"""
conn = connOOOP()
if not conn:
    logging.info('[%s] %s' % ('Error connecting to ERP'))

for result in conn.ResPartner.filter(manufacturer=True):
    values = {
        'id': result.id,
        'name': result.name,
        'slug': defaultfilters.slugify(result.name),
    }

    manufacturer = ResManufacturer(**values)
    try:
        manufacturer.save()            
        logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Manufacturers save ID %s') % result.id))
    except:
Exemplo n.º 17
0
def cancel(request, order):
    """
    Order. Cancel Order
    """

    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))

    values = conn.SaleOrder.filter(partner_id=partner_id,
                                   name=order,
                                   shop_id__in=OERP_SALES)
    if len(values) == 0:
        error = _(
            'It is not allowed to view this section or not found. Use navigation menu.'
        )
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    value = values[0]

    if value.state != 'draft':
        error = _(
            'Your order is in progress and it is not possible to cancel. Contact with us'
        )
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    #cancel order
    try:
        cancel = conn_webservice('sale.order', 'action_cancel', [[value.id]])
    except:
        error = _(
            'An error is getting when cancel this order. Try again or contact us'
        )
        return render_to_response("partner/error.html",
                                  locals(),
                                  context_instance=RequestContext(request))

    #drop session if exists
    if 'sale_order' in request.session:
        if request.session['sale_order'] == value.name:
            del request.session['sale_order']

    value = conn.SaleOrder.get(value.id)  #reload sale order values
    title = _('Order %s cancelled') % (value.name)
    metadescription = _('Order %s cancelled') % (value.name)

    return render_to_response("sale/order.html", {
        'title': title,
        'metadescription': metadescription,
        'value': value,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 18
0
def register(request):
    """Registration page. If exists session, redirect profile"""

    context_instance = RequestContext(request)

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

    site_configuration = siteConfiguration(SITE_ID)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return render_to_response("partner/register.html",
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 19
0
def whistlist(request):
    """
    Whistlist
    Favourites products customer
    """

    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 contact us')
        return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request))

    prod_whistlist = False
    partner = conn.ResPartner.get(partner_id)
    product_obj = partner.product_whistlist_ids

    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:
                for prod in product_obj:
                    if prod.id == tplproduct[0].id: #exist this product whistlist
                        prod_whistlist = conn_webservice('res.partner','write', [[partner_id], {'product_whistlist_ids':[(3, tplproduct[0].id)]}])
            except:
                prod_whistlist = True
                
    if 'add' in path:
        kwargs = {
            'slug_'+get_language(): path[-1], #slug is unique
        }
        tplproduct = ProductTemplate.objects.filter(**kwargs)
        if tplproduct.count() > 0:
            check_add = False
            if product_obj:
                for prod in product_obj:
                    if prod.id == tplproduct[0].id: #exist this product whistlist
                        check_add = True
            if not check_add:
                prod_whistlist = conn_webservice('res.partner','write', [[partner_id], {'product_whistlist_ids':[(4, tplproduct[0].id)]}])

    title = _('Whislist')
    metadescription = _('Whislist of %s') % full_name
    
    if prod_whistlist:
        partner = conn.ResPartner.get(partner_id) #refresh product_whistlist_ids if add or remove
        product_obj = partner.product_whistlist_ids
    
    products = []
    if product_obj:
        for prod in product_obj:
            prods = ProductProduct.objects.filter(product_tmpl=prod.id).order_by('price')
            tplproduct = ProductTemplate.objects.get(id=prod.id)
            prod_images = ProductImages.objects.filter(product=prod.id,exclude=False)
            base_image = False
            if prod_images.count() > 0:
                base_image = prod_images[0]

            products.append({'product': tplproduct, 'name': tplproduct.name, 'price': prods[0].price, 'base_image': base_image})

    return render_to_response("catalog/whistlist.html", {
                    'title': title, 'metadescription': metadescription, 
                    'products': products,
                    'currency': DEFAULT_CURRENCY,
                }, context_instance=RequestContext(request))