def add(self): h.requirerights("admin") users = meta.Session.query(model.Person).all() c.users = [] for i in users: c.users.append([i.id, h.name(i)]) return render ("/divisions/add.html")
def edit(self, id): c.order = h.checkorder(id) # Теперь - проверка прав доступа (админ либо ответственный подразделения, создавшего заявку) h.requirelogin() if not ( h.have_role("admin") or h.have_role("operator") or ( session.has_key("division") and (h.have_role("creator") and c.order.cust_id == session["division"]) or (h.have_role("responsible") and c.order.perf_id == session["division"]) ) ): abort(403) work = meta.Session.query(model.Work).order_by(model.Work.id).all() c.work = [] for i in work: c.work.append([i.id, i.title]) category = ( meta.Session.query(model.Category) .filter(model.Category.upcat_id == c.order.upper_category.id) .order_by(model.Category.id) .all() ) c.category = [] for i in category: c.category.append([i.id, i.title]) upcategory = ( meta.Session.query(model.UpperCategory).filter_by(deleted=False).order_by(model.UpperCategory.id).all() ) c.upcategory = [[None, u" -- выберите надкатегорию -- "]] for i in upcategory: c.upcategory.append([i.id, i.title]) return render("/orders/edit.html")
def getinfo(self, id=None): if id is None: return "" c.order = meta.Session.query(model.Order).get(int(id)) if c.order is None: return "" return render("/orders/info.html")
def index(self): qorder = meta.Session.query(model.Order).filter_by(deleted=False) # Filter old orders (more than 1 year old) max_age = request.params.get('max_age_in_days', '365') if len(max_age) and max_age != 'unlimited': qorder = qorder.filter("age(orders.created) < interval ':age days'").params(age=int(max_age)) freeorders = qorder.filter_by(status_id=1) # .limit(10) # if (session.get('preferences') or dict()).get('upcat') is not None: c.upcat = meta.Session.query(model.UpperCategory).filter_by(url_text=session['preferences']['upcat']).one() freeorders = freeorders.filter_by(upcat_id=c.upcat.id) c.numfree = freeorders.count() c.freeorders = freeorders.order_by(model.sql.desc(model.Order.created))[:10] if session.has_key('division') and h.have_role('performer'): #session.has_key('performer') and session['performer']: # Заявки, выполняемые моим подразделением c.mydivorders = qorder.filter("status_id<>:value and perf_id=:perf").params(value=4, perf=session['division']).order_by(model.sql.desc(model.Order.created))[:10] # Заявки, выполняемые мной myperf = qorder.filter(model.sql.not_(model.Order.status_id.in_([1, 3, 4, 5]))) myperf = myperf.filter(model.Order.performers.any(id=session['id'])) c.myperforming = myperf.order_by(model.Order.created)[:10] # Жалобы! c.complaints = qorder.filter("status_id=:value and perf_id=:perf").params(value=6, perf=session['division']).order_by(model.Order.created).all() if session.has_key('division') and session.has_key('creator') and session['creator']: c.myownorders = qorder.filter("cust_id=:div").params(div=session['division']).order_by(model.sql.desc(model.Order.created))[:10] orderstoapprove = qorder.filter("status_id=:value and cust_id=:perf").params(value=3, perf=session['division']) c.orderstoapprove = orderstoapprove.order_by(model.Order.created)[:10] c.numtoapprove = orderstoapprove.count() # Немножко статистики на главную c.ordercount = meta.Session.query(model.Order).filter_by(deleted=False).count() statuses = meta.Session.query(model.Status).filter(model.Status.redirects==model.Status.id)\ .order_by(model.Status.id).all() c.ordercountbystatus = [(unicode(status.title), status.ordercount) for status in statuses] return render('/main.html')
def add(self): h.requirerights("admin") divisions = meta.Session.query(model.Division).filter_by(deleted=False).order_by(model.Division.title).all() c.divisions = [[None, u"-- выберите подразделение --"]] for i in divisions: c.divisions.append([i.id, i.title]) return render ("/users/add.html")
def list(self, show=None): q = meta.Session.query(model.Person).filter_by(deleted=False).order_by(model.Person.login).order_by(model.Person.surname) if show is None: users = q elif show == "customers": users = q.filter_by(creator=True) elif show == "performers": users = q.filter_by(performer=True) elif show == "appointers": users = q.filter_by(appointer=True) elif show == "responsibles": users = q.filter_by(responsible=True) elif show == "chiefs": users = q.filter_by(chief=True) elif show == "administrators": users = q.filter_by(admin=True) elif show == "operators": users = q.filter_by(operator=True) else: users = q # Ищем? c.search = request.params.get('search', '') if len(c.search): search = "%"+unicode(c.search).lower()+"%" users = users.filter(sqlalchemy.or_(model.Person.login.ilike(search), model.Person.surname.ilike(search), model.Person.name.ilike(search), model.Person.patronymic.ilike(search))) # Разбивка на страницы c.paginator = h.paginate.Page( users, page=int(request.params.get('page', 1)), items_per_page = 15, ) c.usercount = q.count() return render ("/users/list.html")
def edit(self, id=None): user = h.checkuser(id) h.requirerights(user_is=id) qdivs = meta.Session.query(model.Division).filter_by(deleted=False) divisions = qdivs.all() c.divisions = [[None, u"-- нет --"]] for i in divisions: c.divisions.append([i.id, i.title]) values = { 'login': user.login, 'name': user.name, 'surname': user.surname, 'patronymic': user.patronymic, 'email': user.email, 'phone': user.phone, 'creator': user.creator, 'performer': user.performer, 'appointer': user.appointer, 'responsible': user.responsible, 'chief': user.chief, 'admin': user.admin, 'operator': user.operator, 'div_id': user.div_id } c.curdiv = [user.div_id] return htmlfill.render(render("/users/edit.html"), values)
def document (self): """Render the error document""" resp = request.environ.get('pylons.original_response') code = cgi.escape(request.GET.get('code', '')) content = cgi.escape(request.GET.get('message', '')) if resp: content = literal(resp.status) code = code or cgi.escape(str(resp.status_int)) if not code: raise Exception('No status code was found') if code in ["401", "403", "404", "410", "500"]: return render ("/error/"+code+".html") else: c.code = code c.message = content return render('/error/document.html')
def choose (self, id=None): c.order = h.checkorder(id) # Теперь - проверка прав доступа (ответственный подразделения, выполняющего заявки) if not (h.have_role('admin') or ((h.have_role("appointer")) and session.has_key('division') and c.order.perf_id == session['division'])): abort(403) actionquery = meta.Session.query(model.Action) #if actionquery.filter_by(div_id=c.order.perf_id).all() is None: # lastaction = None #else: # lastaction = actionquery.filter_by(div_id=c.order.perf_id).order_by(model.sql.desc(model.Action.created)).first() lastaction = actionquery.filter_by(order_id=id).filter_by(div_id=c.order.perf_id).filter(model.Action.status_id != 16).order_by(model.sql.desc(model.Action.created)).first() c.actions = actionquery.filter_by(order_id=id).order_by(model.Action.created).all() # Статусы statuses = meta.Session.query(model.Status).order_by(model.Status.gui_priority) if h.have_role('admin'): excluded_statuses = [1, 4, 6, 11, 12, 14] else: excluded_statuses = [1, 2, 4, 6, 11, 12, 14] c.statuses = [["", u" -- выберите -- "]] + [[status.id, status.title] for status in statuses if status.id not in excluded_statuses] # Люди-исполнители performers = meta.Session.query(model.Person).filter_by(deleted=False).filter_by(performer=True).order_by(model.Person.surname, model.Person.name, model.Person.name) if h.have_role('admin') and lastaction is not None: performers = performers.filter_by(div_id=lastaction.div_id) else: performers = performers.filter_by(div_id=session['division']) c.performers = [[user.id, h.name(user)] for user in performers] if lastaction is not None: c.curperfs = [x.id for x in c.order.performers] c.curdiv = lastaction.div_id if h.have_role("admin"): divlist = [x.div_id for x in meta.Session.query(model.Person.div_id).filter_by(performer=True).all()] c.divisions = [[x.id, x.title] for x in meta.Session.query(model.Division).filter_by(deleted=False).filter(model.Division.id.in_(divlist)).all()] return render("/actions/choose.html")
def list(self, show=None, sort="date", **kwargs): qorder = meta.Session.query(model.Order, case([(and_(model.Order.urgent==True, model.Order.doneAt==None), True)], else_=False).label('really_urgent')) qorder = qorder.order_by("really_urgent DESC", model.sql.desc(model.Order.created)) # Filter old orders (more than 1 year old) max_age = request.params.get('max_age_in_days', '365') if len(max_age) and max_age != 'unlimited': qorder = qorder.filter("age(orders.created) < interval ':age days'").params(age=int(max_age)) # Main filtrations c.upcat = kwargs.get('upcat', None) c.mworkcur = kwargs.get('work', None) or request.params.get('work','any') c.mcatcur = kwargs.get('cat', None) or request.params.get('cat','any') c.mstatcur = kwargs.get('status', None) or request.params.get('status','any') if c.upcat not in ['any', None]: upcat = meta.Session.query(model.UpperCategory).filter_by(url_text=c.upcat).first() if upcat is not None: qorder = qorder.filter_by(upcat_id=upcat.id) if c.mcatcur not in ['any', None]: cat = meta.Session.query(model.Category).filter_by(url_text=c.mcatcur).first() if cat is not None: qorder = qorder.filter_by(cat_id=cat.id) if c.mworkcur not in ['any', None]: work = meta.Session.query(model.Work).filter_by(url_text=c.mworkcur).first() if work is not None: qorder = qorder.filter_by(work_id=work.id) if c.mstatcur not in ['any', 'performed', 'not_performed', None]: status = meta.Session.query(model.Status).filter(model.Status.redirects==model.Status.id).filter_by(id=c.mstatcur).first() if status is not None: qorder = qorder.filter_by(status_id=status.id) elif c.mstatcur == 'not_performed': qorder = qorder.filter(model.sql.not_(model.Order.status_id.in_([3, 4, 15]))) elif c.mstatcur == 'performed': qorder = qorder.filter(model.Order.status_id.in_([3, 4])) qorder = qorder.filter_by(deleted=bool(request.urlvars.get('deleted', False))) # Разбивка на страницы c.paginator = h.paginate.Page( qorder, page = (kwargs.get('page') or 1), #int(request.params.get('page', 1)), items_per_page = (session.get('preferences') or {}).get('ordersinpage', 15), ) c.ordercount = qorder.count() mstat = meta.Session.query(model.Status)\ .filter(model.Status.redirects==model.Status.id).filter_by(deleted=False)\ .order_by(model.Status.id).all() c.mstat = [ ([('any', u' -- Все -- ')], u'Все заявки'), ([('not_performed', u'Не выполненные'), ('performed', u'Выполненные')], u'По степени завершённости'), ([[x.id, x.title] for x in mstat], u'В определённом состоянии') ] mcat = meta.Session.query(model.Category).filter_by(deleted=False).order_by(model.Category.id) if kwargs.get('upcat') not in ['any', None] and upcat is not None: mcat = mcat.filter(or_(model.Category.upcat_id==upcat.id, model.Category.upcat_id==None)) c.mcat = [['any', u' -- Все -- ']] + [[x.url_text, x.title] for x in mcat.all()] mwork = meta.Session.query(model.Work).filter_by(deleted=False).order_by(model.Work.id).all() c.mwork = [['any', u' -- Все -- ']] + [[x.url_text, x.title] for x in mwork] session['last_orders_list_url'] = url_for() return render ("/orders/list.html")
def view(self, id=None): c.division = h.checkdiv(id) c.division.responsible = meta.Session.query(model.Person).filter_by(div_id=id).filter_by(responsible=True).all() c.division.chief = meta.Session.query(model.Person).filter_by(div_id=id).filter_by(chief=True).all() c.lastorders = meta.Session.query(model.Order).filter_by(cust_id=id).\ order_by(model.sql.desc(model.Order.created))[:10] c.personnel = meta.Session.query(model.Person).filter_by(div_id=id).\ filter_by(deleted=False).order_by(model.Person.surname).all() # Учёт количества сделанных заявок thismonday = datetime.combine(date.today(), time(0, 0)) - timedelta(date.today().weekday()) last = meta.Session.query(model.Person.id, func.count(model.Order.id), func.sum(model.OrderPerformer.workload)).\ join(model.Person.order_performs, model.OrderPerformer.order).\ filter(model.Person.div_id==id).filter(model.OrderPerformer.current==True).group_by(model.Person.id) last30d = last.filter(model.Order.doneAt > datetime.now()-timedelta(30)).all() thisweek = last.filter(model.Order.doneAt >= thismonday).all() prevweek = last.filter(model.Order.doneAt < thismonday).filter(model.Order.doneAt >= thismonday-timedelta(7)).all() last1d = last.filter(model.Order.doneAt > datetime.combine(date.today(), time(0, 0))).all() # Учёт по дням количества сделанных заявок dates = meta.Session.execute dates_q = """ SELECT o."doneAt"::date AS done_date FROM orders o WHERE o."doneAt" BETWEEN (now() - '1 month'::interval)::timestamp AND now() GROUP BY done_date ORDER BY done_date; """ order_count_q = """ SELECT o."doneAt"::date AS done_date, (o."doneAt"::date - (SELECT a.created::date FROM actions a WHERE a.order_id = o.id AND a.status_id = 2 ORDER BY a.created DESC LIMIT 1) + 1) AS days, op.workload FROM people p JOIN orderperformers op ON p.id = op.person_id JOIN orders o ON op.order_id = o.id WHERE p.id = %d AND o.status_id IN (3, 4) AND o."doneAt" BETWEEN (now() - '1 month'::interval)::timestamp AND now() ORDER BY done_date; """ c.dates = [row[0] for row in meta.Session.execute(dates_q)] c.graph_data = [[0 for d in c.dates] for user in c.personnel] # Empty graph data for user_idx, user in enumerate(c.personnel): for row in meta.Session.execute(order_count_q % user.id): stop_idx = c.dates.index(row[0]) start_idx = stop_idx - row[1] - 2 if start_idx < 0: start_idx = 0 for idx in range(start_idx, stop_idx): c.graph_data[user_idx][idx] += float(row[2])/(row[1]+2) # Подготовка к отображению шаблона c.lastmonth = dict([[record[0], record[1:]] for record in last30d]) c.prevweek = dict([[record[0], record[1:]] for record in prevweek]) c.thisweek = dict([[record[0], record[1:]] for record in thisweek]) c.today = dict([[record[0], record[1:]] for record in last1d]) c.total = dict([[record[0], record[1:]] for record in last.all()]) return render("/divisions/view.html")
def orders (self, id=None): c.person = h.checkuser(id) c.statuses = [[2, u"Принятые"], [3, u"Выполненные"]] c.status = request.params.get("status", 3) c.start_date = datetime.strptime(request.params.get("start_date", datetime.now().date().isoformat()), "%Y-%m-%d") c.stop_date = datetime.strptime(request.params.get("stop_date", datetime.now().date().isoformat()), "%Y-%m-%d") c.orders = meta.Session.query(model.Order).join(model.Order.actions).join(model.Action.action_performers)\ .filter(and_(model.Action.status_id==c.status, model.Action.action_performers.any(person_id=id)))\ .filter(model.Action.created>=c.start_date).filter(model.Action.created<=c.stop_date+timedelta(1)).all() return render ("/users/orders.html")
def takerequest (self, id=None): c.order = h.checkorder(id) # Теперь - проверка прав доступа if not (h.have_role('appointer') and c.order.status_id==1): abort(401) c.division = meta.Session.query(model.Division).get(int(session['division'])) performers = meta.Session.query(model.Person).filter_by(deleted=False)\ .filter_by(div_id=session['division']).filter_by(performer=True).order_by(model.Person.surname).all() c.performers = [] for user in performers: c.performers.append([user.id, h.name(user)]) return render ("/orders/take.html")
def switch (self, id=None): h.requirerights("operator") userdivs =meta.Session.query(model.Person, model.Division).join(model.Division)\ .filter(and_(model.Person.deleted==False, model.Person.creator==True))\ .filter(or_(model.Person.chief==True, model.Person.responsible==True))\ .order_by(model.Division.title).order_by(model.Person.surname).all() #users = meta.Session.query(model.Person)\ # .filter_by(deleted=False).filter_by(creator=True).order_by(model.Person.login).order_by(model.Person.surname).all() #users.sort(key=lambda x:(x.division.title, x.surname)); #c.users = [[unicode(x.id), x.division.title + h.literal(" — ") + (h.name(x))] for x in users] c.users = [[unicode(x[0].id), x[1].title + h.literal(" — ") + (h.name(x[0]))] for x in userdivs] c.selected = id return render ("/users/switch.html")
def list(self): qdiv = meta.Session.query(model.Division).filter_by(deleted=False).order_by(model.Division.title) # Производим поиск подразделений? c.search = request.params.get('search', '') if len(c.search): search = "%"+unicode(c.search).lower()+"%" qdiv = qdiv.filter(sqlalchemy.or_(model.Division.title.ilike(search), model.Division.description.ilike(search), model.Division.address.ilike(search))) # Показ c.paginator = h.paginate.Page( qdiv, page=int(request.params.get('page', 1)), items_per_page = 15, ) c.divcount = qdiv.count() return render ("/divisions/list.html")
def listownorders (self, type="performing", **kwargs): qorder = meta.Session.query(model.Order, case([(and_(model.Order.urgent==True, model.Order.doneAt==None), True)], else_=False).label('really_urgent')) qorder = qorder.order_by("really_urgent DESC", model.sql.desc(model.Order.created)) qorder = qorder.filter(model.Order.deleted==False) if type == "performing": qorder = qorder.filter(model.sql.not_(model.Order.status_id.in_([1, 3, 4, 5, 15]))) qorder = qorder.filter(model.Order.performers.any(id=session['id'])) # Разбивка на страницы c.paginator = h.paginate.Page( qorder, page = (kwargs.get('page') or 1), #int(request.params.get('page', 1)), items_per_page = (session.get('preferences') or {}).get('ordersinpage', 15), ) c.ordercount = qorder.count() session['last_orders_list_url'] = url_for() return render ("/orders/list.html")
def add(self): '''Показ формы для создания заявки''' h.requirerights('creator') c.order = model.Order() work = meta.Session.query(model.Work).filter_by(deleted=False).order_by(model.Work.id).all() c.work = [[None, u" -- выберите вид работ -- "]] for i in work: c.work.append([i.id, i.title]) category = meta.Session.query(model.Category).filter_by(deleted=False).order_by(model.Category.id).all() c.category = [[None, u" -- выберите категорию -- "]] for i in category: c.category.append([i.id, i.title]) upcategory = meta.Session.query(model.UpperCategory).filter_by(deleted=False).order_by(model.UpperCategory.id).all() c.upcategory = [[None, u" -- выберите надкатегорию -- "]] for i in upcategory: c.upcategory.append([i.id, i.title]) c.curcat = c.curwork = c.upcat = [] return render ("/orders/add.html")
def thank (self, id=None): # Если номер заявки не указан, то позволим выбрать. if id is not None: c.order = h.checkorder(id) if not session.has_key('division'): abort(401) elif c.order.cust_id != session['division']: abort(403) c.selectedorder = c.order.id else: c.selectedorder = None if not h.have_role('creator'): abort(403) orders = meta.Session.query(model.Order).filter("status_id<>:value and cust_id=:customer").params(value=4, customer=session['division']).all() c.orders =[['', u'-- выберите заявку, выполнением которой вы остались довольны --']] for order in orders: if h.can_complain(order): if len(order.title) > 32: order.title = order.title[:32] + u"…" str = unicode(order.id) + ". [" + order.work.title + h.literal(" — ") + order.category.title + "]: " + order.title c.orders.append([order.id, str]) return render("/actions/thank.html")
def edit(self, id=None): h.requirelogin() div = h.checkdiv(id) if not (h.have_role('admin') or (session.get('division')==div.id and (session.get('chief') or session.get('responsible')))): abort(403) users = meta.Session.query(model.Person).all() c.users = [] for i in users: c.users.append([i.id, h.name(i)]) #qmembers = meta.Session.query(model.Person).filter_by(division=div.id).all() members = [] for i in div.people: members.append(i.id) values = { 'title': div.title, 'address': div.address, 'description': div.description, 'email': div.email, 'phone': div.phone, 'users': members, } return htmlfill.render(render("/divisions/edit.html"), values)
def index(self): return render(u'/admin/index.html')
def preferences (self): c.user = h.checkuser(session['id']) c.upcats = [[None, u" -- все -- "]] + [[x.url_text, x.title] for x in meta.Session.query(model.UpperCategory).filter_by(deleted=False).all()] return render ("/users/preferences.html")
def view(self, id=None): c.division = h.checkdiv(id) c.division.responsible = meta.Session.query(model.Person).filter_by(div_id=id).filter_by(responsible=True).all() c.division.chief = meta.Session.query(model.Person).filter_by(div_id=id).filter_by(chief=True).all() c.lastorders = meta.Session.query(model.Order).filter_by(cust_id=id).\ order_by(model.sql.desc(model.Order.created))[:10] c.personnel = meta.Session.query(model.Person).filter_by(div_id=id).\ filter_by(deleted=False).order_by(model.Person.surname).all() # Учёт количества сделанных заявок thismonday = datetime.combine(date.today(), time(0, 0)) - timedelta(date.today().weekday()) last = meta.Session.query(model.Person.id, func.count(model.Order.id), func.sum(model.OrderPerformer.workload)).\ join(model.Person.order_performs, model.OrderPerformer.order).\ filter(model.Person.div_id==id).filter(model.OrderPerformer.current==True).group_by(model.Person.id) last30d = last.filter(model.Order.doneAt > datetime.now()-timedelta(30)).all() thisweek = last.filter(model.Order.doneAt >= thismonday).all() prevweek = last.filter(model.Order.doneAt < thismonday).filter(model.Order.doneAt >= thismonday-timedelta(7)).all() last1d = last.filter(model.Order.doneAt > datetime.combine(date.today(), time(0, 0))).all() # Реактивность и тормознутость reacts_q = """ SELECT people.id, actions.created, orders.created FROM people JOIN actionperformers ap ON people.id = ap.person_id JOIN actions ON ap.action_id = actions.id JOIN orders ON actions.order_id = orders.id WHERE people.id IN (SELECT id FROM people WHERE div_id = %d) AND actions.created BETWEEN (now() - '1 month'::interval)::timestamp AND now() AND actions.status_id = 2 ORDER BY people.id """ reacts = meta.Session.execute(reacts_q % c.division.id) count_of_actions = 0 temp = 0 first = True reaction = [] thour = 0 tminute = 0 tsecond = 0 lastid = None for row in reacts: if first: lastid = row[0] first = False if row[0] != lastid: if count_of_actions != 0: temp = float(temp)/count_of_actions else: temp = 0 thour = int(temp) tminute = int((temp-thour)*60) tsecond = int(((temp-thour)*60-tminute)*60) reaction.append([lastid, '%dh %dm %ds'%(thour,tminute,tsecond)]) temp = 0 lastid = row[0] count_of_actions = 0 fromdate = row[2] todate = row[1] daygenerator = (fromdate.date() + timedelta(x) for x in range((todate.date() - fromdate.date()).days)) res_d = sum(1 for day in daygenerator if day.weekday() < 5) fromtime = fromdate.time() totime = todate.time() res_m = (totime.minute - fromtime.minute) res_s = (totime.second - fromtime.second) if res_d == 0: res_h = (totime.hour - fromtime.hour) if fromtime.hour < 12 and totime.hour > 13: res_h -= 1 else: res_d -= 1 res_h = 9-fromtime.hour+totime.hour if fromtime.hour < 12: res_h -= 1 if totime.hour > 13: res_h -= 1 if res_s < 0: res_m -= 1 res_s = 60 + res_s if res_m < 0: res_h -= 1 res_m = 60 + res_m temp += 8*res_d + res_h + float(res_m)/60 + float(res_s)/3600 count_of_actions +=1 if count_of_actions != 0: temp = float(temp)/count_of_actions else: temp = 0 thour = int(temp) tminute = int((temp-thour)*60) tsecond = int(((temp-thour)*60-tminute)*60) reaction.append([lastid, '%dh %dm %ds'%(thour,tminute,tsecond)]) # Учёт по дням количества сделанных заявок dates = meta.Session.execute dates_q = """ SELECT o."doneAt"::date AS done_date FROM orders o WHERE o."doneAt" BETWEEN (now() - '1 month'::interval)::timestamp AND now() GROUP BY done_date ORDER BY done_date; """ order_count_q = """ SELECT o."doneAt"::date AS done_date, (o."doneAt"::date - (SELECT a.created::date FROM actions a WHERE a.order_id = o.id AND a.status_id = 2 ORDER BY a.created DESC LIMIT 1) + 1) AS days, op.workload FROM people p JOIN orderperformers op ON p.id = op.person_id JOIN orders o ON op.order_id = o.id WHERE p.id = %d AND o.status_id IN (3, 4) AND o."doneAt" BETWEEN (now() - '1 month'::interval)::timestamp AND now() ORDER BY done_date; """ c.dates = [row[0] for row in meta.Session.execute(dates_q)] c.graph_data = [[0 for d in c.dates] for user in c.personnel] # Empty graph data for user_idx, user in enumerate(c.personnel): for row in meta.Session.execute(order_count_q % user.id): stop_idx = c.dates.index(row[0]) start_idx = stop_idx - row[1] - 2 if start_idx < 0: start_idx = 0 for idx in range(start_idx, stop_idx): c.graph_data[user_idx][idx] += float(row[2])/(row[1]+2) # Подготовка к отображению шаблона c.lastmonth = dict([[record[0], record[1:]] for record in last30d]) c.prevweek = dict([[record[0], record[1:]] for record in prevweek]) c.thisweek = dict([[record[0], record[1:]] for record in thisweek]) c.today = dict([[record[0], record[1:]] for record in last1d]) c.total = dict([[record[0], record[1:]] for record in last.all()]) c.reacts = dict([[record[0], record[1]] for record in reaction]) return render("/divisions/view.html")
def view(self, id=None): c.person = h.checkuser(id) c.today = date.today() return render("/users/view.html")
def login(self): return render ("/users/login.html")
def view(self, id): c.order = h.checkorder(id) # c.order.title = c.order.title.replace(u"\n", h.literal(u"<br />")); return render("/orders/view.html")
def list(self, show=None, sort="date", **kwargs): qorder = meta.Session.query( model.Order, case([(and_(model.Order.urgent == True, model.Order.doneAt == None), True)], else_=False).label( "really_urgent" ), ) if type(kwargs.get("searchvalue", None) or request.params.get("searchvalue")).__name__ == "unicode": qorder = qorder.filter(model.Order.title.ilike("%%%s%%" % request.params["searchvalue"])) else: # Filter old orders (more than 1 year old) max_age = request.params.get("max_age_in_days", "365") if len(max_age) and max_age != "unlimited": qorder = qorder.filter("age(orders.created) < interval ':age days'").params(age=int(max_age)) qorder = qorder.order_by("really_urgent DESC", model.sql.desc(model.Order.created)) # Main filtrations c.upcat = kwargs.get("upcat", None) c.mworkcur = kwargs.get("work", None) or request.params.get("work", "any") c.mcatcur = kwargs.get("cat", None) or request.params.get("cat", "any") c.mstatcur = kwargs.get("status", None) or request.params.get("status", "any") if c.upcat not in ["any", None]: upcat = meta.Session.query(model.UpperCategory).filter_by(url_text=c.upcat).first() if upcat is not None: qorder = qorder.filter_by(upcat_id=upcat.id) if c.mcatcur not in ["any", None]: cat = meta.Session.query(model.Category).filter_by(url_text=c.mcatcur).first() if cat is not None: qorder = qorder.filter_by(cat_id=cat.id) if c.mworkcur not in ["any", None]: work = meta.Session.query(model.Work).filter_by(url_text=c.mworkcur).first() if work is not None: qorder = qorder.filter_by(work_id=work.id) if c.mstatcur not in ["any", "performed", "not_performed", None]: status = ( meta.Session.query(model.Status) .filter(model.Status.redirects == model.Status.id) .filter_by(id=c.mstatcur) .first() ) if status is not None: qorder = qorder.filter_by(status_id=status.id) elif c.mstatcur == "not_performed": qorder = qorder.filter(model.sql.not_(model.Order.status_id.in_([3, 4, 15]))) elif c.mstatcur == "performed": qorder = qorder.filter(model.Order.status_id.in_([3, 4])) qorder = qorder.filter_by(deleted=bool(request.urlvars.get("deleted", False))) # Разбивка на страницы c.paginator = h.paginate.Page( qorder, page=(kwargs.get("page") or 1), # int(request.params.get('page', 1)), items_per_page=(session.get("preferences") or {}).get("ordersinpage", 15), ) c.ordercount = qorder.count() mstat = ( meta.Session.query(model.Status) .filter(model.Status.redirects == model.Status.id) .filter_by(deleted=False) .order_by(model.Status.id) .all() ) c.mstat = [ ([("any", u" -- Все -- ")], u"Все заявки"), ([("not_performed", u"Не выполненные"), ("performed", u"Выполненные")], u"По степени завершённости"), ([[x.id, x.title] for x in mstat], u"В определённом состоянии"), ] mcat = meta.Session.query(model.Category).filter_by(deleted=False).order_by(model.Category.id) if kwargs.get("upcat") not in ["any", None] and upcat is not None: mcat = mcat.filter(or_(model.Category.upcat_id == upcat.id, model.Category.upcat_id == None)) c.mcat = [["any", u" -- Все -- "]] + [[x.url_text, x.title] for x in mcat.all()] mwork = meta.Session.query(model.Work).filter_by(deleted=False).order_by(model.Work.id).all() c.mwork = [["any", u" -- Все -- "]] + [[x.url_text, x.title] for x in mwork] session["last_orders_list_url"] = url_for() return render("/orders/list.html")
def saveautoassign(self): return render(u'/admin/assign.html')