コード例 #1
0
ファイル: views.py プロジェクト: Ishayahu/hasadim
def save_from_bd(request,section,option):
    # raise NotImplementedError("Надо корректно обрабатывать настройки, связанные с БД!! например, место по умолчанию, статус по умолчанию+сделать, чтобы при редактировании всё было правильно")
    lang,user,fio,method = get_info(request)
    if request.method == 'POST':
        value = request.POST.get('new_value')
        config=UnicodeConfigParser()
        config.readfp(codecs.open(config_file, encoding='utf-8', mode='r'))
        config.set(section,"__bd__option__"+option,value)
        config.write(codecs.open(config_file, encoding='utf-8', mode='w'))
        # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
        opt_id = get_full_bd_option(section,option).id
        opt_val = get_full_bd_option(section,option).value
        returning_value = str(opt_id)+";"+opt_val
        return (True,('OK.html', {},{'html':returning_value},request,app))
    return (True,('Error.html', {},{'html':'метод не POST! Нифига не сделано!'},request,app))
コード例 #2
0
ファイル: api.py プロジェクト: Ishayahu/MJCC-tasks
def get_asset_add_form_script(request,asset_category,form_number):
    lang=select_language(request)
    user = request.user.username
    try:
        fio = Person.objects.get(login=user)
    except Person.DoesNotExist:
        fio = FioError()
    method = request.method
    try:
        asset_type = Asset_type.objects.get(id=asset_category)
    except Asset_type.DoesNotExist:
        return ErrorMessage('Неверно указан код категории актива: '+str(asset_category))
    # функция для загрузки последней цены, срока гарантии + установка статуса в {{статус по умолчанию}} и места в {{место по умолчанию}} из настроек раздела [cashless] (из get_asset_add_form.html)
    # get_bd_option_with_description returns name,opt_id,opt_val,desc
    # a,b,default_place,c = get_bd_option_with_description('cashless','default_place')
    default_place = get_full_bd_option('cashless','default_place').value
    # a,b,default_status,c = get_bd_option_with_description('cashless','default_status')
    default_status = get_full_bd_option('cashless','default_status').value
    return (True,('get_asset_add_form_script.html', {},{'default_place':default_place,'default_status':default_status,'number':form_number,'asset_type':asset_type, 'method':method},request,app))
コード例 #3
0
ファイル: views.py プロジェクト: Ishayahu/hasadim
def edit_from_bd(request,section,option):
    lang,user,fio,method = get_info(request)
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
    opt_id = get_full_bd_option(section,option).id
    opts = get_bd_option_variants(section,option)
    for opt in opts:
        if str(opt.id) == str(opt_id):
            opt.selected = True
    # raise NotImplementedError("Надо корректно обрабатывать настройки, связанные с БД!! например, место по умолчанию, статус по умолчанию+сделать, чтобы при редактировании всё было правильно")
    return (True,('edit_from_bd.html', {},{'opts':opts,'option':option},request,app))
コード例 #4
0
ファイル: views.py プロジェクト: Ishayahu/hasadim
def show_settings(request):
    # a=open(os.path.sep.join((os.getcwd(),'user_settings','test_file.py')),'w')
    
    # raise NotImplementedError("Надо корректно обрабатывать настройки, связанные с БД!! например, место по умолчанию, статус по умолчанию+сделать, чтобы при редактировании всё было правильно")
    # Надо корректно обрабатывать настройки, связанные с БД!! например, место по умолчанию, статус по умолчанию
    #+сделать, чтобы при редактировании всё было правильно
    
    # class Setting():
        # def __init__(self, option, value, name, description, from_bd):
            # self.name = name
            # self.value = value.replace('\n','<p>')
            # self.description = description
            # self.option = option
            # self.from_bd = from_bd
    class Settings_group():
        def __init__(self,name,description):
            self.name = name
            self.settings = []
            self.description = description
    settings=[]
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    for section in config.sections():
        setting_goup = Settings_group(section,get_section_description(section))
        for item in config.items(section):
            # Не включаем описания и названия опций
            if item[0][-12:]=='_description' or item[0][-5:]=='_name' or item[0][-5:]=='_help':
                continue
            # Настройки, связанные со значениями в БД
            if item[0][:6]=='__bd__':
                if item[0][:12]=='__bd__name__':
                    option = item[0][12:]
                    # return name,opt_id,opt_val,desc
                    # Надо, чтобы при отображении в шаблоне редактировалось оно как список!
                    # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
                    full_option = get_full_bd_option(section,option)
                    # setting_goup.settings.append(Setting(option, opt_id+";"+opt_val, name, desc, 1))
                    setting_goup.settings.append(full_option)
            # Все остальные настройки
            else: 
                # setting_goup.settings.append(Setting(*get_option_with_name_and_description(section,item[0]), from_bd=0))
                full_option = get_full_option(section,item[0])
                setting_goup.settings.append(full_option)
        settings.append(setting_goup)
    return (True,('show_settings.html', {},{'settings':settings,},request,app))
