Esempio n. 1
0
def setup():
    # Recreate database each time for demo
    Base.metadata.drop_all(bind=db.engine)
    Base.metadata.create_all(bind=db.engine)
    db.session.add(Store('Calculator', 'Bobs Electronics', 89, "electronics"))
    db.session.add(Store('Sour Patch Kids', 'Candy4U', 4, "food"))
    db.session.commit()
Esempio n. 2
0
def store_add_post():
    """
    store 添加商店

    """
    db = g._imdb
    developer_id = session['user']['id']
    
    appid = config.KEFU_APPID
    name = request.form['name'] if request.form.has_key('name') else None
    if not name:
        return INVALID_PARAM()

    mode = default_mode
    db.begin()
    if mode == MODE_BROADCAST:
        gid = Group.create_group(db, appid, 0, name, False)
    else:
        gid = 0
    store_id = Store.create_store(db, name, gid, mode, developer_id)
    db.commit()

    #将名称存储redis,用于后台推送
    Store.set_store_name(g.im_rds, store_id, name)

    if gid:
        content = "%d,%d,%d"%(gid, appid, 0)
        publish_message(g.im_rds, "group_create", content)

    obj = {"store_id":store_id}

    return redirect(url_for('.store_index'))
Esempio n. 3
0
 async def create_store(self, ctx, name: str):
     """ Create a store """
     store = Store.find_one({'name': name})
     if not store:
         store = Store.insert_one({'name': name})
         return await ctx.send(f'```css\nCreated store "{name}"\n```')
     await ctx.send(f'```fix\nA store already exists with that name\n```')
Esempio n. 4
0
def store_index():
    """
    store 模块首页

    """
    print request.args
    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 10))

    developer_id = session['user']['id']

    print offset, limit, developer_id
    db = g._imdb
    count = Store.get_store_count(db, developer_id)
    stores = Store.get_page_stores(db, developer_id, offset, limit)

    g.pagination.setdefault()
    g.pagination.rows_found = count
    g.pagination.limit = limit
    g.pagination.offset = offset

    return render_template('store/index.html',
                           data={'offset': offset, 'list': stores,
                                 'pagination': g.pagination,
                                 })
Esempio n. 5
0
def creation_tables():

    database.execute_sql("SET FOREIGN_KEY_CHECKS=0")

    if CategoriesProduct.table_exists():
        CategoriesProduct.drop_table(cascade=True)

    if Category.table_exists():
        Category.drop_table(cascade=True)

    if Product.table_exists():
        Product.drop_table(cascade=True)

    if User.table_exists():
        User.drop_table(cascade=True)

    if Store.table_exists():
        Store.drop_table(cascade=True)

    database.execute_sql("SET FOREIGN_KEY_CHECKS=1")

    User.create_table()
    Store.create_table()
    Product.create_table()
    Category.create_table()
    CategoriesProduct.create_table()
Esempio n. 6
0
    async def store_stock(self, ctx, store_name: str, item_name: str):
        store = Store.find_one({'name': store_name})
        if not store:
            return await ctx.send(
                f'```fix\nCould not find store "{store_name}"\n```')
        item = Item.find_one({'name': item_name})
        if not item:
            return await ctx.send(
                f'```fix\nCould not find item "{item_name}"\n```')

        store = Prodict.from_dict(store)
        item = Prodict.from_dict(item)
        if store.item_list:
            if item.id in store['item_list']:
                return await ctx.send(
                    f'```fix\nItem "{item_name}" already exists in "{store_name}"\n```'
                )
            store.item_list.append(item.id)
            print('exist')
        else:
            print('not exist')
            store.item_list = [item.id]

        Store.save(store)

        await ctx.send(f'```css\nStocked "{item_name}" in "{store_name}"\n```')
Esempio n. 7
0
async def add_store(name: str, token: str, user_id: str) -> Store:
    store = Store(name=name, token=token, user_id=user_id)
    if hasattr(store, "id"):
        delattr(store, "id")
    ret = await db.stores.insert_one(store.dict(by_alias=True))
    store.id = ret.inserted_id
    return store
