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
def update_prices(request, product_ids): partner_id = request.user.get_profile().partner_id if request.user.user_profile_s.count() > 0 else False data = '' if partner_id: products = [] for product in product_ids: try: product = int(product) products.append({'product_id':int(product),'quantity':1}) except: pass # values => {"1":{"regularPrice":"50"},"2":{"regularPrice":"100"}} values = conn_webservice('product.product','zoook_compute_price', [OERP_SALE, products, partner_id]) data = json.dumps(values) return data
def update_prices(request, product_ids): partner_id = request.user.get_profile( ).partner_id if request.user.user_profile_s.count() > 0 else False data = '' if partner_id: products = [] for product in product_ids: try: product = int(product) products.append({ 'product_id': int(product), 'quantity': 1 }) except: pass # values => {"1":{"regularPrice":"50"},"2":{"regularPrice":"100"}} values = conn_webservice('product.product', 'zoook_compute_price', [OERP_SALE, products, partner_id]) data = json.dumps(values) return data
def register(request): """Registration page. If exists session, redirect profile""" if request.user.is_authenticated(): #redirect profile return HttpResponseRedirect("/partner/profile/") title = _('Create an Account') metadescription = _('Create an Account of %(site)s') % {'site':SITE_TITLE} if request.method == "POST": message = [] users = '' emails = '' 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'] country = data['country'] if data['password1'] == data['password2']: 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) 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 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 error: conn = connOOOP() if not conn: error = _('Error when you are 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 in our ERP. Contact us to create a new user') message.append(msg) #check if this vat valid if not error: vat = data['vat_code']+data['vat'] check_vat = conn_webservice('res.partner', 'dj_check_vat', [vat, OERP_SALE]) if not check_vat: msg = _('Vat not valid. Check if the vat is correct') message.append(msg) #create new partner and user if not error: # create partner partner = conn.ResPartner.new() partner.name = data['name'] partner.vat = vat 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(data['country']) address.email = data['email'] 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() # send email subject = _('New user is added - %(name)s') % {'name':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 this email") % {'site':SITE_TITLE,'username':username,'password':password,'live_url':LIVE_URL} email = EmailMessage(subject, body, to=[email]) email.send() # authentification / login user user = authenticate(username=username, password=password) auth_login(request, user) return HttpResponseRedirect("/partner/profile/") 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) vat_code = VAT_CODE countries = ResCountry.objects.all() country_default = COUNTRY_DEFAULT return render_to_response("partner/register.html", locals(), context_instance=RequestContext(request))
from config_path import djpath sys.path.append(djpath) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from settings import * from django.utils.translation import ugettext as _ from base.models import ResCountry, ResCountryState from tools.conn import conn_webservice logging.basicConfig(filename=LOGFILE,level=logging.INFO) logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Configuration. Running'))) """ countries / states """ results = conn_webservice('sale.shop', 'dj_export_countries', [[OERP_SALE]]) for result in results: # minicalls with one id (step to step) because it's possible return a big dicctionay and broken memory. values = conn_webservice('django.external.mapping', 'get_oerp_to_dj', ['zoook.res.country',[result]]) if DEBUG: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), values)) if len(values) > 0: count = values[0] country = ResCountry(**count) try: country.save() #states
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']))
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))
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))
parser.add_option("-p", "--products", dest="products", default=False, help="Get product list.") options, args = parser.parse_args() """ for product.template for product.product if product.attributes """ """Get Products to import at Django""" prods = [] if options.products: prods = options.products.split(',') results = conn_webservice('sale.shop', 'dj_export_products', [[OERP_SALE], prods]) logging.info('[%s] Total: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'),len(results))) langs = conn_webservice('sale.shop', 'zoook_sale_shop_langs', [[OERP_SALE]]) langs = langs[str(OERP_SALE)] context = {} if len(results) == 0: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Products Template. Not products template news or modified'))) for result in results: # minicalls with one id (step to step) because it's possible return a big dicctionay and broken memory. values = conn_webservice('base.external.mapping', 'get_oerp_to_external', ['zoook.product.template',[result['product_template']],context,langs]) if DEBUG: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), values))
parser.add_option("-r", "--resource", dest="resources", default=False, help="Get product list.") options, args = parser.parse_args() """Get Attachment to import at Django""" resources = [] if options.resources: resources = options.resources.split(',') conn = connOOOP() if not conn: logging.info('[%s] %s' % ('Error connecting to ERP')) results = conn_webservice('sale.shop', 'dj_export_attachments', [[OERP_SALE], resources]) logging.info('[%s] Total: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), len(results))) if len(results) == 0: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Not resources news or modified'))) for res in results: result = conn.IrAttachment.get(res) values = { 'id': result.id, 'name': result.name, 'description': result.description and result.description or '', 'res_name': result.res_name,
logging.basicConfig(filename=LOGFILE,level=logging.INFO) logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Images. Running'))) usage = "usage: %prog [options]" parser = optparse.OptionParser(usage) parser.add_option("-p", "--products", dest="products", default=False, help="Get product list.") options, args = parser.parse_args() products = [] if options.products: products = options.products.split(',') results = conn_webservice('sale.shop', 'dj_export_images', [[OERP_SALE], products]) if len(results) == 0: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Images. Not images news or modified'))) for result in results: # minicalls with one id (step to step) because it's possible return a big dicctionay and broken memory. context = {'shop':OERP_SALE} values = conn_webservice('base.external.mapping', 'get_oerp_to_external', ['zoook.product.images',[result],context]) if DEBUG: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), values)) if len(values) > 0: img = values[0] image = ProductImages(**img)
import sys import logging import time 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 base.models import ResCountry, ResCountryState from tools.conn import conn_webservice logging.basicConfig(filename=LOGFILE,level=logging.INFO) logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Configuration. Running'))) langs = conn_webservice('sale.shop', 'zoook_sale_shop_langs', [[OERP_SALE]]) langs = langs[str(OERP_SALE)] context = {} """ countries / states """ results = conn_webservice('sale.shop', 'dj_export_countries', [[OERP_SALE]]) for result in results: # minicalls with one id (step to step) because it's possible return a big dicctionay and broken memory. values = conn_webservice('base.external.mapping', 'get_oerp_to_external', ['zoook.res.country',[result],context,langs]) if DEBUG: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), values))
import time 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 catalog.models import ProductCategory from tools.conn import conn_webservice logging.basicConfig(filename=LOGFILE, level=logging.INFO) logging.info( '[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Categories. Running'))) results = conn_webservice('sale.shop', 'dj_export_categories', [[OERP_SALE]]) langs = conn_webservice('sale.shop', 'zoook_sale_shop_langs', [[OERP_SALE]]) langs = langs[str(OERP_SALE)] context = {} if len(results) == 0: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Categories. Not categories news or modified'))) cat2 = [] for result in results: # minicalls with one id (step to step) because it's possible return a big dicctionay and broken memory. values = conn_webservice( 'base.external.mapping', 'get_oerp_to_external',
parser = optparse.OptionParser(usage) parser.add_option("-r", "--resource", dest="resources", default=False, help="Get product list.") options, args = parser.parse_args() """Get Attachment to import at Django""" resources = [] if options.resources: resources = options.resources.split(',') conn = connOOOP() if not conn: logging.info('[%s] %s' % ('Error connecting to ERP')) results = conn_webservice('sale.shop', 'dj_export_attachments', [[OERP_SALE], resources]) logging.info('[%s] Total: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'),len(results))) if len(results) == 0: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Not resources news or modified'))) for res in results: result = conn.IrAttachment.get(res) values = { 'id': result.id, 'name': result.name, 'description': result.description and result.description or '', 'res_name': result.res_name, 'res_model': result.res_model, 'res_id': result.res_id,
def exam(request, offer, course, exam): """Training Exam/Questionarie page """ contact_id = checkContactID(request) if not contact_id: error = _("Are you a student? 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 you are connecting with our ERP. Try again or cantact us") return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request)) full_name = checkFullName(request) contact = conn.ResPartnerContact.get(contact_id) # TODO: check if have rules access view this source offer = conn.TrainingOffer.filter(alias=offer) if len(offer) == 0: error = _("The page requested could not be found.") return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request)) course = conn.TrainingCourse.filter(alias=course) if len(course) == 0: error = _("The page requested could not be found.") return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request)) exam = conn.TrainingExamQuestionnaire.filter(alias=exam) if len(exam) == 0: error = _("The page requested could not be found.") return render_to_response("partner/error.html", locals(), context_instance=RequestContext(request)) offer = offer[0] course = course[0] exam = exam[0] # check if contact make this exam make_exam = True for part in conn.TrainingParticipation.filter(contact_id=contact_id): if course.id == part.seance_id.course_id.id: participation = part if part.questionnaire_id: make_exam = False url = LIVE_URL title = exam.name site_title = SITE_TITLE metadescription = exam.metadescription or _("Questionaire %(name)s") % {"name": exam.name} metakeywords = exam.metakey or "" path_info = request.path_info.split("/") if "questionarie" in path_info: # questionaire page # list questions questions_questions = conn.TrainingExamQuestionnaireQuestion.filter(questionnaire_id=exam.id) questions = [] for question in questions_questions: questions.append(question.question_id) return render_to_response("training/questionarie.html", locals(), context_instance=RequestContext(request)) if "answer" in path_info: # questionaire page if request.method == "POST": values = request.POST if len(values) > 0: # add participation questionaire participation.questionnaire_id = exam participation.result_received = True participation.save() make_exam = False # reload participation participation_id = participation.id del participation i = 1 for k, v in values.iteritems(): answer_values = {} value = k.split("_") if len(value) > 1: answer_values["participation_id"] = participation_id if value[1][-2:] == "[]": answer_values["question_id"] = value[1][:-2] else: answer_values["question_id"] = value[1] if value[0] == "qcm": answer_values["response_qcm_ids"] = [v] if value[0] == "qcu": answer_values["response_qcu_ids"] = [v] if value[0] == "yesno": answer_values["response_yesno"] = v if value[0] == "plain": answer_values["response_plain"] = v answer_values["sequence"] = i i = i + 1 # create participation line questions answer_exam = conn_webservice("training.participation.line", "question_answer", [answer_values]) participation = conn.TrainingParticipation.get(participation_id) # reload participation return render_to_response("training/exam.html", locals(), context_instance=RequestContext(request))
def register(request): """Registration page. If exists session, redirect profile""" if request.user.is_authenticated(): #redirect profile return HttpResponseRedirect("/partner/profile/") title = _('Create an Account') metadescription = _('Create an Account of %(site)s') % {'site': SITE_TITLE} if request.method == "POST": message = [] users = '' emails = '' 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'] country = data['country'] if data['password1'] == data['password2']: 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) 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 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 error: conn = connOOOP() if not conn: error = _( 'Error when you are 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 in our ERP. Contact us to create a new user' ) message.append(msg) #check if this vat valid if not error: vat = data['vat_code'] + data['vat'] check_vat = conn_webservice('res.partner', 'dj_check_vat', [vat, OERP_SALE]) if not check_vat: msg = _('Vat not valid. Check if the vat is correct') message.append(msg) #create new partner and user if not error: # create partner partner = conn.ResPartner.new() partner.name = data['name'] partner.vat = vat 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( data['country']) address.email = data['email'] 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() # send email subject = _('New user is added - %(name)s') % { 'name': 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 this email" ) % { 'site': SITE_TITLE, 'username': username, 'password': password, 'live_url': LIVE_URL } email = EmailMessage(subject, body, to=[email]) email.send() # authentification / login user user = authenticate(username=username, password=password) auth_login(request, user) return HttpResponseRedirect("/partner/profile/") 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) vat_code = VAT_CODE countries = ResCountry.objects.all() country_default = COUNTRY_DEFAULT return render_to_response("partner/register.html", locals(), context_instance=RequestContext(request))
import sys import logging import time 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 catalog.models import ProductCategory from tools.conn import conn_webservice logging.basicConfig(filename=LOGFILE,level=logging.INFO) logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Categories. Running'))) results = conn_webservice('sale.shop', 'dj_export_categories', [[OERP_SALE]]) langs = conn_webservice('sale.shop', 'zoook_sale_shop_langs', [[OERP_SALE]]) langs = langs[str(OERP_SALE)] context = {} if len(results) == 0: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), _('Sync. Categories. Not categories news or modified'))) cat2 = [] for result in results: # minicalls with one id (step to step) because it's possible return a big dicctionay and broken memory. values = conn_webservice('base.external.mapping', 'get_oerp_to_external', ['zoook.product.category',[result],context,langs]) if DEBUG: logging.info('[%s] %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), values))