def index(self): """Отображение главной страницы""" campaign_q = meta.Session.query(model.Campaign) c.current_campaign = campaign_q.filter_by(status = '1').first() c.finished_active_campaign = campaign_q.filter_by(status = '2').first() c.finished_inactive_campaign = campaign_q.filter_by(status = '3').order_by(model.Campaign.id.desc()).all() return render('/derived/campaign/view.html')
def user_app(self): """Вывод данных о заявке пользователя""" # Выбор заявки и элементов заявки для определённого пользователя app_q = meta.Session.query(model.App) c.current_app = app_q.filter_by(author_id = app_globals.user_id).filter_by(campaign_id = app_globals.current_campaign_id).first() app_elements_q = meta.Session.query(model.AppElements) c.current_app_elements = app_elements_q.filter_by(app_id = c.current_app.id) # Выбор всех доступных вариантов источников финансирования и нужд finsource_q = meta.Session.query(model.FinSource) c.available_finsource = [(finsource.id, finsource.name) for finsource in finsource_q] needs_q = meta.Session.query(model.Needs) c.available_needs = [(needs.id, needs.name) for needs in needs_q] users = request.environ['authkit.users'] # c.available_groups = users.list_groups() groups_q = meta.Session.query(model.Group) c.available_groups = [(group.uid, group.view) for group in groups_q] # Информациия о заявке values = {} element_amount = {} element_amountp = {} element_price = {} element_pricep = {} total_price = 0 total_pricep = 0 for element in c.current_app_elements: values['quarter1_el'+str(element.id)] = element.quarter1 values['quarter2_el'+str(element.id)] = element.quarter2 values['quarter3_el'+str(element.id)] = element.quarter3 values['quarter4_el'+str(element.id)] = element.quarter4 values['amountp_el'+str(element.id)] = element.amountp values['pricep_el'+str(element.id)] = element.pricep values['finsource_el'+str(element.id)] = element.finsource values['needs_el'+str(element.id)] = element.needs values['place_el'+str(element.id)] = element.place values['note_el'+str(element.id)] = element.note element_amount[element.id] = element.quarter1 + element.quarter2 + element.quarter3 + element.quarter4 element_amountp[element.id] = element.amountp element_pricep[element.id] = element.pricep element_price[element.id] = element_amount[element.id] * element.items.price if element.status == 3: pass else: total_price += element_price[element.id] total_pricep += element_pricep[element.id] c.element_amount = element_amount c.element_amountp = element_amountp c.element_price = element_price c.element_pricep = element_pricep c.total_price = total_price c.total_pricep = total_pricep c.all_apps = app_q.filter_by(author_id = app_globals.user_id).all() return htmlfill.render(render('/derived/app/user_view.html'), values)
def add_user_form(self): """Показывает форму регистрации, только Администратор должен иметь доступ к ней""" users = request.environ['authkit.users'] #c.available_groups = users.list_groups()[1:] groups_q = meta.Session.query(model.Group) c.available_groups = [(group.name, group.view) for group in groups_q] #c.available_roles = users.list_roles() return render('/derived/account/add_user_form.html')
def new_item(self): """Отображение формы для создания объекта""" section_q = meta.Session.query(model.Section) available_sections = [(section.id, section.name) for section in section_q] c.available_sections = available_sections[1:] unit_q = meta.Session.query(model.Unit) c.available_units = [(unit.id, unit.name) for unit in unit_q] return render("/derived/catalog/new_item.html")
def sale_app(self): """Вывод формы для реализации заявок""" # Пустой запрос global_app_elements = meta.Session.query(model.AppElements).filter_by(id = 0) values = {} # Выбор нужных заявок и элементов заявки app_q = meta.Session.query(model.App) approved_apps = app_q.filter_by(campaign_id = app_globals.current_campaign_id) approved_apps = approved_apps.filter(or_(model.App.status.like(4), model.App.status.like(4))).all() for approved_app in approved_apps: app_elements_q = meta.Session.query(model.AppElements) app_elements = app_elements_q.filter_by(app_id = approved_app.id) for element in app_elements: values['quarter1_el'+str(element.id)] = element.quarter1 values['quarter2_el'+str(element.id)] = element.quarter2 values['quarter3_el'+str(element.id)] = element.quarter3 values['quarter4_el'+str(element.id)] = element.quarter4 values['quarter1p_el'+str(element.id)] = element.quarter1p values['quarter2p_el'+str(element.id)] = element.quarter2p values['quarter3p_el'+str(element.id)] = element.quarter3p values['quarter4p_el'+str(element.id)] = element.quarter4p values['finsource_el'+str(element.id)] = element.finsource values['needs_el'+str(element.id)] = element.needs values['place_el'+str(element.id)] = element.place values['note_el'+str(element.id)] = element.note values['action_el'+str(element.id)] = element.status try: global_app_elements = global_app_elements.union(app_elements) except: pass c.global_app_elements = global_app_elements.order_by(model.AppElements.item_id.asc()) total_price = 0 total_pricep = 0 for app_element in c.global_app_elements: if (app_element.status == 3) or (app_element.status == 8): pass else: total_price += app_element.price total_pricep += app_element.pricep c.total_price = total_price c.total_pricep = total_pricep # Действия c.available_actions = [ (5, u'Закуплено'), (6, u'Изменено'), (7, u'Заменено'), (8, u'Не закуплено'), ] # Корректное отображение названий групп groups_q = meta.Session.query(model.Group) c.available_groups = [(group.uid, group.view) for group in groups_q] #return render('/derived/app/sale_view.html') return htmlfill.render(render('/derived/app/sale_view.html'), values)
def sale_app_print(self): """Формы реализации заявки - версия для печати """ #response.content_type = 'application/download' # Пустой запрос global_app_elements = meta.Session.query(model.AppElements).filter_by(id = 0) values = {} # Выбор нужных заявок и элементов заявки app_q = meta.Session.query(model.App) approved_apps = app_q.filter_by(campaign_id = app_globals.current_campaign_id) approved_apps = approved_apps.filter(or_(model.App.status.like(4), model.App.status.like(4))).all() for approved_app in approved_apps: app_elements_q = meta.Session.query(model.AppElements) app_elements = app_elements_q.filter_by(app_id = approved_app.id) for element in app_elements: values['quarter1_el'+str(element.id)] = element.quarter1 values['quarter2_el'+str(element.id)] = element.quarter2 values['quarter3_el'+str(element.id)] = element.quarter3 values['quarter4_el'+str(element.id)] = element.quarter4 values['quarter1p_el'+str(element.id)] = element.quarter1p values['quarter2p_el'+str(element.id)] = element.quarter2p values['quarter3p_el'+str(element.id)] = element.quarter3p values['quarter4p_el'+str(element.id)] = element.quarter4p values['finsource_el'+str(element.id)] = element.finsource values['needs_el'+str(element.id)] = element.needs values['place_el'+str(element.id)] = element.place values['note_el'+str(element.id)] = element.note values['action_el'+str(element.id)] = element.status try: global_app_elements = global_app_elements.union(app_elements) except: pass c.global_app_elements = global_app_elements.order_by(model.AppElements.item_id.asc()) total_price = 0 total_pricep = 0 for app_element in c.global_app_elements: if app_element.status == 3: pass else: total_price += app_element.price total_pricep += app_element.pricep c.total_price = total_price c.total_pricep = total_pricep # Корректное отображение названий групп groups_q = meta.Session.query(model.Group) c.available_groups = [(group.uid, group.view) for group in groups_q] # Текущий год c.year = datetime.datetime.now().strftime('%Y') return htmlfill.render(render('/derived/app/sale_view_print.html'), values)
def edit_section(self): """Отображение формы для изменения/удаления раздела""" section_q = meta.Session.query(model.Section) section = section_q.filter_by(id=request.urlvars["id"]).first() c.current_section = section c.available_sections = [(section.id, section.name) for section in section_q] values = { "name": c.current_section.name, "parent_section": c.current_section.id, "description": c.current_section.description, } return htmlfill.render(render("/derived/catalog/edit_section.html"), values)
def signin(self): """Вход в систему Здесь происходит много всего: - добавление глобальной переменной, содержащей user_id - проверка, началась ли кампания - проверка, создана ли заявка для текущей кампании; если нет - создание - если кампания не запущена, сбросить глобальные переменные - TODO: что-то надо сделать с предыдущими заявками""" if not request.environ.get('REMOTE_USER'): # This triggers the AuthKit middleware into displaying the sign-in form abort(401) else: # Определить uis пользователя и поместить в глобальную переменную user_q = meta.Session.query(model.User) user = user_q.filter_by(username = request.environ['REMOTE_USER']).first() app_globals.user_id = user.uid app_globals.user_group = user.group.view app_globals.user_view = user.view campaign_q = meta.Session.query(model.Campaign) c.current_campaign = campaign_q.filter_by(status = '1').first() # Проверить, есть ли активные кампании if c.current_campaign: app_globals.current_campaign_id = c.current_campaign.id app_globals.current_campaign_start_date = c.current_campaign.start_date app_globals.current_campaign_end_date = c.current_campaign.end_date # Проверить, есть ли у пользователя заявка для этой кампании app_q = meta.Session.query(model.App) c.app = app_q.filter_by(author_id = app_globals.user_id).filter_by(campaign_id = app_globals.current_campaign_id).first() try: c.app.id # Создать заявка для новой кампании except: app = model.App() app.author_id = app_globals.user_id app.status = '1' app.campaign_id = app_globals.current_campaign_id app.created = datetime.datetime.now() app.edited = datetime.datetime.now() meta.Session.add(app) meta.Session.flush() ''' Сделать что-то с предыдущими заявками!!! ''' # Если кампаний не найдено, обнулить глобальные переменные else: #app_globals.current_campaign_id = 0 #app_globals.current_campaign_start_date = 0 #app_globals.current_campaign_end_date = 0 pass return render('/derived/account/signedin.html')
def group_app_print(self): """Вывод данных о заявке по отделу - версия для печати""" #response.content_type = 'application/download' # Пустой запрос group_app_elements = meta.Session.query(model.AppElements).filter_by(id = 0) # Выбор группы boss_q = meta.Session.query(model.User) boss_group = boss_q.filter_by(username = request.environ['REMOTE_USER']).first().group_uid c.boss_group_view = boss_q.filter_by(username = request.environ['REMOTE_USER']).first().group.view # Выбор пользователей в этой группе users_q = meta.Session.query(model.User) users_in_group = users_q.filter_by(group_uid = boss_group).all() # Выбор заявки и элементов заявок, соответстующих определённой группе for user in users_in_group: app_q = meta.Session.query(model.App) current_app = app_q.filter_by(author_id = user.uid).filter_by(campaign_id = app_globals.current_campaign_id) current_app = current_app.filter(or_(model.App.status.like(2), model.App.status.like(3))).first() app_elements_q = meta.Session.query(model.AppElements) try: current_app_elements = app_elements_q.filter_by(app_id = current_app.id) group_app_elements = group_app_elements.union(current_app_elements) except: pass c.group_app_elements = group_app_elements.order_by(model.AppElements.item_id.asc()) total_price = 0 for app_element in c.group_app_elements: if app_element.status == 3: pass else: total_price += app_element.price c.total_price = total_price # Вывод корректных названий групп groups_q = meta.Session.query(model.Group) c.available_groups = [(group.uid, group.view) for group in groups_q] # Текущий год c.year = datetime.datetime.now().strftime('%Y') # Вывод информации о лимитах users = request.environ['authkit.users'] limit_q = meta.Session.query(model.Limit) try: c.limit = limit_q.filter_by(campaign_id = app_globals.current_campaign_id).filter_by(group_uid = boss_group).first() except: c.limit = '0' return render('/derived/app/group_view_print.html')
def manage_accounts(self): """Основная страница управления пользователями Список пользователей, групп""" users = request.environ['authkit.users'] boss_list = {} c.users = users for user in users.list_users(): if users.user_has_role(user, 'boss'): try: boss_list.update({users.user_group(user):user}) except: pass c.boss_list = boss_list return render('/derived/account/manage_accounts.html')
def settings(self): """Настройка параметров: Нужды Источники финансирования Единица измерения""" finsource_q = meta.Session.query(model.FinSource) c.available_finsource = [(finsource.id, finsource.name) for finsource in finsource_q] needs_q = meta.Session.query(model.Needs) c.available_needs = [(needs.id, needs.name) for needs in needs_q] unit_q = meta.Session.query(model.Unit) c.available_units = [(unit.id, unit.name) for unit in unit_q] return render('/derived/campaign/settings.html')
def search_item(self): """Поиск объектов по каталогу""" section_q = meta.Session.query(model.Section) c.section = section_q item_q = meta.Session.query(model.Item) c.search_results = item_q.filter_by(brand=self.form_result["search_string"]).all() # To disable "Add" link app_q = meta.Session.query(model.App) c.current_app_status = ( app_q.filter_by(author_id=app_globals.user_id) .filter_by(campaign_id=app_globals.current_campaign_id) .first() .status ) return render("/derived/catalog/search_item.html")
def edit_item(self): """Отображение формы для изменения/удаления объекта""" section_q = meta.Session.query(model.Section) c.available_sections = [(section.id, section.name) for section in section_q] unit_q = meta.Session.query(model.Unit) c.available_units = [(unit.id, unit.name) for unit in unit_q] item_q = meta.Session.query(model.Item) item = item_q.filter_by(id=request.urlvars["id"]).first() c.current_item = item values = { "brand": c.current_item.brand, "model": c.current_item.model, "description": c.current_item.description, "section_id": c.current_item.section_id, "unit_id": c.current_item.unit_id, "price": c.current_item.price, } # return render('/derived/catalog/edit.html') return htmlfill.render(render("/derived/catalog/edit_item.html"), values)
def section(self, id): """Отображает список подразделов и breadcrumbs""" section_q = meta.Session.query(model.Section) c.section = section_q def breadcrumbs(section_id): "Отображает список разделов до Главного" a = "" b = [] d = [] while a != None: a = c.section.filter_by(id=section_id).first().parent_section_id a_name = c.section.filter_by(id=section_id).first().name a_id = c.section.filter_by(id=section_id).first().id if a != None: b = [(a_name, a_id)] + b section_id = a c.breadcrumbs = b # try: c.current_section = section_q.filter_by(id=id).first() breadcrumbs(c.current_section.id) # item_q = meta.Session.query(model.Item) # c.section_items = item_q.filter_by(section_id = c.current_section.id) # Just using ORM relation instead of another query c.section_items = c.current_section.items # To disable "Add" link app_q = meta.Session.query(model.App) c.current_app_status = ( app_q.filter_by(author_id=app_globals.user_id) .filter_by(campaign_id=app_globals.current_campaign_id) .first() .status ) app_globals.current_section_id = c.current_section.id return render("/derived/catalog/section.html")
def edit_group_form(self): """Форма изменения параметров группы""" users = request.environ['authkit.users'] c.group = request.params['group'] c.group_view = users.group_view(c.group) users_in_group_list = [] for user in users.list_users(): if users.user_has_group(user, request.params['group']): try: users_in_group_list += [user] except: pass if users.user_has_role(user, 'boss'): c.boss = user else: c.boss = '' c.users_in_group_list = users_in_group_list values = { 'group': c.group, 'view': c.group_view, } return htmlfill.render(render('/derived/account/edit_group_form.html'), values)
def edit_item_group_form(self): """Открывает новое окно для изменения конкретного элемента""" user_app_element = meta.Session.query(model.AppElements).filter_by(id = request.urlvars['id']) c.user_app_element = user_app_element finsource_q = meta.Session.query(model.FinSource) c.available_finsource = [(finsource.id, finsource.name) for finsource in finsource_q] needs_q = meta.Session.query(model.Needs) c.available_needs = [(needs.id, needs.name) for needs in needs_q] users = request.environ['authkit.users'] groups_q = meta.Session.query(model.Group) c.available_groups = [(group.uid, group.view) for group in groups_q] # Информациия о заявке values = {} element_amount = {} element_price = {} total_price = 0 for element in user_app_element: values['quarter1'] = element.quarter1 values['quarter2'] = element.quarter2 values['quarter3'] = element.quarter3 values['quarter4'] = element.quarter4 values['finsource'] = element.finsource values['needs'] = element.needs values['place'] = element.place values['note'] = element.note element_amount[element.id] = element.quarter1 + element.quarter2 + element.quarter3 + element.quarter4 element_price[element.id] = element_amount[element.id] * element.items.price total_price += element_price[element.id] c.element_amount = element_amount c.element_price = element_price c.total_price = total_price return htmlfill.render(render('/derived/app/edit_item_group_form.html'), values)
def edit_user_form(self): """Показывает форму регистрации, только Администратор должен иметь доступ к ней""" users = request.environ['authkit.users'] c.username = request.params['username'] c.password = users.user_password(c.username) c.view = (users.user_view(c.username)) c.mail = (users.user_mail(c.username)) #c.available_groups = users.list_groups()[1:] groups_q = meta.Session.query(model.Group) c.available_groups = [(group.name, group.view) for group in groups_q] try: c.group = users.user_group(request.params['username']) except: c.group = '' #c.available_roles = users.list_roles() # c.roles = users.user_roles(request.params['username']) values = { 'password': c.password, 'group': c.group, 'mail': c.mail, 'view': c.view, # 'roles': c.roles, } return htmlfill.render(render('/derived/account/edit_user_form.html'), values)
def add_user(self): """Добавление нового пользователя""" users = request.environ['authkit.users'] c.available_groups = users.list_groups()[1:] available_roles = users.list_roles() if not users.user_exists(self.form_result['username']): users.user_create(self.form_result['username'], password=self.form_result['password']) users.user_set_view(self.form_result['username'], self.form_result['view']) users.user_set_mail(self.form_result['username'], self.form_result['mail']) users.user_set_group(self.form_result['username'], self.form_result['group']) # try: # for role in self.form_result['roles']: # if role not in available_roles: # users.user_add_role(self.form_result['username']), self.form_result['roles']) # else: # users.user_add_role(self.form_result['username']), role) # except: # pass users.user_add_role(self.form_result['username'], 'user') meta.Session.commit() redirect(url(h.url(controller='account', action='manage_accounts'))) else: c.username = self.form_result['username'] return render('/derived/account/add_user_form.html')
def signinagain(self): """Вход в системe с другими логином и паролем""" request.environ['paste.auth_tkt.logout_user']() return render('/derived/account/signin.html').replace('%s', h.url('signin'))
def global_app_print(self): """Обобщённая заявка по предприятию - версия для печати """ #response.content_type = 'application/download' # Пустой запрос global_app_elements = meta.Session.query(model.AppElements).filter_by(id = 0) # Выбор нужных заявок и элементов заявки app_q = meta.Session.query(model.App) approved_apps = app_q.filter_by(campaign_id = app_globals.current_campaign_id) approved_apps = approved_apps.filter(or_(model.App.status.like(3), model.App.status.like(4))).all() for approved_app in approved_apps: app_elements_q = meta.Session.query(model.AppElements) app_elements = app_elements_q.filter_by(app_id = approved_app.id) try: global_app_elements = global_app_elements.union(app_elements) except: pass c.global_app_elements = global_app_elements.order_by(model.AppElements.item_id.asc()) total_price = 0 for app_element in c.global_app_elements: if app_element.status == 3: pass else: total_price += app_element.price c.total_price = total_price # Корректное отображение названий групп groups_q = meta.Session.query(model.Group) c.available_groups = [(group.uid, group.view) for group in groups_q] # Сегодняшняя дата c.now = datetime.datetime.now().strftime('%d.%m.%Y') # Сумма по группам users = request.environ['authkit.users'] c.users = users total_group_price = {} for group in c.users.list_groups(): # Пустой запрос group_app_elements = meta.Session.query(model.AppElements).filter_by(id = 0) # Выбор группы boss_group = c.users.group_uid(group) c.boss_group_view = c.users.group_view(group) # Выбор пользователей в этой группе users_q = meta.Session.query(model.User) users_in_group = users_q.filter_by(group_uid = boss_group).all() # Выбор заявки и элементов заявок, соответстующих определённой группе for user in users_in_group: app_q = meta.Session.query(model.App) current_app = app_q.filter_by(author_id = user.uid).filter_by(campaign_id = app_globals.current_campaign_id) current_app = current_app.filter(or_(model.App.status.like(2), model.App.status.like(3))).first() app_elements_q = meta.Session.query(model.AppElements) try: current_app_elements = app_elements_q.filter_by(app_id = current_app.id) group_app_elements = group_app_elements.union(current_app_elements) except: pass c.group_app_elements = group_app_elements.order_by(model.AppElements.item_id.asc()) total_price = 0 for app_element in c.group_app_elements: if (app_element.status == 3) or (app_element.status == 8): pass else: total_price += app_element.price total_group_price[group] = total_price c.total_group_price = total_group_price # Вывод информации о лимитах limit_q = meta.Session.query(model.Limit) try: c.limit = limit_q.filter_by(campaign_id = app_globals.current_campaign_id).all() except: pass return render('/derived/app/global_view_print.html')
def new_section(self): """Отображение формы для создания раздела""" section_q = meta.Session.query(model.Section) c.available_sections = [(section.id, section.name) for section in section_q] return render("/derived/catalog/new_section.html")
def new(self): """Форма создания новой заявочной кампании""" users = request.environ['authkit.users'] c.users = users return render('/derived/campaign/new.html')
def signout(self): """Выход из системы""" # The actual removal of the AuthKit cookie occurs when the response passes # through the AuthKit middleware, we simply need to display a page # confirming the user is signed out return render('/derived/account/signedout.html')