Esempio n. 8
0
def add_store():
    db = g._imdb
    developer_id = g.developer_id
    appid = KEFU_APPID
    name = request.form['name'] if request.form.has_key('name') else None
    if not name:
        return INVALID_PARAM()

    mode = default_mode
    db.begin()
    if mode == MODE_BROADCAST:
        gid = Group.create_group(db, appid, 0, name, False)
    else:
        gid = 0
    store_id = Store.create_store(db, name, gid, mode, developer_id)
    db.commit()

    #将名称存储redis,用于后台推送
    Store.set_store_name(g.im_rds, store_id, name)

    if gid:
        content = "%d,%d,%d"%(gid, appid, 0)
        publish_message(g.im_rds, "group_create", content)

    obj = {"store_id":store_id}
    return make_response(200, obj)
Esempio n. 9
0
def insert_stores():
    Store.create(user_id=1,
                 name='Veterinaria Ramírez',
                 address='Av. Venezuela 202')
    Store.create(user_id=2,
                 name='Veterinaria Jei',
                 address='Av. 5 de Abril 05-04')
Esempio n. 10
0
def store_add_post():
    """
    store 添加商店

    """
    db = g._imdb
    developer_id = session['user']['id']

    appid = config.KEFU_APPID
    name = request.form['name'] if request.form.has_key('name') else None
    if not name:
        return INVALID_PARAM()

    db.begin()
    gid = Group.create_group(db, appid, 0, name, False)
    store_id = Store.create_store(db, name, gid, developer_id)
    db.commit()

    #将名称存储redis,用于后台推送
    Store.set_store_name(g.im_rds, store_id, name)

    content = "%d,%d,%d" % (gid, appid, 0)
    publish_message(g.im_rds, "group_create", content)

    obj = {"store_id": store_id}

    return redirect(url_for('.store_index'))
Esempio n. 11
0
def index():
    # with this code, your need to directly type in /store
    store_name = request.args.get('store_name')
    print(store_name)
    newstore = Store(name=store_name)
    newstore.save()
    return render_template('index.html', store_name=store_name)
Esempio n. 12
0
def store_index():
    """
    store 模块首页

    """
    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 10))

    developer_id = session['user']['id']

    print offset, limit, developer_id
    db = g._imdb
    count = Store.get_store_count(db, developer_id)
    stores = Store.get_page_stores(db, developer_id, offset, limit)

    g.pagination.setdefault()
    g.pagination.rows_found = count
    g.pagination.limit = limit
    g.pagination.offset = offset

    return render_template('store/index.html',
                           data={
                               'offset': offset,
                               'list': stores,
                               'pagination': g.pagination,
                           })
Esempio n. 13
0
    async def view(self, ctx, store=None):
        """ View store """
        user = await author.get(ctx.author)
        store_list = ''
        stores = StoreModel.find()
        loaded_store = None
        if store is None:
            if not stores:
                return await ctx.send(f'```fix\nThere are no stores setup"\n```')
            if stores.count() == 1:
                loaded_store = Prodict.from_dict(stores[0])
                item_list = ''
                loaded_store.inventory = sorted(loaded_store.inventory, key=curried.get_in(['price']), reverse=False)
                for i, item in enumerate(loaded_store.inventory):
                    item = Prodict.from_dict(item)
                    if user['quote_to'] != 'USD':
                        rates = await coins.rate_convert()
                        item.price = rates[user['quote_to']] * item.price
                        item.payout = rates[user['quote_to']] * item.payout
                    formatted_price = currency.symbol(user["quote_to"]) + '{0:.2f}'.format(item.price)
                    formatted_payout = "{0:.2f}".format(item.payout)
                    item_list += f'{i + 1}. {item.name}{" " * (15 - len(item.name))}{formatted_price}{" " * (10 - len(formatted_price))}{item.about.format(payout=formatted_payout, rate=str(item.rate) + " minutes")}\n'
                return await ctx.send(
                    f'```py\n{user.quote_to}\nStore name: {loaded_store.name}\n\nItem{" " * (18 - len("item"))}Price{" " * (10 - len("price"))}Description\n\n{item_list}\n\nQoins represent a USD value by default, the prices will convert depending upon what quote currency you have set on your account.  Use the "{self.config.prefix[0]}sq <currency symbol>" command to change it```')
            for i, _store in enumerate(stores):
                _store = Prodict.from_dict(_store)
                item_count = len(_store.inventory)
                store_list += f'\n{i + 1}. {_store.name}{" " * (12 - len("Name"))}{item_count}{" " * (10 - len(str(item_count)))}{_store.about}'
            store_list_head = f'\nName{" " * (15 - len("Name"))}Item Count{" " * (10 - len("item"))}Description'

            await ctx.send(f'```diff\nStore list:\n{store_list_head}{store_list}\n```')
            return await ctx.send_help('view')

        store_list = []
        for i, _store in enumerate(stores):
            store_list.append(_store)
        if store.isnumeric():
            if int(store) - 1 in range(len(store_list)):
                loaded_store = store_list[int(store) - 1]
        else:
            loaded_store = StoreModel.find_one({'name': store})

        if not loaded_store:
            return await ctx.send(f'```fix\nCould not find store "{store}"\n```')

        loaded_store = Prodict.from_dict(loaded_store)
        item_list = ''
        for i, item in enumerate(loaded_store.inventory):
            item = Prodict.from_dict(item)
            if user['quote_to'] != 'USD':
                rates = await coins.rate_convert()
                item.price = rates[user['quote_to']] * item.price
                item.payout = rates[user['quote_to']] * item.payout
            formatted_price = currency.symbol(user["quote_to"]) + '{0:.2f}'.format(item.price)
            formatted_payout = "{0:.2f}".format(item.payout)

            item_list += f'{i + 1}. {item.name}{" " * (18 - len(item.name))}{formatted_price}{" " * (10 - len(formatted_price))}{item.about.format(payout=formatted_payout)}\n'
        await ctx.send(
            f'```py\n{user.quote_to}\n{loaded_store.name}\n\nItem{" " * (21 - len("item"))}Price{" " * (10 - len("price"))}Description\n\n{item_list}```')