コード例 #5
0
def show_user_settings(request,for_user_login):
    class Settings_group():
        def __init__(self,name,description):
            self.name = name
            self.settings = []
            self.description = description
    lang,login,user,method = get_info(request)
    if user not in admins and for_user_login:
        return (False,HttpResponseRedirect('/'))
    settings=[]
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    section = '{0}_settings'.format(login)
    try:
        setting_goup = Settings_group(section,get_section_description(section))
        for item in config.items(section):
            # Не включаем описания и названия опций
            if item[0][-12:]=='_description' or item[0][-5:]=='_name' or item[0][-5:]=='_help':
                continue
            # Настройки, связанные со значениями в БД
            if item[0][:6]=='__bd__':
                if item[0][:12]=='__bd__name__':
                    option = item[0][12:]
                    # return name,opt_id,opt_val,desc
                    # Надо, чтобы при отображении в шаблоне редактировалось оно как список!
                    # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
                    full_option = get_full_bd_option(section,option)
                    # setting_goup.settings.append(Setting(option, opt_id+";"+opt_val, name, desc, 1))
                    setting_goup.settings.append(full_option)
            # Все остальные настройки
            else:
                # setting_goup.settings.append(Setting(*get_option_with_name_and_description(section,item[0]), from_bd=0))
                full_option = get_full_option(section,item[0])
                setting_goup.settings.append(full_option)
        settings.append(setting_goup)
    except ConfigParser.NoSectionError:
        settings=None
    return (True,('show_settings.html', {},{'settings':settings,},request,app))
コード例 #6
0
ファイル: api.py プロジェクト: Ishayahu/MJCC-tasks
def cashless_edit_stages(request,bill_number,stage_name,new_stage,not_redirect):
    # print stage_name
    cl=Cashless.objects.get(id=bill_number)
    today=str(datetime.datetime.today()).split(' ')[0].replace('-','.') # '2013.10.21'
    today_dash=str(datetime.datetime.today()) # '2013-10-21'
    if stage_name in cl.stages.split(';'):
    # Если меняется дата этапа из настроек
        stage_number=cl.stages.split(';').index(stage_name)
        if new_stage=='1':
            dates=cl.dates.split(';')
            dates[stage_number] = today
            cl.dates = ';'.join(dates)
            cl.save()
        else:
            dates=cl.dates.split(';')
            dates[stage_number] = ''
            cl.dates = ';'.join(dates)
            cl.save()
    # Если меняется дата получения товара и сдачи документов в бухгалтерию
    if stage_name==u'Товар_получен':
        assets = cl.payment_set.get().asset_set.filter()
        # raise NotImplementedError("Надо чтобы статусы брались из настроек. Причём вместо заказан - статус для добавленного в счёт актива")
        # name_before,opt_id_before,opt_val_before,desc_before = get_bd_option_with_description("cashless","default_status")
        # name_after,opt_id_after,opt_val_after,desc_after = get_bd_option_with_description("cashless","status_after_closing_bill")
        opt_val_before = get_full_bd_option('cashless','default_status').id
        opt_val_after = get_full_bd_option('cashless','status_after_closing_bill').id
        status_reserved = Status.objects.get(id=opt_val_before)
        status_new =  Status.objects.get(id=opt_val_after)
        if new_stage=='1':
            cl.date_of_assets = today_dash
            cl.save()
            # Теперь надо активировать полученный товар в базе
            for asset in assets:
                asset.status = status_new
                asset.save()
        else:
            cl.date_of_assets = None
            cl.save()
            # Теперь надо перенести полученный товар обратно в зарезервированный
            for asset in assets:
                asset.status = status_reserved
                asset.save()
    if stage_name==u'Документы_сданы':
        if new_stage=='1':
            cl.date_of_documents = today_dash
            cl.save()
        else:
            cl.date_of_documents = None
            cl.save()
    # из views.show_bill для построения новой таблицы
    # если безнал - надо получить пройденные этапы и не пройденные и предоставить возможность их пройти в "пакетном режиме"
    # from user_settings.functions import get_stages
    
    # Мы должны пользоваться теми этапами, которые предусмотрены для счёта
    stages = cl.stages.split(';')
    class Stages_info():
        class Stage():
            def __init__(self,n,d):
                self.name = n
                self.date = d
                self.id_name = n.replace(" ","_")
        def __init__(self):
            self.items=[]
            for x in stages:
                self.items.append(self.Stage(x,""))
            self.items.append(self.Stage("Товар получен",""))
            self.items.append(self.Stage("Документы сданы",""))
        def edit(self,n,d):
            self.items[n].date=d
        def date_of_assets(self,d):
            self.items[-2].date=d
        def date_of_documents(self,d):
            self.items[-1].date=d
    si = Stages_info()
    if cl.dates:
        d=cl.dates.split(";")
        for x in range(len(stages)):
            if not d[x]:
                #break
                pass
            else:
                si.edit(x,d[x])
    if cl.date_of_assets:
        si.date_of_assets(cl.date_of_assets)
    if cl.date_of_documents:
        si.date_of_documents(cl.date_of_documents)
    if not_redirect=='1':
        return (True,('stages_table.html', {},{'stages_info':si},request,app))
    return (False,(HttpResponseRedirect('/all_bills/')))
