Exemple #1
0
 def post(self):
     """Create a new menu item"""
     args = self.parser.parse_args()
     name = args.get("name", "")
     description = args.get("description", "")
     price = args.get("price", "")
     if empty(name) or empty(description) or empty(price):
         return {
             "message":
             "You have to specify all"
             " details of an item"
             " such as name, price, description"
         }, 403
     if not valid_name(name):
         return {"message": "Please specify a valid name for item"}, 403
     if not valid_price(price):
         return {
             "message": "Please specify a valid price"
             " for the item"
         }, 403
     if not valid_description(description):
         return {
             "message": "Please specify a valid description "
             "for the item"
         }
     menu_item = Menu(name, description, price)
     saved = menu_item.save()
     if saved:
         return {
             "message": "The menu item was successfully saved",
             "data": menu_item.json1
         }, 201
     return {"message": "There was problem saving the item. Try again"}, 403
Exemple #2
0
def deploy(deploy_type):
    import os
    from flask.ext.migrate import upgrade
    from app.models import BlogInfo, User, ArticleTypeSetting, Source, \
        ArticleType, Plugin, BlogView, Comment

    # ADMIN SETTING
    ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL') or "*****@*****.**"
    ADMIN_NAME = os.environ.get('ADMIN_NAME') or "admin"
    ADMIN_PASSWD = os.environ.get('ADMIN_PASSWD') or "admin"

    # upgrade database to the latest version
    upgrade()

    if deploy_type == 'product':
        # step_1:insert basic blog info
        BlogInfo.insert_blog_info()
        # step_2:insert admin account
        User.insert_admin(email=ADMIN_EMAIL,
                          username=ADMIN_NAME,
                          password=ADMIN_PASSWD)
        # step_3:insert system default setting
        ArticleTypeSetting.insert_system_setting()
        # step_4:insert default article sources
        Source.insert_sources()
        # step_5:insert default articleType
        Menu.insert_menus()
        ArticleType.insert_system_articleType()
        ArticleType.insert_articleTypes()
        # step_6:insert system plugin
        Plugin.insert_system_plugin()
        # step_7:insert blog view
        BlogView.insert_view()
Exemple #3
0
def menu_edit(id):
    '''/admin/Menu/edit'''
    # 生成菜单数据
    data = Menu.mlist_to_tree()
    list = Menu.form_at_tree(data)
    list.insert(0, {"id": "0", "showName": u"顶级菜单"})
    menu = Menu.query.get_or_404(int(id))
    #form
    form = AddmenuForm()
    menus = [(int(n['id']), n['showName']) for n in list]
    form.fid.choices = menus

    if form.validate_on_submit():
        menu.name = form.name.data
        menu.fid = form.fid.data
        menu.hide = form.hide.data
        menu.url = form.url.data
        menu.sort = form.sort.data
        db.session.add(menu)
        db.session.commit()
        return jsonify({'code': 1, 'msg': '菜单修改成功!'})

    if form.errors:
        return jsonify({'code': 0, 'msg': '菜单修改失败!'})

    form.name.data = menu.name
    form.fid.data = menu.fid
    form.hide.data = menu.hide
    form.url.data = menu.url
    form.sort.data = menu.sort

    return render_template('admin/menu/edit.html', form=form, menu=menu)
Exemple #4
0
 def createMenu(self, id = 1):
     with self.app.app_context():
         menu = Menu.query.get(id)
         if not menu:
             menu = Menu(category=MenuType.BREAKFAST)
             menu.save()
         return menu.id
Exemple #5
0
def createdb():
    db.create_all()
    Role.insert_master()
    User.insert_master()
    Menu.insert_master()
    City.insert_master()
    R_User_City.insert_master()
    R_Role_Menu.insert_master()
    CityInfo.insert_master()
Exemple #6
0
def deploy(deploy_type):
    db.drop_all()
    db.create_all()

    if deploy_type == 'generate_data':
        # step_1:insert navs
        Menu.init_menus()
        ArticleType.init_articleTypes()
        User.insert_admin('*****@*****.**', 'adrui', 'adjsjZBR1996')
        Source.insert_source()