Esempio n. 14
0
def store_create():
    store_name = request.form.get('store_name')
    store = Store(name=store_name)
    if store.save():
        flash("Store created!", "success")
        return redirect(url_for('store_new'))
    else:
        return render_template('store.html', errors=store.errors)
Esempio n. 15
0
def store_form():
    s = Store(name=request.args['name'])

    if s.save():
        flash("Successfuly save")
        return redirect(url_for('store'))
    else:
        return render_template('store.html', name=request.args['name'] )
Esempio n. 16
0
def create_store():
    s = Store(name=request.form.get('store_name'))
    if s.save():
        flash("successfully save")
        return redirect(url_for('create_store'))
    else:
        return render_template('store.html',
                               name=request.form.get('store_name'))
Esempio n. 17
0
def shop_form(): 
    store_name = request.form.get('store_name')
    store_details = Store(name=store_name)
    if store_details.save(): 
        flash('Store sucessfully saved!')
        return redirect(url_for('index'))
    else: 
        return render_template('shop.html', store_name = store_name)
Esempio n. 18
0
    def get(self):
        cursor = self.request.get('cursor', "")
        page = self.request.get_range('page')
        
        if cursor:
            cursor = Cursor(urlsafe=cursor)
            ss, next_curs, more = Store.query().fetch_page(100, start_cursor=cursor)
        else:
            ss, next_curs, more = Store.query().fetch_page(100)

        base_template = u'''
            <div>
                {}
            </div>
            <form>
                <input name='cursor' value='{}'>
                <input type='submit' value="下一頁">
            </form>
        '''

        store_template = u'''
            <div>
                <h2>{0}{1.name}</h2>
                <a href="/store/{0}?action=delete"  target="_blank">刪除store</a>
                <ul>{2}</ul>
            </div>
        
        '''

        img_template = u'''
            <li>
                <img src="{1}">
                <a href="/images/{0}?action=delete&{2}" target="_blank" >刪除圖片</a>
                <a href="/images/{0}?action=set&tag=Parity&{2}" target="_blank" >平價</a>
                <a href="/images/{0}?action=set&tag=Meals&{2}" target="_blank" >簡餐</a>
                <a href="/images/{0}?action=set&tag=Restaurant&{2}" target="_blank" >餐廳</a>
                <a href="/images/{0}?action=set&tag=Space&{2}" target="_blank" >空間</a>
                <a href="/images/{0}?action=set&tag=drink&{2}" target="_blank" >飲料</a>
                <div>{3}</div>
            </li>
        '''
        stores = []
        for s in ss:
            imgs = []
            for img in s.imgs:
                try:
                    code = urllib.urlencode({'url':img.image})
                    imgs.append(img_template.format(s.key.id(), img.image, code, img.tag))
                except Exception as e:
                    pass

            imgs = "\n".join(imgs)
            try:
                stores.append(store_template.format(s.key.id(), s, imgs))
            except Exception as e:
                print e
        html = base_template.format("\n".join(stores), next_curs.urlsafe())
        self.response.out.write(html)
