Commits

fak3 committed 65f5ad7

interactive_fix_adata and snils settings

  • Participants
  • Parent commits 2af1dcd

Comments (0)

Files changed (6)

File gui_dialogs.py

         self.layout.setAlignment(self.button, Qt.AlignLeft)
 
 
-def parse_lengths():
-    logging.info(u'Вычисляется длительность всех скачанных видеофайлов')
-    settings = main_utils.load_settings()
-    for o in Order.objects.filter(archive_data__isnull=False).select_related('uik__region').iter_bulk():
-        logging.info(u'Вычисляется длительность заказа № %s', o)
-        main_utils.parse_order_videolen(settings['download_dir'], o)
-        o.save()
-    logging.info(u'Завершено: Длительность всех скачанных видеофайлов вычислена')
-
-
 class ExportAction(ActionSetting):
     def __init__(self, settings, parent):
         text = textwrap.dedent(u'''
 
         self.button.setEnabled(True)
         
-        
-class GetLenAction(ActionSetting):
-    def __init__(self, settings, parent):
-        text = textwrap.dedent(u'''
-            Вычислить длительность всех скачанных видеофайлов
-        ''').replace('\n', '')
-        super(GetLenAction,self).__init__(u'Длительность видео', u'Вычислить', text, self.onclick, parent)
-
-    def onclick(self):
-        self.button.setEnabled(False)
-
-        dlg = ActionDialog(u'Вычисляется длительность всех скачанных видеофайлов', parse_lengths)
-        res = dlg.exec_()
-
-        if res == ActionDialog.OK:
-            QMessageBox.information(None, u'Завершено', u'Завершено')
-
-        self.button.setEnabled(True)
-
 
 class BoolSetting(QGroupBox):
     def __init__(self, label, text, key, settings, parent, *args):
             #logging.info(u'Директория для скачанных файлов изменена:' % unicode(dir))
 
 
-class SettingsDialog(QDialog):
-    def __init__(self, parent, *args):
-        QDialog.__init__(self, parent, *args)
+class TextSetting(QFrame):
+    def __init__(self, label, key, settings, parent, *args):
+        QFrame.__init__(self, parent, *args)
+        self.key = key
+        self.settings = settings
+        self.value = settings[key]
 
+        self.label = QLabel(label)
+        self.edit = QLineEdit(self.value)
+        self.edit.textChanged .connect(self.change)
+
+        layout = HBox(self, [self.label, self.edit])
+
+    #sizeHint = lambda self: QSize(560, 80)
+
+    def change(self, text):
+        self.settings[self.key] = unicode(text)
+
+
+class SettingsDialog(Dialog):
+    sizeHint = lambda self: QSize(560, 780)
+    
+    def __init__(self, *args):
+        super(SettingsDialog, self).__init__(*args)
         self.settings = main_utils.load_settings()
 
         download_dir = DirSetting(u'Директория для скачанных файлов', 'download_dir', self.settings, self)
 
         max_time_text = u'Максимальное время, которое можно заказать'
         max_time = OrderTimeSetting(u'Максимальное время для заказа', max_time_text, 'max_time', self.settings, self)
+        
+        snils = TextSetting(u'СНИЛС (без разделителей)', 'snils', self.settings, self)
 
         max_exec_time_text = textwrap.dedent(u'''
             Проверять заказы только за срок:''').replace('\n', ' ')
         
         text = u"Автоматически экспортировать статистику"
         auto_export = BoolSetting(u'Экспорт статистики', text, 'auto_export', self.settings, self)
+        
+        text = u"Спрашивать неизвстные регионы у пользователя"
+        interactive_fix_adata = BoolSetting(u'Исправление полученных данных', text, 'interactive_fix_adata', self.settings, self)
 
         export_action = ExportAction(self.settings, self)
-        
-        self.getlen_action = GetLenAction(self.settings, self)
 
         self.ok = QPushButton('OK')
         self.ok.clicked.connect(self.accept)
 
         self.setSizePolicy(QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum))
 
-        layout = VBox(self, [
-            download_dir, max_time, max_exec_time, reorder_time, download_first, recheck_nlink, auto_export,
-            export_action, self.getlen_action, self.ok])
+        self.fr = QFrame()
+        flayout = VBox(self.fr, [
+            download_dir, snils, max_time, max_exec_time, reorder_time, download_first, recheck_nlink, interactive_fix_adata,
+            auto_export, export_action, self.ok])
+            
+        self.sa = QScrollArea()
+        self.sa.setWidgetResizable(True)
+        self.sa.setWidget(self.fr)
+        layout = VBox(self, [self.sa, self.ok])
 
 
     def accept(self):
 
 
     def wvload_finished(self, ok):
+        settings = main_utils.load_settings()
+        if settings['snils']:
+            doc = self.webview.page().mainFrame().documentElement()
+            snils = doc.findFirst("input[id=username]")
+            snils.evaluateJavaScript("this.value = '%s'" % settings['snils'])
+            self.webview.page().mainFrame().evaluateJavaScript('Authentication.format()')
+        
         sitedata = self.sites[self.current_site]
 
         cx = self.cookie_jar.cookiesForUrl(QUrl(sitedata['login_url']))
         settings.setdefault('download_before_dialog', False)
         settings.setdefault('recheck_no_link', True)
         settings.setdefault('auto_export', True)
+        settings.setdefault('interactive_fix_adata', True)
+        settings.setdefault('snils', '')
 
         main_utils.dump_settings(settings)
 
         self.action()
 
     def _settings_dlg(self):
-        dlg = gui_dialogs.SettingsDialog(self)
+        dlg = gui_dialogs.SettingsDialog()
         dlg.exec_()
 
 

File main_utils.py

         logging.info(u'последний %s' % last)
 
 
-def fix_adata(adata, reg_aliases, bad_addreses = None):
+def fix_adata(adata, settings, reg_aliases, bad_addreses = None):
     adata['region'] = reg_aliases.get(adata.get('region'))
     if adata['region']:
         return adata
         else:
             bad_addreses.add(addr)
 
+    if settings['interactive_fix_adata'] is False:
+        return adata
+        
     import gui_dialogs
     logging.info(u'Неправильный регион, адрес: \n%s' % addr)
     dlg = gui_dialogs.AddrParseDialog(addr)
             if not dborder.archive_data:
                 fetch_order_adata(dborder)
                 if dborder.archive_data:
-                    adata = fix_adata(dborder.archive_data, reg_aliases, bad_addreses)
+                    adata = fix_adata(dborder.archive_data, settings, reg_aliases, bad_addreses)
 
                     if dborder.uik_id == zerouik.id:
                         uik_id = umap.get(oukey(adata))
     return True
 
 
-
 def download_order_videofiles(dl_dir, order, on_stop = None):
     ''' Скачивает видеофайлы в заказе '''
     for archive_url in order.archive_urls:

File test/base.py

         self.tmp_download_dir = '/dev/shm/gosvideo_test/'
         shutil.rmtree(self.tmp_download_dir, True)
         
-        self.settings = {'download_dir': self.tmp_download_dir, 'auto_export': False, 'recheck_no_link': False}
+        self.settings = dict(
+            download_dir = self.tmp_download_dir, 
+            auto_export = False, 
+            recheck_no_link = False,
+            interactive_fix_adata = True)
         self.patch_load('settings')
         self.patch_load('reg_aliases')
         self.patch_load('bad_addreses')

File test/test_main.py

         
         
     def test_fixadata_bad_addr(self):
-        adata = fix_adata({'address': '%$#@'}, self.reg_aliases)
+        adata = fix_adata({'address': '%$#@'}, self.settings, self.reg_aliases)
         self.assertEqual(adata['region'], '?')
         
     def test_fixadata_empty_addr(self):
-        adata = fix_adata({}, self.reg_aliases)
+        adata = fix_adata({}, self.settings, self.reg_aliases)
         self.assertEqual(adata, {'region': '?'})
         
     def test_fixadata_region_ok(self):
-        adata = fix_adata({'region': 'Московская область'}, self.reg_aliases)
+        adata = fix_adata({'region': 'Московская область'}, self.settings, self.reg_aliases)
         self.assertEqual(adata['region'], 'Московская область')
         
     def test_fixadata_region_second(self):
-        adata = fix_adata({'address': 'Россия; Московская область'}, self.reg_aliases)
+        adata = fix_adata({'address': 'Россия; Московская область'}, self.settings, self.reg_aliases)
         self.assertEqual(adata['region'], 'Московская область')
         
     def test_fixadata_no_region(self):
         self.autoclick('AddrParseDialog.abuttons.-1')
-        adata = fix_adata({'address': 'Россия'}, self.reg_aliases)
+        adata = fix_adata({'address': 'Россия'}, self.settings, self.reg_aliases)
         self.assertEqual(adata['region'], '?')
         
         
         adata_expected = {'address': 'только улица', 'region': '?'}
         
         self.autoclick('AddrParseDialog.abuttons.-1')
-        adata_result1 = fix_adata(adata_input, self.reg_aliases, bad_addreses)
+        adata_result1 = fix_adata(adata_input, self.settings, self.reg_aliases, bad_addreses)
         
         with patch.object(AddrParseDialog, '__init__', side_effect = AddrParseDialog.__init__):
-            adata_result2 = fix_adata(adata_input, self.reg_aliases, bad_addreses)
+            adata_result2 = fix_adata(adata_input, self.settings, self.reg_aliases, bad_addreses)
             self.assertEqual(adata_result2, adata_expected)
             self.assertEqual(AddrParseDialog.__init__.called, False)
         
         adata_expected = {'address': 'МСК', 'region': 'Московская область'}
         
         self.autoclick('AddrParseDialog.abuttons.0')
-        adata_result1 = fix_adata(adata_input, self.reg_aliases)
+        adata_result1 = fix_adata(adata_input, self.settings, self.reg_aliases)
         
         with patch.object(AddrParseDialog, '__init__', side_effect = AddrParseDialog.__init__):
-            adata_result2 = fix_adata(adata_input, self.reg_aliases)
+            adata_result2 = fix_adata(adata_input, self.settings, self.reg_aliases)
             self.assertEqual(adata_result2, adata_expected)
             self.assertEqual(AddrParseDialog.__init__.called, False)
         
         self.assertEqual(Order.objects.filter(uik__num = 1, tstart = tstart).count(), 1)
         
     def test_order_timespan_geterror(self):
-        get = Mock(side_effect = [self.fakeserver.postget] + [ConnectionError] * 3)
+        get = Mock(side_effect = [self.fakeserver.postget] + [ConnectionError] * 4)
         patch('requests.session', lambda: Mock(get = get, post = self.fakeserver.postget)).start()
         args = self.uik, datetime.now(), timedelta(minutes = 30), {}
         self.assertRaises(ConnectionError, order_timespan, *args)
         self.assertEqual(Order.objects.count(), 0)
         
     def test_order_timespan_posterror(self):
-        post = Mock(side_effect = [ConnectionError] * 3)
+        post = Mock(side_effect = [ConnectionError] * 4)
         patch('requests.session', lambda: Mock(get = self.fakeserver.postget, post = post)).start()
         args = self.uik, datetime.now(), timedelta(minutes = 30), {}
         self.assertRaises(ConnectionError, order_timespan, *args)
         self.autoclick('AddrParseDialog.abuttons.0')
         self.autoclick('DownloadDialog.bbox.Cancel')
         def other_thread():
-            adata = fix_adata({'address': 'МСК; улица; дом'}, self.reg_aliases)
+            adata = fix_adata({'address': 'МСК; улица; дом'}, self.settings, self.reg_aliases)
             self.assertEqual(adata['region'], 'Московская область')
             dlg = DownloadDialog()
             res = dlg.exec_()

File test/test_userstories.py

                 'MainWindow.cb '
                 'DownloadDialog.treeWidget.0.0--dclick,'
                 'DownloadDialog.bbox.1 '
-                'MainWindow.tframe.settings_button '
-                'SettingsDialog.getlen_action.button '
-                'SettingsDialog.ok '
                 'MainWindow.ob ' # wait until action finishes before closing MainWindow
                 'OrderDialog.bbox.Cancel '
                 'MainWindow--close'