Exemple #7
0
 def post(self):
     '''
     添加菜单
     '''
     args = parse_base.parse_args()
     pid = args.get('pid')
     name = args.get('name')
     url = args.get('url')
     icon = args.get('icon')
     sort = args.get('sort')
     _data = Menu.query.filter_by(name = name,is_del = '0').first()
     if _data:
         abort(RET.Forbidden,msg='菜单已存在')
     model_data = Menu()
     model_data.pid = pid
     model_data.name = name
     model_data.url = url
     model_data.icon = icon
     model_data.sort = sort
     model_data.last_editor = g.admin.username
     if model_data.add():
         data = {
                 'status':RET.Created,
                 'msg':'添加成功',
                 'data':model_data
         }
         return marshal(data,sing_fields)
     abort(RET.BadRequest,msg='添加失败,请重试')
Exemple #8
0
    def menu():
        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]

            if access_token:
                user_id = User.decode_token(access_token)
                if isinstance(user_id, int):
                    current_user = User.query.filter_by(id=user_id).first()
                    if request.method == "POST":
                        if current_user.caterer:
                            menu_meals = request.data.get('meal_list', '')
                            date = request.data.get('date', '')
                            if date == '':
                                date = datetime.datetime.now()
                            if menu_meals:
                                meals = [Meal.get(id=id) for id in menu_meals]
                                menu = Menu(date=date)
                                menu.add_meal_to_menu(meals)
                                return {
                                    'message': 'Todays menu has been updated'
                                }, 201

                            return {'message': 'Please add meals to menu'}, 202

                        else:

                            response = {
                                'message':
                                'You are unauthorized to access this'
                            }
                            return make_response(jsonify(response)), 401

                    else:  # GET

                        menu = Menu.query.order_by('menu.date').all()[-1]
                        menu_meals = [item.make_dict() for item in menu.meals]
                        return {
                            'message': 'Here is the menu for today',
                            'menu': menu_meals
                        }, 200

                else:
                    # user is not legit, so the payload is an error message
                    message = user_id
                    response = {'message': message}
                    return make_response(jsonify(response)), 401

            else:
                response = {'message': 'Please input access token'}
                return make_response(jsonify(response)), 401
        else:
            return {'message': 'Please input access token'}
Exemple #9
0
def index():
	'''/admin/index'''
	if not int(current_user.id) == 1:
		menu = Menu.glist_to_tree(session.get('gid'))
	else:
		menu = 	Menu.mlist_to_tree()
	mlist = Menu.form_at_tree(menu)
	session['enable_url'] = filter(None, list(set(auth['url'] for auth in mlist)))
	#处理隐藏菜单
	data = [m for m in mlist if int(m['hide']) == 0]

	return render_template('admin/index.html', list=data, username=session.get('username'))
Exemple #10
0
 def populate_database(self):
     record = Menu.query.first()
     if not record:
         new_record = Menu(name="Pasta")
         new_record2 = Menu(name="Burger")
         new_record3 = Menu(name="Salad")
         new_record4 = Menu(name="Risotto")
         new_record5 = Menu(name="Cookie")
         db.session.add(new_record)
         db.session.add(new_record2)
         db.session.add(new_record3)
         db.session.add(new_record4)
         db.session.add(new_record5)
         db.session.commit()