Esempio n. 19
0
def store_create():
    # get form value in form
    store_name = request.form.get('store_name')
    store = Store(name=store_name)
    if store.save():
        flash("Store created!", "success")
    else:
        flash("Unable to create!", "danger")
    return redirect(url_for('store_new'))
def submitBusiness_accepted(request):
	Name = request.POST['name']
	Owner = request.user
	StoreType = request.POST['storeType']
	Address = request.POST['address']
	Info = request.POST['info']
	new_store = Store(name = Name, owner = Owner, storeType = StoreType, address = Address, info = Info)
	new_store.save()
	return HttpResponseRedirect('success')
Esempio n. 21
0
def store_created():

    store_name = request.form.get("store_name")
    store = Store(name=store_name)
    if store.save():
        flash("Successfully added", "success")
    else:
        flash("Duplicate Entry!!", "danger")
    return redirect(url_for("store_new"))
Esempio n. 22
0
def s_create():
    store_name = request.form.get('store_name')
    s = Store(name=store_name)

    if s.save():
        flash(f"Successfully saved {store_name}")
        return redirect(url_for('store'))
    else :
        return render_template('store.html', name=store_name, errors=s.errors)
Esempio n. 23
0
def store_create():
    store_name = request.form.get('store_name')
    store = Store(name=store_name)
    if store.save():
        flash(f"{store_name} has been created!", 'info')
    else:
        flash('Something went wrong!')

    return redirect('/')
Esempio n. 24
0
def store_form():
    name=request.form.get('store_name')
    s = Store(name=name)

    if s.save():
        # flash("Successfully saved!") #Set flash for another time. Uses secret key: https://flask.palletsprojects.com/en/1.0.x/quickstart/#sessions
        return redirect(url_for('store'))
    else:
        return render_template('store.html', name=name)
Esempio n. 25
0
def update(id):
    store = Store.update(name=request.form['store_name']).where(Store.id == id)
    store_id = Store.get_by_id(id)
    if store.execute():
        flash('Succesfully updated store name!', 'success')
        return redirect(url_for('edit', store=store, id=store_id))
    else:
        flash('Failed to update store name :/', 'danger')
        return redirect(url_for('update'))
Esempio n. 26
0
def create():
    store_name = request.form['store_name']
    # store_name = request.form.get('store_name') //this is a 'softcode' version of the code above
    store = Store(name=store_name)
    if store.save():
        flash('Successfully Created Store', "success")
        return redirect(url_for('show'))
    else:
        flash('failed to create store', "danger")
        return redirect(url_for('show'))
Esempio n. 27
0
def add_store():
    store = Store(name=request.form["store_name"])
    if store.save():
        flash("Successfully saved!")
        return redirect("/")
    else:
        flash("Store already exists! Trash!")
        return render_template("store.html",
                               name=request.form["store_name"],
                               errors=store.errors)
Esempio n. 28
0
def create_store():
    s = Store(name=request.form.get('name'))

    if s.save():
        flash("successfully saved")
        return redirect(url_for('store'))
    else:
        for e in s.errors:
            flash(e)
        return render_template('store.html', name=request.form['name'])
Esempio n. 29
0
def create_store():
    store_name = request.form.get("store_name")
    store = Store(name=store_name)

    if store.save():
        flash(f"Saved store: {store_name}")
        return redirect(url_for("new_store"))
    else:
        flash("That name is already taken")
        return render_template("store.html", errors=store.errors)
def create():
    store_name = request.form.get('store_name')
    store = Store(name=store_name)

    if store.save():  # save method returns either 0 or 1
        flash(f"Saved Store: {store_name}")
        return redirect(url_for('addstore'))
    else:
        flash('Name is already taken, pick another')
        return render_template('store.html', errors=store.errors)
Esempio n. 31
0
def destroy_store(store_id):
    store_list = Store.select()

    if request.method == "POST":
        store = Store.get_by_id(store_id)
        flash(f"Closed {store.name}.")
        store.delete_instance()
        return redirect(url_for('index_stores'))
    else:
        return render_template('stores.html', store_list=store_list)
