def add_method_decorator(self): self.method_decorators = [] if self.resource.auth_required: self.method_decorators.append(roles_required(*[i for i in self.resource.roles_required])) self.method_decorators.append(roles_accepted(*[i for i in self.resource.roles_accepted])) self.method_decorators.append(set_user) self.method_decorators.append(jwt_required)
def add_method_decorator(self): self.method_decorators = [] # self.method_decorators.append(check_shop_access) self.method_decorators.append( roles_required(*[i for i in self.resource.roles_required])) self.method_decorators.append( roles_accepted(*[i for i in self.resource.roles_accepted]))
class ViewDebug(MethodView): ####################################################################### decorators = [lambda f: roles_accepted(ROLE_SUPER_ADMIN)(f)] url_rules = { 'debug': ['/_debuginfo',('GET',)], } #---------------------------------------------------------------------- def get(self): #---------------------------------------------------------------------- try: appconfigpath = getattr(current_app,'configpath','<not set>') appconfigtime = getattr(current_app,'configtime','<not set>') # collect groups of system variables sysvars = [] # collect current_app.config variables configkeys = list(current_app.config.keys()) configkeys.sort() appconfig = [] for key in configkeys: value = current_app.config[key] if True: # maybe check for something else later if key in ['SQLALCHEMY_DATABASE_URI', 'SQLALCHEMY_BINDS', 'SECRET_KEY', 'SECURITY_PASSWORD_SALT', 'GOOGLE_OAUTH_CLIENT_ID', 'GOOGLE_OAUTH_CLIENT_SECRET', 'GMAPS_API_KEY', 'GMAPS_ELEV_API_KEY', 'APP_OWNER_PW', 'RSU_KEY', 'RSU_SECRET', ]: value = '[obscured]' appconfig.append({'label':key, 'value':value}) sysvars.append(['current_app.config',appconfig]) # collect flask.session variables sessionkeys = list(session.keys()) sessionkeys.sort() sessionconfig = [] for key in sessionkeys: value = session[key] sessionconfig.append({'label':key, 'value':value}) sysvars.append(['flask.session',sessionconfig]) # commit database updates and close transaction db.session.commit() return render_template('sysinfo.jinja2',pagename='Debug', version=thisversion, configpath=appconfigpath, configtime=appconfigtime, sysvars=sysvars, # owner=owner_permission.can(), inhibityear=True,inhibitclub=True) except: # roll back database updates and close transaction db.session.rollback() raise
class AdminOrEditorView(TemplateView): blueprint = admin route = '/admin/editor' route_name = 'admin_or_editor' template_name = ' admin/index.html' decorators = [roles_accepted('admin', 'editor')] def get_context_data(self, *args, **kwargs): return {'content': 'This is the Admin/Editor Page'}
class TestException(MethodView): ####################################################################### decorators = [lambda f: roles_accepted(ROLE_SUPER_ADMIN)] url_rules = { 'testexception': ['/xcauseexception',('GET',)], } #---------------------------------------------------------------------- def get(self): #---------------------------------------------------------------------- try: raise testException except: # roll back database updates and close transaction db.session.rollback() raise
class StockStatResource(Resource): method_decorators = [roles_accepted('admin', 'owner', 'staff'), auth_token_required] model = Stock def get(self): shops = request.args.getlist('__retail_shop_id__in') for shop in shops: if not current_user.has_shop_access(shop): return make_response(jsonify({'message': 'Access Forbidden'}), 403) if len(shops) == 1: shops = shops[0].split(',') from_date = datetime.strptime(request.args['__created_on__gte'], '%Y-%m-%dT%H:%M:%S.%fZ').date() to_date = datetime.strptime(request.args['__created_on__lte'], '%Y-%m-%dT%H:%M:%S.%fZ').date() days = (to_date - from_date).days collection_type = 'day' if days > 28: collection_type = 'week' if days > 360: collection_type = 'month' stock_metrics = Stock.query \ .with_entities(cast(func.coalesce(func.Sum(self.model.purchase_amount * self.model.units_purchased), 0), Integer), cast(func.coalesce(func.Sum(self.model.selling_amount * self.model.units_sold), 0), Integer), cast(func.coalesce( func.Sum((self.model.units_purchased - self.model.units_sold) * self.model.purchase_amount) .filter(self.model.expired == True), 0), Integer), func.cast(func.date_trunc(collection_type, func.cast(self.model.created_on, Date)), Text) .label('dateWeek')) \ .filter(self.model.created_on.between(from_date, to_date), self.model.retail_shop_id.in_(shops)).order_by('dateWeek').group_by('dateWeek').limit(100).all() distributor_metrics = DistributorBill.query \ .with_entities(cast(func.coalesce(func.Sum(DistributorBill.bill_amount), 0), Integer), DistributorBill.distributor_name, ) \ .filter(DistributorBill.created_on.between(from_date, to_date), DistributorBill.retail_shop_id.in_(shops)) \ .group_by(DistributorBill.distributor_id) \ .limit(100).all() return make_response(jsonify(dict(stock_metrics=stock_metrics, distributor_metrics=distributor_metrics)), 200)
def admin_or_superuser(*args, **kwargs): # pylint: disable=unused-argument if roles_accepted('admin', 'superuser')(lambda: None)(): raise ProcessingException(status=403, detail='Forbidden')
class CommonResource(Resource): method_decorators = [roles_accepted('admin', 'counsellor', 'student'), auth_token_required]
class StudentResource(Resource): method_decorators = [roles_accepted('admin', 'student'), auth_token_required]
class OrderStatResource(Resource): method_decorators = [ roles_accepted('admin', 'owner', 'staff'), auth_token_required ] model = Order def get(self): shops = request.args.getlist('__retail_shop_id__in') for shop in shops: if not current_user.has_shop_access(shop): return make_response(jsonify({'message': 'Access Forbidden'}), 403) if len(shops) == 1: shops = shops[0].split(',') from_date = datetime.strptime(request.args['__created_on__gte'], '%Y-%m-%dT%H:%M:%S.%fZ').date() to_date = datetime.strptime(request.args['__created_on__lte'], '%Y-%m-%dT%H:%M:%S.%fZ').date() days = (to_date - from_date).days collection_type = 'day' if days > 28: collection_type = 'week' if days > 360: collection_type = 'month' orders = self.model.query.join(Item, and_(Item.order_id == self.model.id)) \ .filter(self.model.retail_shop_id.in_(shops), self.model.created_on.between(from_date, to_date)) total_orders, total_sales, total_items, total_quantity, total_due = \ orders.with_entities(func.Count(func.Distinct(self.model.id)), func.sum(self.model.total), func.Count(func.Distinct(Item.product_id)), func.sum(Item.quantity), func.Sum(self.model.amount_due)).all()[0] orders = self.model.query\ .with_entities(func.count(func.Distinct(self.model.id)), func.sum(self.model.total), func.avg(self.model.total), func.cast(func.date_trunc(collection_type, func.cast(self.model.created_on, Date)), Text) .label('dateWeek')) \ .filter(self.model.created_on.between(from_date, to_date), self.model.retail_shop_id.in_(shops)) \ .group_by('dateWeek').order_by('dateWeek').all() items = Item.query.join(self.model, and_(self.model.id == Item.order_id)) \ .filter(self.model.retail_shop_id.in_(shops)) max_sold_items = items.join(Product, and_(Product.id == Item.product_id)) \ .with_entities(func.Sum(Item.quantity), Product.name, ) \ .filter(self.model.created_on.between(from_date, to_date)) \ .group_by(Item.product_id, Product.name).order_by(-func.Sum(Item.quantity)).limit(10).all() max_profitable_items = items.join(Product, and_(Product.id == Item.product_id)) \ .join(Stock, and_(Stock.id == Item.stock_id)) \ .with_entities(func.Sum((Item.unit_price - Stock.purchase_amount) * Item.quantity), Product.name, ) \ .filter(self.model.created_on.between(from_date, to_date)) \ .group_by(Item.product_id, Product.name) \ .order_by(-func.Sum((Item.unit_price - Stock.purchase_amount) * Item.quantity)) \ .limit(10).all() return make_response( jsonify( dict(total_orders=total_orders, total_sales=total_sales, total_quantity=total_quantity, max_sold_items=max_sold_items, max_profitable_items=max_profitable_items, total_items=str(total_items), orders=orders)), 200)
class CustomerStatResource(Resource): method_decorators = [ roles_accepted('admin', 'owner', 'staff'), auth_token_required ] model = Customer def get(self): shops = request.args.getlist('__retail_shop_id__in') for shop in shops: if not current_user.has_shop_access(shop): return make_response(jsonify({'message': 'Access Forbidden'}), 403) brand_id = request.args.get('__retail_brand_id__equal') if len(shops) == 1: shops = shops[0].split(',') from_date = datetime.strptime(request.args['__created_on__gte'], '%Y-%m-%dT%H:%M:%S.%fZ').date() to_date = datetime.strptime(request.args['__created_on__lte'], '%Y-%m-%dT%H:%M:%S.%fZ').date() days = (to_date - from_date).days collection_type = 'day' if days > 56: collection_type = 'week' if days > 360: collection_type = 'month' new_customers = self.model.query.join(Order, and_(Order.customer_id == self.model.id)) \ .with_entities(func.Count(func.Distinct(Order.customer_id)), func.Sum(Order.total), func.avg(Order.total), func.cast(func.date_trunc(collection_type, func.cast(self.model.created_on, Date)), Text) .label('dateWeek') ) \ .filter(and_(self.model.created_on.between(from_date, to_date), Order.created_on.between(from_date, to_date), Order.retail_shop_id.in_(shops))).group_by('dateWeek').order_by('dateWeek')\ .having(func.Count(func.Distinct(Order.id)) > 0).all() return_customers = self.model.query.join(Order, and_(Order.customer_id == self.model.id)) \ .with_entities(func.Count(func.Distinct(Order.customer_id)), func.Sum(Order.total), func.avg(Order.total), func.cast(func.date_trunc(collection_type, func.cast(self.model.created_on, Date)), Text) .label('dateWeek') ) \ .filter(and_(self.model.created_on.between(from_date, to_date), Order.created_on.between(from_date, to_date))) \ .having(func.Count(func.Distinct(Order.id)) > 1).group_by('dateWeek').order_by('dateWeek').all() old_customers = Order.query.join(Customer, and_(Customer.id == Order.customer_id)) \ .with_entities(func.Count(func.Distinct(Order.customer_id)), func.Sum(Order.total), func.avg(Order.total), func.cast(func.date_trunc(collection_type, func.cast(Order.created_on, Date)), Text) .label('dateWeek') ) \ .filter(and_(Customer.created_on <= from_date, Order.created_on.between(from_date, to_date), Order.retail_shop_id.in_(shops), Customer.retail_brand_id == brand_id))\ .group_by('dateWeek').order_by('dateWeek') \ .having(func.Count(func.Distinct(Order.id)) > 0).all() total_due = self.model.query.outerjoin(Order, and_(Order.customer_id == self.model.id)) \ .outerjoin(CustomerTransaction, and_(CustomerTransaction.customer_id == self.model.id)) \ .with_entities(func.coalesce(cast(func.Sum(Order.total), Float), 0.0) - func.coalesce(cast(func.Sum(Order.amount_paid), Float), 0.0) - func.coalesce(cast(func.Sum(CustomerTransaction.amount), Float), 0.0)) \ .filter(self.model.retail_brand_id == brand_id).scalar() top_customers = self.model.query.outerjoin(Order, and_(Order.customer_id == self.model.id)) \ .with_entities(func.Count(func.Distinct(Order.id)), self.model.name) \ .filter(self.model.retail_brand_id == brand_id, Order.created_on.between(from_date, to_date), Order.retail_shop_id.in_(shops)).group_by(Order.customer_id, self.model.name) \ .order_by(-func.Count(func.Distinct(Order.id))).limit(10).all() top_billed_customers = self.model.query.outerjoin(Order, and_(Order.customer_id == self.model.id)) \ .with_entities(func.Sum(Order.total), self.model.name) \ .filter(self.model.retail_brand_id == brand_id, Order.created_on.between(from_date, to_date), Order.retail_shop_id.in_(shops)).group_by(Order.customer_id, self.model.name) \ .order_by(-func.Sum(Order.total)).limit(10).all() return make_response( jsonify( dict(new_customers=new_customers, return_customers=return_customers, old_customers=old_customers, top_billed_customers=top_billed_customers, total_due=total_due, top_customers=top_customers)), 200)
class CommonResource(Resource): method_decorators = [roles_accepted('admin', 'user', 'guest'), auth_token_required]