Exemple #11
0
def deploy(deploy_type):
    from flask.ext.migrate import upgrade
    from app.models import BlogInfo, User, ArticleTypeSetting, Source, \
        ArticleType, Plugin, BlogView, Comment

    # upgrade database to the latest version
    upgrade()

    if deploy_type == 'product':
        # step_1:insert basic blog info
        BlogInfo.insert_blog_info()
        # step_2:insert admin account
        User.insert_admin(email='*****@*****.**',
                          username='******',
                          password='******')
        User.insert_admin(email='*****@*****.**',
                          username='******',
                          password='******')
        User.insert_admin(email='*****@*****.**',
                          username='******',
                          password='******')
        User.insert_admin(email='*****@*****.**',
                          username='******',
                          password='******')
        # step_3:insert system default setting
        ArticleTypeSetting.insert_system_setting()
        # step_4:insert default article sources
        Source.insert_sources()
        # step_5:insert default articleType
        ArticleType.insert_system_articleType()
        # step_6:insert system plugin
        Plugin.insert_system_plugin()
        # step_7:insert blog view
        BlogView.insert_view()

    # You must run `python manage.py deploy(product)` before run `python manage.py deploy(test_data)`
    if deploy_type == 'test_data':
        # step_1:insert navs
        Menu.insert_menus()
        # step_2:insert articleTypes
        ArticleType.insert_articleTypes()
        # step_3:generate random articles
        Article.generate_fake(100)
        # step_4:generate random comments
        Comment.generate_fake(300)
        # step_5:generate random replies
        Comment.generate_fake_replies(100)
        # step_4:generate random comments
        Comment.generate_fake(300)
Exemple #12
0
    def setUp(self):
        db.create_all()
        db.session.add(
            Place(name='Testname',
                  address="123 Test st.",
                  city="Englewood",
                  state="Florida",
                  zip_="34224",
                  website="http://fake.com",
                  phone="123-456-7899",
                  owner="Jeff Reiher",
                  yrs_open=1))

        db.session.add(
            Menu(name="burger",
                 course="dinner",
                 description="test description",
                 price="$1.00",
                 place_id=1))

        db.session.add(
            User(username="******",
                 email="*****@*****.**",
                 password="******",
                 avatar="picofjeff.jpg"))

        db.session.commit()
Exemple #13
0
	def get(self, id):
		menu = Menu.query.filter_by(id = id).first()
		if not menu:
			return {'message': 'Menu not found'}
		return {
		    'Menu': Menu.to_json(menu)
		}
Exemple #14
0
 def createMenuItem(self, id=1):
     with self.app.app_context():
         menu_item = MenuItem.query.get(id)
         if not menu_item:
             menu = Menu.query.get(1)
             if not menu:
                 menu = Menu(category=MenuType.BREAKFAST)
                 menu.save()
             meal_name = 'ugali'
             meal = Meal.query.filter_by(name=meal_name).first()
             if not meal:
                 meal = Meal(name=meal_name, img_path='#', cost=200)
                 meal.save()
             menu_item = MenuItem(menu_id=menu.id, meal_id=meal.id)
             menu_item.save()
         return menu_item.id
Exemple #15
0
def api(month, day, year):
    """Return past menu JSON from database."""
    start = datetime(year, month, day)
    end = start + timedelta(days=1)
    menu = Menu.objects(date_modified__gte=start,
                        date_modified__lt=end).first_or_404()
    return jsonify(menu)
Exemple #16
0
 def put(self, menu_id):
     """Update a menu item"""
     menu = Menu.find_by_id(meal_id=menu_id)
     if menu is None:
         return {
             "message":
             "The menu item with an id number %s doesn't"
             " exist" % menu_id
         }, 404
     args = self.parser.parse_args()
     name = args.get("name", "")
     description = args.get("description", "")
     price = args.get("price", "")
     if empty(name) or empty(description) or empty(price):
         return {
             "message":
             "You have to specify all"
             " details of an item"
             " such as name, price, description"
         }, 403
     if not valid_name(name):
         return {"message": "Please specify a valid name for item"}, 403
     if not valid_price(price):
         return {
             "message": "Please specify a valid price"
             " for the item"
         }, 403
     if not valid_description(description):
         return {
             "message": "Please specify a valid description "
             "for the item"
         }
     menu_item = Menu(name, description, 200)
     menu_item.id = menu.id
     updated = menu_item.update()
     if updated:
         return {
             "message": "The menu item was successfully updated",
             "menu_item": menu_item.json
         }, 200
     else:
         return {
             "message":
             "There was a problem updating the menu item"
             " maybe you provided a name already taken by"
             " another menu item"
         }, 400