Esempio n. 32
0
 def post(self, request, *args):
     name = request.POST['name']
     owner = request.POST['owner']
     latlon = request.POST['location'].split(",")
     owner = Seller.objects.get(id=owner)
     location = fromstr('POINT(%s %s)' % (latlon[0], latlon[1]), srid=4326)
     s = Store(name=name, owner=owner, location=location)
     s.save()
     success = True
     context = {"success": success, "id": s.id}
     return self.render_to_json_response(context)
Esempio n. 33
0
def store_info(store_number):
	if request.method == 'POST':
		new_store_name = request.form['new_store_name']
		Store.update({Store.name: new_store_name}).where(Store.id == store_number)
		return redirect(url_for('store/index'))
	else:
		store_id = Store.select().where(Store.id == store_number)
		num_of_wh = True
		for store in store_id:
			num_of_wh = len(list(store.warehouses))
		return render_template('store_page.html', store_id=store_id, num_of_wh=num_of_wh)
Esempio n. 34
0
 def post(self, name):
     if StoreModel.find_by_name(name):
         return dict(message=f'A store with name {name} already exists'), 400
     
     store = StoreModel(name)
     try:
         store.save()
     except:
         return dict(message='An error occurred while creating the store'), 500
     
     return store.json(), 201
Esempio n. 35
0
def create_store():
    if request.method == "POST":
        s = Store(name=request.form.get('store_name'))
        if s.save():
            flash(
                f"Store name {request.form['store_name']} successfully saved.")
            return redirect(url_for('new_store'))
        else:
            return render_template('add-store.html',
                                   name=request.form['store_name'],
                                   errors=s.errors)
Esempio n. 36
0
 def set_key(self, classifier, key, value):
     """
     Set the value held by the classifier, key composite key.
     """
     session = self.sessionFactory()
     store = Store()
     value = json.dumps(value)
     store.value = value
     store.key = key
     store.classifier = classifier
     session.merge(store)
     session.commit()
Esempio n. 37
0
def upload():
    with open('data.csv') as f:
        reader = csv.DictReader(f)
        for row in reader:
            try:
                s = Store()
                
                print row['name'], row['images'], row['types']
                if re.search("\[.*\]", row['reference']):
                    row['place_id'] = row['scope']
                    row['scope'] = row['latlng']
                    row['latlng'] = row['address']
                    row['address'] = row['photos']
                    row['photos'] = row['reference']

            

                print row['name'], row['images'], row['types']
                s.tags = json.loads(row['types'])
                s.point = db.GeoPt(*eval(row['latlng']))
                s.reference = row['reference'] and row['reference'][0] or ""
                s.address = row['address']
                s.name = row['name']

                
                for img in eval(row['images']):
                    image = Image()
                    image.image = img
                    image.put()
                    s.imgs.append(image)
            except Exception as e:
                pass
            finally:
                s.put()
Esempio n. 38
0
 def post(self):
     '''Add a new store by the method post'''
     try:
         args = self.reqparse.parse_args()
         store = Store(
             name=args['name'],
             address=args['address'],
             phone=args['phone'],
             owner=args['owner'],
             geolocation=args['geolocation']
         )
         store.save()
         return {'store': marshal(store, store_fields)}, 201
     except Exception:
         abort(500)
Esempio n. 39
0
 def set_key_list(self, classifier, key_value_tuples):
     """
     Given a list of tuples of classifier, key, value set them all.
     It is more efficient to use one session and merge all of the objects
     at once than to merge them individually.
     """
     session = self.sessionFactory()
     for key, value in key_value_tuples:
         store = Store()
         value = json.dumps(value)
         store.value = value
         store.key = key
         store.classifier = classifier
         session.merge(store)
     session.commit()
Esempio n. 40
0
    def test_should_have_store_as_addressable(self):
        """
        Prueba que una direccion pueda ser asociada
        a una tienda
        """

        store = Store(name="My store")
        store.save()

        address = Address()
        address.street1 = "Cra 7 # 6-19"
        address.addressable_object = store 
        address.save()

        address_from_db = Address.objects.get(id=address.id)
        self.assertEqual(address_from_db.addressable_type.name, 'store')
Esempio n. 41
0
def store_seller_post(store_id):
    """
    store 添加商店人员

    """
    db = g._imdb
    developer_id = session['user']['id']

    form = request.form
    name = form.get('name', '')
    password = form.get('password', '')
    number = form.get('number', '')
    if not name or not password or not store_id:
        return INVALID_PARAM()
        
    if not number:
        number = None
    password = md5.new(password).hexdigest()

    group_id = Store.get_store_gid(db, store_id)

    db.begin()
    seller_id = Seller.add_seller(db, name, password, store_id, group_id, number)
    Group.add_group_member(db, group_id, seller_id)
    db.commit()

    content = "%d,%d"%(group_id, seller_id)
    publish_message(g.im_rds, "group_member_add", content)
    
    return redirect(url_for('.store_seller', store_id=store_id))
