consolidator

Форк
0
/
GuidsWindow.py 
196 строк · 7.7 Кб
1
import os
2
import sys
3
import subprocess
4
from PySide6.QtGui import QBrush,QColor
5
from PySide6.QtCore import (Slot,Qt,QAbstractTableModel)
6
from PySide6.QtWidgets import (
7
    QTableView,
8
    QTableWidget,
9
    QPushButton,
10
    QTableWidgetItem,
11
    QDialog,
12
    QLabel,
13
    QTableWidgetSelectionRange)
14
from PySide6.QtUiTools import QUiLoader
15
from MyConfig import MyConfig
16
from GuidsSync import Synchronizer
17
import pandas as pd
18
from ExcelPath import ExcelPath
19

20
class TableModel(QAbstractTableModel):
21
    def __init__(self, data:pd.DataFrame):
22
        super(TableModel, self).__init__()
23
        self._data = data
24

25
    def data(self, index, role):
26
        if role == Qt.DisplayRole:
27
            value = self._data.iloc[index.row(), index.column()]
28
            return str(value)
29

30
    def rowCount(self, index):
31
        return self._data.shape[0]
32

33
    def columnCount(self, index):
34
        return self._data.shape[1]
35

36
    def headerData(self, section, orientation, role):
37
        # section is the index of the column/row.
38
        if role == Qt.DisplayRole:
39
            if orientation == Qt.Horizontal:
40
                return str(self._data.columns[section])
41

42
            if orientation == Qt.Vertical:
43
                return str(self._data.index[section])
44

45
class GuidsWindow(QDialog):
46
    
47
    normalButtonColor  = "background-color: rgb(236, 236, 236);"
48
    warningButtonColor = "background-color: rgb(255, 179, 48);"
49
    warningBrush:QBrush = QBrush(QColor("darkCyan"),bs=Qt.BrushStyle.SolidPattern)
50
    
51
    
52
    def __init__(self) -> None:
53
        try:
54
            try:
55
                self.cur_path = sys._MEIPASS
56
            except:
57
                self.cur_path = os.path.dirname(os.path.realpath(__file__))   
58
            super().__init__()
59
            self.guids_changed = False
60
            loader = QUiLoader()
61
            
62
            # init config
63
            self.settings = MyConfig(f"{self.cur_path}\\config.json")
64
            self.guidsDir:str = self.settings.get("GuidsDir_",defaultValue=f"{self.cur_path}\\guids") #bug fix GuidsDir -> GuidsDir_
65
            self.RemoteGuidsDir:str = self.settings.get("RemoteGuidsDir",defaultValue=None)
66
            # self.ExcelPath:str = self.settings.get("ExcelPath",defaultValue=None)
67
            ## issue http://vsys01775:8282/flea/pyexcelcons3/-/issues/8
68
            self.ExcelPath:str = ExcelPath.get()
69
            
70
            # init components
71
            self.GuidsDialog:QDialog = loader.load(f"{self.cur_path}\\GuidsWindow.ui", None)
72
            self.remoteGuidsButton:QPushButton = self.GuidsDialog.remoteGuidsButton
73
            self.localGuidsButton:QPushButton = self.GuidsDialog.localGuidsButton
74
            self.syncWarningLabel:QLabel = self.GuidsDialog.syncWarningLabel
75
            self.guidsTable:QTableWidget = self.GuidsDialog.guidsTable
76
            self.dataView:QTableView = self.GuidsDialog.dataView
77
            
78
            # init slot connections
79
            self.remoteGuidsButton.clicked.connect(self.remoteGuidsButton_clicked)
80
            self.localGuidsButton.clicked.connect(self.localGuidsButton_clicked)
81
            self.guidsTable.itemSelectionChanged.connect(self.guid_select)
82
            
83
                       
84
            # load guids
85
            self.sync:Synchronizer = None
86
            self.reload_guids()
87
                
88
        except : raise 
89
    
90
    def show(self):
91
        try:
92
            self.GuidsDialog.exec()
93
        except: raise
94
    
95
    def dialog_accepted(self):
96
        print("accepted")
97
    
98
    def init_sync(self):
99
        try:
100
            self.sync = Synchronizer(self.RemoteGuidsDir,self.guidsDir)