Exemple #17
0
def create(auth_name, path, level):
    if Menu.query.filter(or_(Menu.auth_name == auth_name)).first():
        return ValidationErrorResult(message='Menu已存在')
    menu = Menu(level=level, auth_name=auth_name, path=path)
    db.session.add(menu)
    db.session.flush()

    return jsonify(schemas.menu_schema.dump(menu)), 201
Exemple #18
0
def post_new_menu(date_int):
    category = request.json['category']
    description = request.json['description']
    cycle = request.json['cycle']
    new_menu = Menu(date_int, category, description, cycle)
    db.session.add(new_menu)
    db.session.commit()
    menu_id = new_menu.menuid
    return str(menu_id)
Exemple #19
0
def menu_add():
    '''/admin/Menu/add'''
    #生成菜单数据
    data = Menu.mlist_to_tree()
    list = Menu.form_at_tree(data)
    list.insert(0, {"id": "0", "showName": u"顶级菜单"})

    #form
    form = AddmenuForm()
    form.fid.choices = [(int(n['id']), n['showName']) for n in list]
    if form.validate_on_submit():
        Menu.insert_menu(form.name.data, form.fid.data, form.hide.data,
                         form.url.data, form.sort.data)
        return jsonify({'code': 1, 'msg': '菜单添加成功!'})
    if form.errors:
        return jsonify({'code': 0, 'msg': '菜单添加失败!'})

    return render_template('admin/menu/add.html', form=form)
 def test_menu_item(self):
     test_name = "test"
     test_item = Menu(name=test_name)
     db.session.add(test_item)
     db.session.commit()
     response = self.app.get('/menu', follow_redirects=True)
     self.assertEqual(response.status_code, 200)
     #self.assertEqual(response.mimetype, 'application/json')
     body = response.data
     self.assertTrue('menu' in body)
Exemple #21
0
    def post(self):
        menu = request.get_json()
        m = Menu(meal_id=menu.get('meal_id'), meal_name=menu.get('meal_name'), price=menu.get('price'),
        category=menu.get('category'))

        menus.append(m)

        result = jsonify({"message": "meal added to menu"})
        result.status_code = 201
        return result
Exemple #22
0
        def post(current_user, self, meal_id):
            if not current_user.type_admin:
                response = jsonify(
                    {"message": "Not authorized to perform this function!"})
                response.status_code = 401
                return response

            meal = Meal.query.filter_by(id=meal_id).first()

            if not meal:
                response = jsonify({"message": "Meal not available"})
                response.status_code = 404
                return response

            menus = Menu(meal.m_name, meal.category, meal.price)
            menus.save()

            response = jsonify({"message": "Meal added to menu"})
            response.status_code = 200
            return response
Exemple #23
0
	def post(self):
		parser = reqparse.RequestParser()
		parser.add_argument('name', required = True, 
			help = 'This can not be blank')
		parser.add_argument('description', type = str, 
			default = "")
		data = parser.parse_args()
		new_menu = Menu(
			name = data['name'],
			description = data['description']
		)
		try:
			new_menu.add_menu_to_db()
			return {
			    'message': 'Menu {} created successfully'.format(data['name'])
			}, 201
		except:
			return {
			    'message': 'Something went wrong.'
			}, 500
Exemple #24
0
def deploy(deploy_type):
    db.create_all()
    # from flask_migrate import upgrade
    # from app.models import User, Menu
    # upgrade database to the latest version
    # upgrade()

    if deploy_type == 'product':
        # step_2:insert admin account
        User.insert_admin(email='*****@*****.**',
                          username='******',
                          password='******')
        # init admin menu
        Menu.init_menu(os.path.join(basedir, 'sql', 'menu'))
        # init admin group
        Group.init_group(os.path.join(basedir, 'sql', 'group'))
        # init admin group_access
        Group_access.init_gaccess(os.path.join(basedir, 'sql', 'group_access'))
        # init admin group_auth
        Group_auth.init_gauth(os.path.join(basedir, 'sql', 'group_auth'))
        print 'db create!'