Esempio n. 42
0
def store_seller(store_id):
    """
    store 销售人员

    """
    db = g._imdb

    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 10))

    rows_found = Seller.get_seller_count(db, store_id)
    sellers = Seller.get_page_seller(db, store_id, offset, limit)
    store_info = Store.get_store(db, store_id)

    g.pagination.setdefault()
    g.pagination.rows_found = rows_found
    g.pagination.limit = limit
    g.pagination.offset = offset

    return render_template('store/seller.html',
                           data={'offset': offset,
                                 'list': sellers,
                                 'store_info': store_info,
                                 'pagination': g.pagination,
                                 })
Esempio n. 43
0
    def set_data_for(self, main_date):

        try:
            on, end = main_date.current.current
        except:
            on, end = main_date.current
        on = datetime(on.year, on.month, on.day, 0, 0, 0)
        end = datetime(end.year, end.month, end.day, 23, 59, 59)
        reports = []
        this_periode_rpt = Reports.select().where(Reports.date >= on,
                                                  Reports.date <= end)
        for store in Store.select().order_by(Store.name):
            if ([(i) for i in this_periode_rpt.where(Reports.store << [store, ])] == []):
                continue
            cpt = 0
            for prod in Product.select().order_by(Product.name):
                if ([(i) for i in this_periode_rpt.where(Reports.store == store,
                                                         Reports.product << [prod, ])] == []):
                    continue
                dict_store = {}
                repts = this_periode_rpt.where(
                    Reports.store == store, Reports.product == prod)
                dict_store["store"] = store.name if cpt < 1 else ""
                dict_store["product"] = prod.name
                dict_store["sum_qty_in"] = repts.select(
                    peewee.fn.SUM(Reports.qty_use)).where(Reports.type_ == Reports.E).scalar()
                dict_store["sum_qty_out"] = repts.select(
                    peewee.fn.SUM(Reports.qty_use)).where(Reports.type_ == Reports.S).scalar()
                cpt += 1
                reports.append(dict_store)

        self.data = [(rep.get('store'), rep.get('product'), rep.get('sum_qty_in'),
                      rep.get('sum_qty_out')) for rep in reports]
Esempio n. 44
0
def store_detail(store_id):
    """
    store 详情

    """
    db = g._imdb
    store_info = Store.get_store(db, store_id)

    return render_template('store/detail.html', data={'store_info': store_info})
Esempio n. 45
0
def delete_seller(store_id, seller_id):
    rds = g.im_rds
    db = g._imdb

    group_id = Store.get_store_gid(db, store_id)

    db.begin()
    Seller.delete_seller(db, store_id, seller_id)
    if group_id:
        Group.delete_group_member(db, group_id, seller_id)
    db.commit()

    Store.delete_seller_id(rds, store_id, seller_id)

    if group_id:
        content = "%d,%d"%(group_id, seller_id)
        publish_message(g.im_rds, "group_member_remove", content)

    return ""
Esempio n. 46
0
    def get(self, _id):
        store = Store.get_by_id(int(_id))       
        store.key.delete()

        html = '''
        <script>
        window.close();
        </script>
        '''
        self.response.out.write(html)
Esempio n. 47
0
class TestEmployee(TestCase):
    def setUp(self):
        self.region = Region(name="test_region")
        self.region.save()
        self.company = Company(code="1001", name="test_company", region=self.region)
        self.company.save()

        self.store = Store(code="10011001", name="test_store", company=self.company)
        self.store.save()

        self.emp_region = Employee(username="******", organization=self.region)
        self.emp_company = Employee(username="******", organization=self.company)
        self.emp_store = Employee(username="******", organization=self.store)

    def test_organizations(self):
        organizations = self.emp_region.organizations()
        self.assertEquals([self.region], organizations)
        organizations = self.emp_company.organizations()
        self.assertEquals([self.region, self.company], organizations)
        organizations = self.emp_store.organizations()
        self.assertEquals([self.region, self.company, self.store], organizations)

    def test_in_xxx_org(self):
        # employee in region
        self.assertTrue(self.emp_region.in_region())
        self.assertFalse(self.emp_region.in_company())
        self.assertFalse(self.emp_region.in_store())

        # employee in company
        self.assertFalse(self.emp_company.in_region())
        self.assertTrue(self.emp_company.in_company())
        self.assertFalse(self.emp_company.in_store())

        # employee in company
        self.assertFalse(self.emp_store.in_region())
        self.assertFalse(self.emp_store.in_company())
        self.assertTrue(self.emp_store.in_store())

    def test_org(self):
        self.assertEqual(self.emp_region.org(), self.region)
        self.assertEqual(self.emp_company.org(), self.company)
        self.assertEqual(self.emp_store.org(), self.store)