101
            self.syncWarningLabel.setVisible(False)              
102
        except Exception as exp: 
103
            if str(exp)=="Bad repo":
104
                self.syncWarningLabel.setVisible(True)
105
                pass
106
            else:
107
                raise exp 
108
           
109
    def remoteGuidsButton_clicked(self):
110
        """ Получить файлы с сервера """
111
        try:
112
            if self.sync.local_files_empty: self.sync.init_local()
113
            else: 
114
                self.sync.sync_server()
115
                self.guids_changed = True
116
            self.reload_guids()
117
        except: raise
118
    
119
    def localGuidsButton_clicked(self):
120
        """ Отправить файлы на сервер """
121
        try:
122
            self.sync.sync_local()
123
            self.reload_guids()
124
        except: raise
125
    
126
    @Slot()
127
    def open_excel(self):
128
        """Открыть excel-файл\n
129
            Путь к excel.exe должен быть указан в config.json в секции ExcelPath
130
        """
131
        try:
132
            btn:QPushButton = self.sender()
133
            cmd  = btn.property("cmd")
134
            print(cmd)
135
            # res = os.system(cmd)
136
            res = subprocess.run([self.ExcelPath,cmd],check=True)
137
            print(f"result: {res.returncode}")
138
            if res.returncode==0: self.reload_guids()
139
            if self.sync.newer_local_exist: self.guids_changed = True
140
        except: raise
141
            
142
    def reload_guids(self):
143
        """ Перезагрузить список справочников """
144
        try:
145
            self.init_sync()
146
            self.guidsTable.setColumnWidth(0,310)
147
            self.guidsTable.setColumnWidth(1,20)
148
            self.guidsTable.setColumnWidth(2,20)
149
            self.guidsTable.setColumnWidth(3,20)                        
150
            self.guidsTable.clearContents()
151
            self.guidsTable.setRowCount(0)
152
            for key in self.sync.local_files.files.keys():
153
                row = self.guidsTable.rowCount()
154
                self.guidsTable.insertRow(row)
155
                self.guidsTable.setItem(row,0,QTableWidgetItem(key))
156
                btn:QPushButton = QPushButton(self.guidsTable)
157
                fullPath = os.path.abspath(f"{self.guidsDir}\\{key}")
158
                cmd = f'{fullPath}'
159
                btn.setProperty("cmd",cmd)
160
                btn.setText("...")
161
                btn.clicked.connect(self.open_excel)
162
                self.guidsTable.setCellWidget(row,3,btn)
163
                                
164
                if key in self.sync.newer_server.keys():
165
                    twi1 =QTableWidgetItem(" ")
166
                    twi1.setBackground(self.warningBrush)
167
                    self.guidsTable.setItem(row,1,twi1)                     
168
                if key in self.sync.newer_local.keys():
169
                    twi2 =QTableWidgetItem(" ")
170
                    twi2.setBackground(self.warningBrush)                    
171
                    self.guidsTable.setItem(row,2,twi2)
172
               
173
            if self.sync.newer_server_exist: self.remoteGuidsButton.setStyleSheet(self.warningButtonColor)
174
            else: self.remoteGuidsButton.setStyleSheet(self.normalButtonColor)
175
            if self.sync.newer_local_exist: self.localGuidsButton.setStyleSheet(self.warningButtonColor)
176
            else: self.localGuidsButton.setStyleSheet(self.normalButtonColor)
177
            if self.sync.local_files_empty and not self.sync.server_files_empty: self.remoteGuidsButton.setStyleSheet(self.warningButtonColor)            
178
        except: raise
179
        
180
    @Slot()
181
    def guid_select(self):
182
        """ Выбор справочника """
183
        try:
184
            table:QTableWidget = self.sender()
185
            selectedRange = table.selectedRanges()
186
            if selectedRange is not None and selectedRange.__len__()>0 :
187
                selected:QTableWidgetSelectionRange = selectedRange[0] 
188
                item = table.item(selected.topRow(),0)
189
                if item is not None:
190
                    file=f"{self.guidsDir}\\{item.data(0)}"
191
                    print(file)
192
                    df = pd.read_excel(file)
193
                    model = TableModel(df)
194
                    self.dataView.setModel(model)
195
            
196
        except: raise

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.