示例#1
0
def create_user(tags,group,start_number,end_number,pending):
	lenutags = len(tags)
	us = []
	for i in range(start_number,end_number):
		test_u = User(u'test%s'%i,
			      u'test%s'%i,
			      u'test%s'%i,
			      'test%s'%i,
			      [group],
			      i,
			      None,
			      i*10000,
			      None,
			      False,
			      [],
			      [],
			      [],
			      [],
			      [],
			      [tags[(i-1)%lenutags],tags[i%lenutags]],
			      0,
			      pending
			      )    
		test_mail = Email('*****@*****.**'%i,test_u)
		test_u.emails = [test_mail]    
		add = Address('city','add1%s'%i,'add2%s'%i,'state','132%s'%(i%2),test_u,None)
		test_u.addresses = [add]
		phone = Phone('landline','2074556%s'%i, test_u)
		test_u.phones = [phone]
		us.append(test_u)
	return us
示例#2
0
    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"])
示例#3
0
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========================'
示例#4
0
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========================'