Example #1
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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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========================'
Example #2
0
    def create(self):
        action = request.params.getone('action')
        values = dict(request.params)
        del values['action']
        if action == _('Add Photo'):
            return render_new_form(
                self.menu_items,
                values=values,
                number_of_photos = number_of_photos(values) + 1
            )
        if action.startswith(_('Remove')):
            new_values = remove_item(values,action,'photo')                
            return render_new_form(
                self.menu_items,
                values=new_values,                
                number_of_photos = number_of_photos(new_values)
            )
        if action == _('Save'):
            schema = NewProductForm()
            try:
                result = schema.to_python(dict(request.params), c)
            except Invalid, e:
                return render_new_form(
                    self.menu_items,
                    values=values,
                    errors=variabledecode.variable_encode(
                        e.unpack_errors() or {},
                        add_repetitions=False
                        ),
                    number_of_photos=number_of_photos(values)
                )
            else:
                #save the fucking photo
                photos =[]
                for picfile in 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()
                    photos.append(Photo(permanent_file.name.split('/')[-1]))
                    permanent_file.close()
                product = Product(
                    result['name'],
                    result['description'],
                    result['quantity'],
                    result['buy_price'],
                    result['sell_price'],
                    result['buy_date'],
                    result['brand'],
                    photos,
                    result['tag']
                )
                product.code = result['code']
                product.wholesale_price = result['wholesale_price']
                product.deleted = False
                Session.add(product)
                Session.commit()

                h.flash(_('Product added successfully.'))
                redirect(url(controller='product', action='index'))    
Example #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',
                'invoicealertfrom':'ma[email protected]',
                'forgotpass':'[email protected]',
                'userconf':'[email protected]',
                '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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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('[email protected]',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========================'