Exemple #25
0
 def get(self, menu_id=None):
     """Get either all menu items"""
     if menu_id is None:
         meals = Menu.all()
         if not meals:
             return {
                 "message":
                 "No menu items are currently available. Check on later"
             }, 404
         return {"message": "success", "menu": meals}, 200
     if not isinstance(menu_id, str) and not isinstance(menu_id, int):
         return {
             "message": "The menu item with id %s does not exist" % menu_id
         }, 404
     meal = Menu.find_by_id(meal_id=menu_id)
     print(meal)
     if not meal:
         return {
             "message": "The menu item with id %s does not exist" % menu_id
         }, 404
     return {"message": "success", "item": meal.json}
    def test_list_menus_range_ok_response(
            self, mock_menu_controller_pagination_meta,
            mock_meal_item_repo_get,
            mock_menu_repo_get_range_paginated_options,
            mock_meal_periods_has_value, mock_auth_get_location):
        '''Test list_menus_range OK response.
        '''
        # Arrange
        with self.app.app_context():
            mock_auth_get_location.return_value = 1
            mock_meal_periods_has_value.return_value = True
            mock_menu = Menu(date=datetime.now(),
                             meal_period='',
                             location_id=1,
                             main_meal_id=1,
                             allowed_side=1,
                             allowed_protein=1,
                             side_items='1,2',
                             protein_items='1,2',
                             vendor_engagement_id=1,
                             created_at=datetime.now(),
                             updated_at=datetime.now())
            mock_meal_item = MealItem(id=1,
                                      meal_type=1,
                                      name='',
                                      image='',
                                      location_id=1,
                                      created_at=datetime.now(),
                                      updated_at=datetime.now())
            mock_menu_repo_get_range_paginated_options.return_value.items = [
                mock_menu,
            ]

            mock_meal_item_repo_get.return_value = mock_meal_item
            mock_period_start_date = '2019-01-01'
            mock_period_end_date = '2019-02-28'
            mock_menu_controller_pagination_meta.return_value = {
                'total_rows': 1,
                'total_pages': 1,
                'current_page': 1,
                'next_page': False,
                'prev_page': False
            }
            menu_controller = MenuController(self.request_context)

            # Act
            result = menu_controller.list_menus_range('lunch',
                                                      mock_period_start_date,
                                                      mock_period_end_date)

            # Assert
            assert result.status_code == 200
            assert result.get_json()['msg'] == 'OK'
Exemple #27
0
def deploy(deploy_type):
    from flask.ext.migrate import upgrade
    from app.models import BlogInfo, User, ArticleTypeSetting, Source, \
        ArticleType, Plugin, BlogView, Comment

    # upgrade database to the latest version
    upgrade()

    if deploy_type == 'product':
        # step_1:insert basic blog info
        BlogInfo.insert_blog_info()
        # step_2:insert admin account
        User.insert_admin(email='*****@*****.**',
                          username='******',
                          password='******')
        # step_3:insert system default setting
        ArticleTypeSetting.insert_system_setting()
        # step_4:insert default article sources
        Source.insert_sources()
        # step_5:insert default articleType
        ArticleType.insert_system_articleType()
        # step_6:insert system plugin
        Plugin.insert_system_plugin()
        # step_7:insert blog view
        BlogView.insert_view()

    # You must run `python manage.py deploy(product)` before run `python manage.py deploy(test_data)`
    if deploy_type == 'test_data':
        # step_1:insert navs
        Menu.insert_menus()
        # step_2:insert articleTypes
        ArticleType.insert_articleTypes()
        # step_3:generate random articles
        Article.generate_fake(100)
        # step_4:generate random comments
        Comment.generate_fake(300)
        # step_5:generate random replies
        Comment.generate_fake_replies(100)
        # step_4:generate random comments
        Comment.generate_fake(300)
Exemple #28
0
def new_menu_item(place_id):
    if request.method == "POST":
        new_menu = Menu(name=request.form["name"],
                        course=request.form["course"],
                        description=request.form["description"],
                        price=request.form["price"],
                        place_id=place_id,
                        user_id=current_user.id)
        db.session.add(new_menu)
        db.session.commit()
        flash("Just add a new menu item", "success")
        return redirect(url_for("home.show_menu", place_id=place_id))
    return render_template("new_menu.html", place_id=place_id)