Esempio n. 48
0
    def setUp(self):
        self.region = Region(name="test_region")
        self.region.save()

        self.company = Company(code="1001", name="test_company", region=self.region)
        self.company.save()
        self.company2 = Company(code="1002", name="test_company_2", region=self.region)
        self.company2.save()

        self.store = Store(code="10011001", name="test_store", company=self.company)
        self.store.save()
Esempio n. 49
0
def lastes_reports():
    list_rep = []
    for store in Store.select():
        for prod in Product.select():
            try:
                list_rep.append(Reports.filter(deleted=False, store=store,
                                               product=prod)
                                       .order_by(Reports.date.desc()).get())
            except Exception as e:
                # print(e)
                pass
    return list_rep
Esempio n. 50
0
def warning_of_prod():
    """"""
    l = []
    for store in Store.all():
        for prod in Product.all():
            report = last_report_store_prod(store.name, prod.name)
            try:
                if report.remaining < Config.nb_warning:
                    l.append(report)
            except AttributeError:
                pass
    return l
Esempio n. 51
0
    def setUp(self):
        self.region = Region(name="test_region")
        self.region.save()
        self.company = Company(code="1001", name="test_company", region=self.region)
        self.company.save()

        self.store = Store(code="10011001", name="test_store", company=self.company)
        self.store.save()

        self.emp_region = Employee(username="******", organization=self.region)
        self.emp_company = Employee(username="******", organization=self.company)
        self.emp_store = Employee(username="******", organization=self.store)
Esempio n. 52
0
class TestOrganization(TestCase):
    def setUp(self):
        self.region = Region(name="test_region")
        self.region.save()

        self.company = Company(code="1001", name="test_company", region=self.region)
        self.company.save()
        self.company2 = Company(code="1002", name="test_company_2", region=self.region)
        self.company2.save()

        self.store = Store(code="10011001", name="test_store", company=self.company)
        self.store.save()

    def test_ancestor(self):
        self.assertTrue(self.region.pk == self.company.ancestor().pk)
        self.assertTrue(self.region.pk == self.store.ancestor().pk)

    def test_belong_to(self):
        self.assertTrue(self.store.belong_to(self.company))
        self.assertFalse(self.region.belong_to(self.company))
        self.assertFalse(self.store.belong_to(self.company2))
Esempio n. 53
0
    def refresh_(self, idd):

        self.prod = Product.get(id=idd)
        rest_by_store = ""

        for store in Store.select():
            remaining, nbr_parts = store.get_remaining_and_nb_parts(self.prod)

            if remaining < 10:
                color_style = 'color: DarkGreen'
            if remaining <= 5:
                color_style = 'color: LightCoral'
            if remaining <= 2:
                color_style = 'color: red; text-decoration: blink'
            if remaining >= 10:
                color_style = 'color: LimeGreen;'
            color_style = color_style + \
                "; border:3px solid green; font-size: 15px"
            if Store.select().count() == 1:
                rest_by_store += """ <p><strong style='{color_style}'> {remaining} </strong><i>pièces</i></p>
                """.format(color_style=color_style, remaining=remaining)
            else:
                rest_by_store += """<li> {store}: <strong style='{color_style}'>
                    {nbr_parts} </strong><i>pièces</i> <b>{remaining} </b><i>carton</i>
                    </li>""".format(store=store.name, color_style=color_style, remaining=remaining,
                                    nbr_parts=nbr_parts * remaining)
        width = height = 50
        if self.prod.image_link:
            self.image_btt.setText("Zoom")
            width = 200
            height = 100

        self.info_box.setText(u"""<h2>{name}</h2>
            <h4>Quantité restante:</h4>
            <ul>{remaining}</ul>
            """.format(name=self.prod.name,
                       remaining=rest_by_store))
        self.image.setText("""<img src="{image}" width='{width}'
            height='{height}'>""".format(image=self.prod.image_link,
                                         width=width, height=height))