コード例 #7
0
def show_settings(request):
    class Settings_group():
        def __init__(self,name,description):
            self.name = name
            self.settings = []
            self.description = description
    settings=[]
    config=ConfigParser.RawConfigParser()
    config.read(config_file)
    for section in config.sections():
        setting_goup = Settings_group(section,get_section_description(section))
        for item in config.items(section):
            # Не включаем описания и названия опций
            if item[0][-12:]=='_description' or item[0][-5:]=='_name' or item[0][-5:]=='_help':
                continue
            # Настройки, связанные со значениями в БД
            if item[0][:6]=='__bd__':
                if item[0][:12]=='__bd__name__':
                    option = item[0][12:]
                    # return name,opt_id,opt_val,desc
                    # Надо, чтобы при отображении в шаблоне редактировалось оно как список!
                    # name,opt_id,opt_val,desc = get_bd_option_with_description(section,option)
                    full_option = get_full_bd_option(section,option)
                    # setting_goup.settings.append(Setting(option, opt_id+";"+opt_val, name, desc, 1))
                    setting_goup.settings.append(full_option)
            # Все остальные настройки
            else: 
                # setting_goup.settings.append(Setting(*get_option_with_name_and_description(section,item[0]), from_bd=0))
                full_option = get_full_option(section,item[0])
                setting_goup.settings.append(full_option)
        settings.append(setting_goup)
        # получаем список модулей, доступных для подключения в меню
    modules = Settings_group('Модули','Доступные модули для системы')
    import os
    import os.path
    from functions import Option
    # [('assets_name', ''), ('section_description', '\xd0\x9f\xd0\xbe\xd0\xb4\xd0\xba\xd0\xbb\xd1\x8e\xd1\x87\xd1\x91\xd0\xbd\xd0\xbd\xd1\x8b\xd0\xb5 \xd0\xbc\xd0\xbe\xd0\xb4\xd1\x83\xd0\xbb\xd0\xb8'), ('assets_description', ''), ('assets', 'True')]
    # получаем списки модулей, которые находятся в настройках
    try:
        connected_modules = [x[0] for x in config.items('modules')]
    except ConfigParser.NoSectionError:
        connected_modules=[]
    # print connected_modules
    cur_dir = os.getcwd()
    for record in os.listdir('.'):
        if os.path.isdir(record):
            temp_dir = os.path.join(cur_dir,record)
            # os.chdir(temp_dir)
            if 'todoes_module' in os.listdir(temp_dir):
                lines = codecs.open(os.path.join(cur_dir,
                                          record,
                                          'todoes_module'),
                                    'r',
                                    encoding='utf-8').readlines()
                lines = [line.strip() for line in lines]
                if lines and lines[0]==u'MODULE_DESCRIPTION_v_1':
                    # проверяем, не включён ли он
                    if record in connected_modules:
                        modules.settings.append(Option(
                            section=u'Модули',
                            option=record,
                            val='True',
                            name=lines[1],
                            desc=lines[2],
                            help_message=lines[3],
                            from_bd=0,
                            opt_id=None,
                            option_type='CONNECT'
                        ))
                    else:
                        # если не подключён
                        modules.settings.append(Option(
                            section=u'Модули',
                            option=record,
                            val='False',
                            name=lines[1],
                            desc=lines[2],
                            help_message=lines[3],
                            from_bd=0,
                            opt_id=None,
                            option_type='CONNECT'
                        ))
    # для каждого модуля надо проверить, есть ли он в настройках
    # если нет - то можно его подключить и добавить в настройки,
    # если есть показываем статус из настроек. Данные для модуля
    # будем брать из файла todoes_module. Если в нём не правильные
    # данные - выдаём про него отдельное сообщение
    settings.append(modules)
    return (True,('show_settings.html',
                  {},
                  {'settings':settings,
                   # 'modules':modules,
                   },
                  request,
                  app))