Exemple #29
0
    def menu_manipulation():

        auth_header = request.headers.get('Authorization')
        if auth_header:
            access_token = auth_header.split(" ")[1]

            if access_token:
                user_id = User.decode_token(access_token)
                if isinstance(user_id, int):
                    current_user = User.query.filter_by(id=user_id).first()
                    if current_user.caterer:
                        menu = Menu.query.order_by('menu.date').all()[-1]
                        if not menu:
                            abort(404)

                        if request.method == "DELETE":
                            menu.delete()
                            return {
                                "message":
                                "Todays menu has been deleted".format(menu.id)
                            }, 200
                        elif request.method == 'PUT':
                            menu_meals = request.data.get('meal_list', '')
                            date = request.data.get('date', '')
                            menu.delete()

                            if date == '':
                                date = datetime.datetime.now()
                            if menu_meals:
                                meals = [Meal.get(id=id) for id in menu_meals]
                                menu = Menu(date=date)
                                menu.add_meal_to_menu(meals)
                                return {
                                    'message':
                                    'The menu has successfully been updated',
                                    'menu': menu_meals
                                }, 200
                            return {'message': 'Please add meals to menu'}, 202
                            menu.save()
                    else:

                        response = {
                            'message':
                            'You are not authorized to perform these functions'
                        }
                        return make_response(jsonify(response)), 401

                else:
                    # user is not legit, so the payload is an error message
                    message = user_id
                    response = {'message': message}
                    return make_response(jsonify(response)), 401

            else:
                response = {'message': 'Please input access token'}
                return make_response(jsonify(response)), 401
        else:
            return {'message': 'Please input access token'}
Exemple #30
0
    def menulist():
        if request.method == "POST":
            id = str(request.data.get('id', ''))
            if id:
                menu = Menu(id=id,
                            title=request.data.get("title"),
                            nodes=request.data.get("nodes"),
                            label=request.data.get("label"))
                menu.save()
                response = jsonify({
                    'id': menu.id,
                    'title': menu.title,
                    'nodes': menu.nodes,
                    'label': menu.label,
                    'date_created': menu.date_created,
                    'date_modified': menu.date_modified
                })
                response.status_code = 201
                return response
        else:
            # GET
            menus = Menu.get_all()
            results = []

            for menu in menus:
                obj = {
                    'count': menu.count,
                    'id': menu.id,
                    'title': menu.title,
                    'nodes': menu.nodes,
                    'label': menu.label,
                    'date_created': menu.date_created,
                    'date_modified': menu.date_modified
                }
                results.append(obj)
            response = jsonify(results)
            response.status_code = 200
            return response
Exemple #31
0
def deploy(deploy_type):
    from flask.ext.migrate import upgrade
    from app.models import BlogInfo, User, ArticleTypeSetting, Source, \
        ArticleType, Plugin, BlogView, Comment

    # upgrade database to the latest version
    upgrade()

    if deploy_type == 'product':
        # step_1:insert basic blog info
        BlogInfo.insert_blog_info()
        # step_2:insert admin account
        User.insert_admin(email='*****@*****.**', username='******', password='******', userlevel='admin')
        # step_3:insert system default setting
        ArticleTypeSetting.insert_system_setting()
        # step_4:insert default article sources
        Source.insert_sources()
        # step_5:insert default articleType
        ArticleType.insert_system_articleType()
        # step_6:insert system plugin
        Plugin.insert_system_plugin()
        # step_7:insert blog view
        BlogView.insert_view()

    # You must run `python manage.py deploy(product)` before run `python manage.py deploy(test_data)`
    if deploy_type == 'test_data':
        # step_1:insert navs
        Menu.insert_menus()
        # step_2:insert articleTypes
        ArticleType.insert_articleTypes()
        # step_3:generate random articles
        Article.generate_fake(100)
        # step_4:generate random comments
        Comment.generate_fake(300)
        # step_5:generate random replies
        Comment.generate_fake_replies(100)
        # step_4:generate random comments
        Comment.generate_fake(300)