Esempio n. 54
0
def add_seller(store_id):
    rds = g.im_rds
    db = g._imdb
    form = request.form
    name = form.get('name', '')
    password = form.get('password', '')
    md5_password = form.get('md5_password', '')
    salt = form.get('salt', '')
    number = form.get('number', '')
    is_password_empty = not password and (not md5_password or not salt)

    if not name or is_password_empty or not store_id:
        return INVALID_PARAM()
        
    if not number:
        number = None

    if password:
        password = generate_password_hash(password)
    elif md5_password:
        password = "******"%(salt,md5_password)

    logging.debug("seller name:%s number:%s password md5:%s", name, number, md5_password)
    group_id = Store.get_store_gid(db, store_id)

    db.begin()
    seller_id = Seller.add_seller(db, name, password, store_id, number)
    if group_id:
        Group.add_group_member(db, group_id, seller_id)
    db.commit()

    Store.add_seller_id(rds, store_id, seller_id)

    if group_id:
        content = "%d,%d"%(group_id, seller_id)
        publish_message(g.im_rds, "group_member_add", content)

    obj = {"seller_id":seller_id}
    return make_response(200, obj)
Esempio n. 55
0
    def popup(self, pos):
        row = self.selectionModel().selection().indexes()[0].row()
        if (len(self.data) - 1) < row:
            return False

        self.store = Store.select().where(
            Store.name == self.data[row][0]).get()
        menu = QMenu()
        menu.addAction(QIcon(u"{}edit.png".format(Config.img_cmedia)),
                       u"modifier", lambda: self.prod_edit(self.store))
        menu.addAction(QIcon("{}del.png".format(Config.img_cmedia)),
                       u"supprimer", lambda: self.prod_del(self.store))

        self.action = menu.exec_(self.mapToGlobal(pos))
Esempio n. 56
0
def set_mode(store_id):
    db = g._imdb
    rds = g.im_rds
    developer_id = g.developer_id
    appid = KEFU_APPID
    mode = int(request.form['mode']) if request.form.has_key('mode') else 0
    if mode != 1 and mode != 2 and mode != 3:
        return INVALID_PARAM()
    r = Store.set_mode(db, store_id, mode)
    if r:
        publish_message(rds, "store_update", str(store_id))

    logging.info("set store:%s mode:%s", store_id, mode)
    return ""
Esempio n. 57
0
def delete_store(store_id):
    rds = g.im_rds
    db = g._imdb
    group_id = Store.get_store_gid(db, store_id)

    Store.delete_store(db, store_id, group_id)

    Store.delete_store_name(rds, store_id)
    Store.delete_store_seller(rds, store_id)

    if group_id:
        content = "%d"%group_id
        publish_message(g.im_rds, "group_disband", content)

    return ""
Esempio n. 58
0
    def __init__(self, store, parent=0, *args, **kwargs):

        super(By_storeViewWidget, self).__init__(parent=parent, *args, **kwargs)
        FPeriodHolder.__init__(self, *args, **kwargs)

        self.setWindowTitle("Par store")
        store = Store.filter(name__icontains=store).get()
        self.title = FPageTitle(u"Les rapports de stock pour: %s"%
                                                            store.name)
        self.table = By_storeTableWidget(store, parent=self,
                                         main_date=self.main_date)

        vbox = QVBoxLayout()
        vbox.addWidget(self.title)
        vbox.addWidget(self.periods_bar)
        vbox.addWidget(self.table)

        self.setLayout(vbox)
Esempio n. 59
0
    def get(self, _id):
        _id = int(_id)
        action = self.request.get('action')
        

        url = self.request.get('url')
        s = Store.get_by_id(int(_id))
        imgs = s.imgs


        f = True
        tmp = []
        if action == 'delete':

            for img in imgs:
                if f and img.image == url:
                    f = False
                else:
                    tmp.append(img)

            s.imgs = tmp
            s.put()


        tag = self.request.get('tag')
        if action == 'set':
            for img in imgs:
                if img.image == url:
                    img.tag = tag
                tmp.append(img)

            s.imgs = tmp
            s.put()
        html = '''
        <script>
        window.close();
        </script>
        '''
        self.response.out.write(html)