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 delete(self, id=None): h.admincheck() div = h.checkdiv(id) # Стараемся не оставить людей сиротами for user in div.people: user.deleted = True #meta.Session.delete(div) div.deleted = True meta.Session.commit() h.flashmsg (u"Подразделение было удалено") redirect_to(h.url_for(controller='division', action='list', id=None))
def save(self, id): 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) for key, value in self.form_result.items(): if getattr(div, key) != value: setattr(div, key, value) meta.Session.commit() h.flashmsg (u"Информация о подразделении была сохранена") redirect_to(h.url_for(controller='division', action='view', id=div.id))
def changeusers(self, id=None): h.admincheck() div = h.checkdiv(id) user = meta.Session.query(model.Person) userlist = eval(self.form_result['users']) # Сначала удалим всех нафиг oldusers = user.filter_by(div_id=id).all() for person in oldusers: person.div_id = None # Вносим в список новых пользователей try: users = user.filter(model.Person.id.in_(userlist)).all() for person in users: person.div_id = div.id except TypeError: # Если элемент один, то ругается, что Int не iterable user.get(userlist).div_id = div.id # Сохраняемся meta.Session.commit() h.flashmsg (u"Информация о подразделении была сохранена") redirect_to(h.url_for(controller='division', action='view', id=id))
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 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")