def setup_app(command, conf, vars): """Place any commands to setup kazhal here""" # Don't reload the app if it was loaded under the testing environment if not pylons.test.pylonsapp: load_environment(conf.global_conf, conf.local_conf) # Create the tables if they don't already exist Base.metadata.create_all(bind=Session.bind) log.info("Adding initial users, groups and permissions...") random.seed(1398) # =================================================Site settings============================= settingsf = file(conf['settings_file'],'wb') settings = {'server_tz':'UTC', 'user_tz':'Iran', 'invoicealertmail':'[email protected],[email protected]', 'invoicesms':'091213433,234542245,987987', 'contactusmail':'[email protected],[email protected]', 'contactusSMS':'02342342,454776', } pickle.dump(settings,settingsf) settingsf.close() # =================================================Creating permissions ============================= perm_names=[ u'admin', #0 u'add_product', #1 u'edit_product',#2 u'remove_product', #3 u'view_user',#4 u'add_user',#5 u'edit_user', #6 u'delete_user', #7 u'reset_user_password', #8 u'add_cradit',#9 u'edit_invoice', #10 u'add_invoice',#11 u'view_invoice',#12 u'confirm_invoice',#13 u'remove_invoice',#14 u'delete_invoice',#15 ] perms=[] for i in range(len(perm_names)): perms.append(Permission(perm_names[i])) Session.add_all(perms) #========================================Creating groups ======================================== admin_g = Group(u'admin') admin_g.permissions = perms Session.add(admin_g) customer_g = Group('customer') Session.add(customer_g) product_editor = Group(u'product_editor') product_editor.permissions = perms[1:3] Session.add(product_editor) product_power = Group('product_power') product_power.permissions = perms[1:4] Session.add(product_power) user_editor = Group('user_editor') user_editor.permissions = perms[4:7] Session.add(user_editor) user_power = Group('user_power') user_power.permissions = perms[4:10] Session.add(user_power) invoice_editor = Group('invoice_editor') invoice_editor.permissions = perms[10:14] Session.add(invoice_editor) invoice_power = Group('invoice_power') invoice_power.permissions = perms[10:] Session.add(invoice_power) #=========================================Creating staff users ====================================== admin_u = User(u'admin',u'admin',u'admin','admin',[admin_g],0,None,0,None,False,[],[],[],[],[],[]) #admin_u.groups.append(admin_g) admin_u.emails = [Email('*****@*****.**',admin_u)] Session.add(admin_u) product_editor_u = User('product_editor','editor','product_editor','product_editor',[product_editor],0,None,0,None,False,[],[],[],[],[],[]) product_editor_u.emails = [Email('*****@*****.**',product_editor_u)] Session.add(product_editor_u) product_power_u = User('product_power','power','product_power','product_power',[product_power],0,None,0,None,False,[],[],[],[],[],[]) product_power_u.emails = [Email('*****@*****.**',product_power_u)] Session.add(product_power_u) invoice_editor_u = User('invoice_editor','editor','invoice_editor','invoice_editor',[invoice_editor],0,None,0,None,False,[],[],[],[],[],[]) invoice_editor_u.emails = [Email('*****@*****.**',invoice_editor_u)] Session.add(invoice_editor_u) invoice_power_u = User('invoice_power','power','invoice_power','invoice_power',[invoice_power],0,None,0,None,False,[],[],[],[],[],[]) invoice_power_u.emails = [Email('*****@*****.**',invoice_power_u)] Session.add(invoice_power_u) user_editor_u =User('user_editor','editor','user_editor','user_editor',[user_editor],0,None,0,None,False,[],[],[],[],[],[]) user_editor_u.emails = [Email('*****@*****.**',user_editor_u)] Session.add(user_editor_u) user_power_u = User('user_power','power','user_power','user_power',[user_power],0,None,0,None,False,[],[],[],[],[],[]) user_power_u.emails= [Email('*****@*****.**',user_power_u)] Session.add(user_power_u) #===================================Creating User/Product tags =============================== user_tags = ['darokhane', 'Lavazeme arayeshi forsh', 'Arayeshgah', 'Namayandehaye Shahrestanha', 'wholesale', 'تست', ] product_tags = ['Tweezers', 'Scissors', 'Nail Clippers', 'Brushes', 'Sponges', 'Nail files', 'Bath range', 'Manicure & Pedicure kits', 'Hair range', 'Others' ] utags=[] for tag in user_tags: utag = UserTag(tag) Session.add(utag) utags.append(utag) ptags=[] for tag in product_tags: ptag = ProductTag(tag) Session.add(ptag) ptags.append(ptag) # ==============================================Creating Customers========================== customers = create_user(utags,customer_g,0,90,False) Session.add_all(customers) Session.add_all(create_user(utags,customer_g,90,100,True)) #=========================================== Creating Products ================================ counter=0 lenptags = len(ptags) products =[] for i in range(1,110): counter+=1 product = Product('product%s'%i, 'description%s'%i, i*10, i*9, (i*10)+17, datetime.now(), 'brand%s'%(i%2), [], [ptags[(counter-1)%lenptags],ptags[counter%lenptags]] ) product.wholesale_price = product.sell_price - 2 product.code = i+10045 products.append(product) product.deleted = False Session.add_all(products) #================================================Creating Invoices =============================== import time invoices =[] product_len = len(products) customers_len = len(customers) td = timedelta(100) now = datetime.now() past = now-td now = time.mktime(now.utctimetuple()) past = time.mktime(past.utctimetuple()) for i in range(0,customers_len): irange = int(random.uniform(2,30)) dates = [] for j in range(0,irange): date =datetime.fromtimestamp(random.randrange(past,now,100)) dates.append(date) for date in dates: invoice = Invoice(date,customers[i],None,'desc %i'%i,0,[],bool(i%2)) product_ids=[] prange = int(random.uniform(3,30)) for k in range(0,prange): product_ids.append(int(random.uniform(0,product_len))) product_ids = set(product_ids) invoice_items = [] totalprice = 0 for id in product_ids: quantity = int(random.uniform(1,30)) item = Invoice_item( products[id], invoice, quantity, products[id].sell_price*quantity, Description = "desc%s"%i, unitprice = products[id].sell_price, ) invoice_items.append(item) totalprice += products[id].sell_price*quantity invoice.total_price = totalprice invoice.invoice_items = invoice_items Session.add(invoice) invoices.append(invoice) admin_u.staff_invoices = invoices[10:60] invoice_editor_u.staff_invoices = invoices[20:70] invoice_power_u.staff_invoices = invoices[70:150] try: Session.commit() except: Session.rollback() print '=================================ERRRRRRRRRRRRORRRRRRRRRRRRRRRRrrr========================'
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'))
def setup_app(command, conf, vars): """Place any commands to setup kazhal here""" # Don't reload the app if it was loaded under the testing environment if not pylons.test.pylonsapp: load_environment(conf.global_conf, conf.local_conf) # Create the tables if they don't already exist Base.metadata.create_all(bind=Session.bind) log.info("Adding initial users, groups and permissions...") random.seed(1398) # =================================================Site settings============================= settingsf = file(conf['settings_file'],'wb') settings = {'server_tz':'UTC', 'user_tz':'Iran', 'invoicealertmail':'[email protected],[email protected]', 'invoicesms':'091213433,234542245,987987', 'contactusmail':'[email protected],[email protected]', 'contactusSMS':'02342342,454776', 'invoicealertfrom':'*****@*****.**', 'forgotpass':'******', 'userconf':'*****@*****.**', 'ip_address':'188.221.122.65' } pickle.dump(settings,settingsf) settingsf.close() # =================================================Creating permissions ============================= perm_names=[ u'admin', #0 u'add_product', #1 u'edit_product',#2 u'remove_product', #3 u'view_user',#4 u'add_user',#5 u'edit_user', #6 u'delete_user', #7 u'reset_user_password', #8 u'add_cradit',#9 u'edit_invoice', #10 u'add_invoice',#11 u'view_invoice',#12 u'confirm_invoice',#13 u'remove_invoice',#14 u'delete_invoice',#15 ] perms=[] for i in range(len(perm_names)): perms.append(Permission(perm_names[i])) Session.add_all(perms) #========================================Creating groups ======================================== admin_g = Group(u'admin') admin_g.permissions = perms Session.add(admin_g) customer_g = Group('customer') Session.add(customer_g) product_editor = Group(u'product_editor') product_editor.permissions = perms[1:3] Session.add(product_editor) product_power = Group('product_power') product_power.permissions = perms[1:4] Session.add(product_power) user_editor = Group('user_editor') user_editor.permissions = perms[4:7] Session.add(user_editor) user_power = Group('user_power') user_power.permissions = perms[4:10] Session.add(user_power) invoice_editor = Group('invoice_editor') invoice_editor.permissions = perms[10:14] Session.add(invoice_editor) invoice_power = Group('invoice_power') invoice_power.permissions = perms[10:] Session.add(invoice_power) #=========================================Creating staff users ====================================== admin_u = User(u'admin',u'admin',u'admin','admin',[admin_g],0,None,0,None,False,[],[],[],[],[],[]) #admin_u.groups.append(admin_g) admin_u.emails = [Email('*****@*****.**',admin_u)] Session.add(admin_u) product_editor_u = User('product_editor','editor','product_editor','product_editor',[product_editor],0,None,0,None,False,[],[],[],[],[],[]) product_editor_u.emails = [Email('*****@*****.**',product_editor_u)] Session.add(product_editor_u) product_power_u = User('product_power','power','product_power','product_power',[product_power],0,None,0,None,False,[],[],[],[],[],[]) product_power_u.emails = [Email('*****@*****.**',product_power_u)] Session.add(product_power_u) invoice_editor_u = User('invoice_editor','editor','invoice_editor','invoice_editor',[invoice_editor],0,None,0,None,False,[],[],[],[],[],[]) invoice_editor_u.emails = [Email('*****@*****.**',invoice_editor_u)] Session.add(invoice_editor_u) invoice_power_u = User('invoice_power','power','invoice_power','invoice_power',[invoice_power],0,None,0,None,False,[],[],[],[],[],[]) invoice_power_u.emails = [Email('*****@*****.**',invoice_power_u)] Session.add(invoice_power_u) user_editor_u =User('user_editor','editor','user_editor','user_editor',[user_editor],0,None,0,None,False,[],[],[],[],[],[]) user_editor_u.emails = [Email('*****@*****.**',user_editor_u)] Session.add(user_editor_u) user_power_u = User('user_power','power','user_power','user_power',[user_power],0,None,0,None,False,[],[],[],[],[],[]) user_power_u.emails= [Email('*****@*****.**',user_power_u)] Session.add(user_power_u) #===================================Creating User/Product tags =============================== user_tags = ['داروخانه', 'لوازم آرایشی فروش', 'آرایشگاه', 'نمایندگی شهرستان', 'wholesale' ] product_tags = ['موچین', 'قیچی', 'ناخن گیر', 'برس', 'اسفنج', 'سوهان ناخن', 'لوازم حمام', 'مانیکور و پتی کور', 'مو و ابرو', 'متفرقه' ] utags=[] for tag in user_tags: utag = UserTag(tag) Session.add(utag) utags.append(utag) ptags=[] for tag in product_tags: ptag = ProductTag(tag) Session.add(ptag) ptags.append(ptag) # ==============================================Creating Customers========================== customers = create_user(utags,customer_g,0,90,False) Session.add_all(customers) Session.add_all(create_user(utags,customer_g,90,100,True)) #=========================================== Creating Products ================================ products =[] ## make a list of photos in the public pics and build a database row for them #put all your picture files in this directory './kazhal/public/pics' before installing the app to create #database entries for all of them... filenames = os.listdir('./kazhal/public/pics') filenames.pop(filenames.index('thumbs')) rows = unicode_csv_reader(open('listofproducts.csv','rb')) for row in rows: name=row[2] code = int(row[3]) wholesale = int(row[4]) filename = str(code)+'.jpg' if filename in filenames: filenames.pop(filenames.index(filename)) photo = [Photo(filename)] else: photo = [] product = Product('%s'%name, '', 0, 0, wholesale, #sell price datetime.now(), 'Basic Care', [], [] ) product.wholesale_price = wholesale product.code = code product.deleted = False product.photos=photo products.append(product) #================================================Creating extra photos =========================== photos =[] for item in filenames: photos.append(Photo(item)) Session.add_all(photos) Session.add_all(products) #================================================Creating Invoices =============================== import time invoices =[] product_len = len(products) customers_len = len(customers) td = timedelta(100) now = datetime.now() past = now-td now = time.mktime(now.utctimetuple()) past = time.mktime(past.utctimetuple()) for i in range(0,customers_len): irange = int(random.uniform(2,20)) dates = [] for j in range(0,irange): date =datetime.fromtimestamp(random.randrange(past,now,100)) dates.append(date) for date in dates: invoice = Invoice(date,customers[i],None,'desc %i'%i,0,[],bool(i%2)) product_ids=[] prange = int(random.uniform(3,20)) for k in range(0,prange): product_ids.append(int(random.uniform(0,product_len))) product_ids = set(product_ids) invoice_items = [] totalprice = 0 for id in product_ids: quantity = int(random.uniform(1,20)) item = Invoice_item( products[id], invoice, quantity, products[id].sell_price*quantity, Description = "desc%s"%i, unitprice = products[id].sell_price, ) invoice_items.append(item) totalprice += products[id].sell_price*quantity invoice.total_price = totalprice invoice.invoice_items = invoice_items Session.add(invoice) invoices.append(invoice) admin_u.staff_invoices = invoices[10:60] invoice_editor_u.staff_invoices = invoices[20:70] invoice_power_u.staff_invoices = invoices[70:150] try: Session.commit() except: Session.rollback() print '=================================ERRRRRRRRRRRRORRRRRRRRRRRRRRRRrrr========================'