def _save(self, result, user=None): addresses = [] emails = [] phones = [] if user: for address in result["address"]: if address["id"]: add = Session.query(Address).filter_by(id=address["id"]).one() add.city = address["city"] add.add1 = address["add1"] add.add2 = address["add2"] add.state = address["state"] add.po_code = address["po_code"] addresses.append(add) else: addresses.append( Address( address["city"], address["add1"], address["add2"], address["state"], address["po_code"], user, None, ) ) else: for address in result["address"]: addresses.append( Address( address["city"], address["add1"], address["add2"], address["state"], address["po_code"], None, None, ) ) if result.has_key("email"): if user: for email in result["email"]: if email["id"]: em = Session.query(Email).filter_by(email_address=email["id"]).one() em.email_address = email["email_address"] emails.append(em) else: emails.append(Email(email["email_address"], user)) else: for email in result["email"]: emails.append(Email(email["email_address"], None)) for phone in result["phone"]: if user: if phone["id"]: ph = Session.query(Phone).filter_by(phone_number=str(phone["id"])).one() ph.p_type = phone["p_type"] ph.phone_number = str(phone["phone_number"]) phones.append(ph) else: phones.append(Phone(phone["p_type"], str(phone["phone_number"]), user)) else: phones.append(Phone(phone["p_type"], str(phone["phone_number"]), None)) photo = None if result["photo"]: picfile = result["photo"] permanent_file = open( os.path.join(config["pylons.paths"]["static_files"], "pics", picfile.filename.replace(os.sep, "_")), "wb", ) shutil.copyfileobj(picfile.file, permanent_file) picfile.file.close() photo = Photo(permanent_file.name.split("/")[-1]) if user: # do something to compare this two lists of Objects instead of asigning the whole list every time if user.first_name != result["first_name"]: user.first_name = result["first_name"] if user.last_name != result["last_name"]: user.last_name = result["last_name"] if user.birth_date != result["birth_date"]: user.birth_date = result["birth_date"] if user.SSN != result["SSN"]: user.SSN = result["SSN"] if "password" in result and result["password"] != "": user._set_password(result["password"]) if addresses != []: try: user.addresses = addresses Session.add_all(addresses) Session.commit() except: Session.rollback() return False if emails != []: try: user.emails = emails Session.add_all(emails) Session.commit() except: Session.rollback() return False if phones != []: try: user.phones = phones Session.add_all(phones) Session.commit() except: Session.rollback() return False if photo: try: user.photo = photo except: Session.rollback() return False if result.has_key("role") and result.has_key("tag"): # for i,group in enumerate(result['role']): # for group2 in user.groups: # if group2.group == group.group: # result['role'].pop(i) if result["role"] != []: user.groups = result["role"] # for i,tag in enumerate(result['tag']): # for tag2 in user.tags: # if tag.tag == tag2.tag: # result['tag'].pop(i) if result["tag"] != []: user.tags = result["tag"] if result["balance"] != user.balance: user.balance = result["balance"] if user.cradit != result["cradit"]: user.cradit = result["cradit"] if user.deleted != result["deleted"]: user.deleted = result["deleted"] else: user = User( result["first_name"], result["last_name"], result["user_name"], result["password"], result["role"], result["SSN"], result["birth_date"], result["balance"], photo, False, addresses, [], [], emails, phones, result["tag"], result["cradit"], False, ) Session.add(user) try: Session.commit() except: Session.rollback() return False return True
def createcustomer(self): readsettings() values = dict(request.params) # create the pending user captchres = h.captcha.submit( values["recaptcha_challenge_field"], values["recaptcha_response_field"], "6LepGccSAAAAAMfzDtmvyRjJ7-A1FWuJa5qUTxX2", session["site_settings"]["ip_address"], ) if not captchres.is_valid: c.menu_items = h.top_menu(self.menu_items, _("Customers")) c.came_from = values["came_from"] if request.GET.get("came_from", None): h.flash(_("After filling the from you will be sent back to your shopping cart")) html = render("/derived/user/new.html") return htmlfill.render(html, values, errors={"captcha": _("Invalid Captcha try again")}) email = Email(email_address=self.form_result["email"], user=None) phone = Phone(None, str(self.form_result["phone"]), None) newcustormer = User( first_name=self.form_result["first_name"], last_name=self.form_result["last_name"], user_name=self.form_result["email"], password=self.form_result["password"], user_groups=[Session.query(Group).filter_by(group="customer").one()], SSN=None, birth_date=None, balance=0, photo=None, addresses=[], customer_invoices=[], staff_invoices=[], emails=[email], phones=[phone], deleted=False, pending=True, ) # create the confirm link Session.add(newcustormer) # confurlcode = randint(10e40,10e49) confurlcode = str(uuid.uuid1()) confurlcode = "cu-" + confurlcode conf = UserConfirm(newcustormer, confurlcode) Session.add(conf) newcustormer.confirmcode = [conf] Session.add(newcustormer) message = Message( session["site_settings"]["userconf"], self.form_result["email"], _("User registration"), encoding="utf-8" ) plain = ( "someone (hopefully you) registered an account with" + str(request.application_url) + "<br/>" + "for confirming your registration click the below link" + "<br/>" + unicode(request.application_url + url(controller="user", action="confirmuser", confirmcode=confurlcode)) + "<br/>" + "After confirmation you can login with your Email address and password." ) c.confurlcode = confurlcode registerHtml = render(_("/derived/emails/register.html")) message.plain = plain message.rich = registerHtml try: message.send() except: Session.delete(conf) Session.delete(phone) Session.delete(email) Session.delete(newcustormer) Session.rollback() h.flash(_("smtp error try again")) redirect(values["came_from"]) Session.commit() h.flash( _( "Check your email and click the activation link after logging in you can continue with the purchuse in Shop online page" ) ) redirect(values["came_from"])
def savebasket(self): wholesale = False if "repoze.who.identity" in request.environ: user = request.environ.get('repoze.who.identity')['user'] wholesale_tag = Session.query(UserTag).filter_by(tag='wholesale').one() if wholesale_tag in user.tags: wholesale = True c.wholesale=True values = dict(request.params) action = request.params.getone('action') del values['action'] if action == _('Remove all items from basket'): session['basket'] = {} h.flash(_('All items removed from basket')) session.save() redirect(url(controller='product', action='list')) if action.startswith(_('Remove item')): gid = int(action.split(' ')[-1]) for item in values: if item.startswith('quantityid-%s'%gid): id = int(values[item]) del session['basket'][id] session.save() newvalues = remove_item(values,action,'quantity') newvalues = remove_item(newvalues,action,'quantityid') return render_editbasket(self.menu_items,values=newvalues) if action == _('Buy'): identity = request.environ.get('repoze.who.identity') if identity is None: redirect( url(controller='account', action='login', came_from=url(controller='product', action='editbasket') ) ) schema = Editbasket() try: result = schema.to_python(dict(request.params), c) except Invalid, e: return render_editbasket(self.menu_items,values=values, errors=variabledecode.variable_encode( e.unpack_errors() or {}, add_repetitions=False) ) else: for i in range(len(result['quantityid'])): session['basket'][result['quantityid'][i]] = result['quantity'][i] session.save() # create pending invoices. email to customer and email to sales user = Session.query(User).filter_by(id=session['user']).one() items=[] dt = datetime.now() productsmsg= "" total = 0 invoice = Invoice(dt,user,None,None,0,[],True) for id in session['basket']: product = Session.query(Product).filter_by(id=id).one() quantity = session['basket'][id] if wholesale: price = product.wholesale_price else: price = product.sell_price totprice = quantity * price productsmsg +='<p>'+_('Code')+' :'+str(product.code)+'<br/>'+_('Name')+' :' + product.name+'<br/>'+_('Unit price')+' :'+str(price)+'<br/>'+_('Quantity')+' :'+str(quantity)+'<br/>'+_('Total price')+' :'+str(totprice)+'<br/>'+'</p>'+'<hr>' total += totprice item = Invoice_item(product, invoice, quantity, totprice, unitprice=price ) items.append(item) invoice.invoice_items = items invoice.total_price = total Session.add(invoice) #Session.commit() customer_message = Message(session['site_settings']['invoicealertfrom'], #user.emails[0].email_address, "*****@*****.**", _("your order details from Kazhal"), encoding='utf-8') plain = _("You placed an order of the following items with Kazhal")+' :'+ productsmsg + "<br/>"+ _("Total price")+' :'+str(total) +"<br/>"+_("our staff will contact you to confirm the purchase.<br/>Thank you.<br/>Kazhal") c.usermsg = _("You placed an order of the following items with Kazhal")+_("our staff will contact you to confirm the purchase.<br/>Thank you.<br/>Kazhal") c.user = user c.invoice = invoice c.total = total customerHtml = render(_('/derived/emails/customer_invoice.html')) customer_message.rich = customerHtml customer_message.plain = plain splain = _("User")+u' :'+user.user_name +u'<br/>'+_("Phone")+u' :'+unicode([int(phone.phone_number) for phone in user.phones])[1:-1]+u'<br/>'+ _("Items")+u' :'+productsmsg+u'<br/>'+_("Total price")+u" :"+unicode(total)+u'<br/>' splain += unicode(h.link_to(_("Click here to confirm the order."),((request.application_url)+url(controller='invoice',action='confirm',id=invoice.id)))) c.usermsg = unicode(h.link_to(_("Click here to confirm the order."),((request.application_url)+url(controller='invoice',action='confirm',id=invoice.id)))) salesHtml = render(_('/derived/emails/customer_invoice.html')) sales_messages=[] for email in session['site_settings']['invoicealertmail'].split(','): sales_message=Message(session['site_settings']['invoicealertfrom'], email, _("User ")+user.user_name+_(" placed an order"), encoding='utf-8') sales_message.plain=splain sales_message.rich = salesHtml sales_messages.append(sales_message) try: customer_message.send() for message in sales_messages: message.send() except: Session.rollback() h.flash(_('For some technical reasons we are unable to accept orders online for now please contact us by phone.(SMTP Error)')) redirect(url(controller='product', action='editbasket')) Session.commit() session['basket']={} session.save() h.flash(_('An email has beed sent to you with the detail of your purchase our staff will call you for further details')) redirect(url(controller='product', action='list'))