-
Notifications
You must be signed in to change notification settings - Fork 0
/
archive_transaction.py
476 lines (366 loc) · 18.3 KB
/
archive_transaction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'project_transaction.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
import sys
import mysql.connector
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QDate, Qt
from PyQt5.QtWidgets import QMessageBox, QDialog
from db import con
from dialogs import Dialog
from PyQt5.QtGui import QColor
from project_activity import Ui_Activity
import win32com.client as win32
class Ui_Trans(object):
#cell status
not_editable = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled
editable = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable
# Trans Pyqt Components
TBLTrans = "" # Table Transaction
BtnPrint = "" # BTN Print
BtnBack = "" # Back Project
project_id = 0 # Project id # Default 0
TBLTrans_rowcount = 0 # Row Count Default 0
TBLTrans_id = 0 # Row Id Default 0
TBLTrans_selectedRow = 0 # Row Id Default 0
ProjectTab=""
projectName=""
def print_trans():
cursor = con.cursor()
cursor.execute(f"SELECT * FROM `projects` WHERE `project_id` = {Ui_Trans.project_id}")
res = cursor.fetchall()
projname=res[0][1]
projsite=res[0][3]
category= res[0][6]
#Reset Selected Row
Ui_Trans.TBLTrans_id = 0
Ui_Trans.TBLTrans_selectedRow = 0
xlApp = win32.Dispatch('Excel.Application')
xlApp.Visible = True
# create a new excel workbook
wb = xlApp.Workbooks.Add()
# create a new excel worksheet
ws = wb.worksheets.add
ws.name = 'Transaction'
rows = []
columnHeaders = []
maxRow=Ui_Trans.TBLTrans.rowCount()+3
ws.Range(ws.cells(3, 1),ws.cells(maxRow, 10)).verticalalignment=-4108
ws.Range(ws.cells(3, 1),ws.cells(maxRow, 10)).horizontalalignment=-4108
#horizontal border
ws.Range(ws.cells(3, 2),ws.cells(maxRow+1, 10)).Borders(3).Weight = 3
#vertical border
ws.Range(ws.cells(3, 1),ws.cells(maxRow, 10)).Borders(2).Weight = 3
# retrieve columns label
for j in range(Ui_Trans.TBLTrans.model().columnCount()):
columnHeaders.append(Ui_Trans.TBLTrans.horizontalHeaderItem(j).text())
# retrieve table content
for row in range(Ui_Trans.TBLTrans.rowCount()):
record = []
for col in range(Ui_Trans.TBLTrans.columnCount()):
if (col==0):
val = Ui_Trans.TBLTrans.cellWidget(row,col)
date = (f"{val.date().month()},{val.date().day()},{val.date().year()}")
record.append(date)
elif (col == 1) | (col == 6) | (col == 7):
record.append(Ui_Trans.TBLTrans.cellWidget(row,col).text())
else:
record.append(Ui_Trans.TBLTrans.item(row, col).text())
rows.append(record)
# insert table content to Excel
ws.Range(ws.cells(4, 2),ws.cells(len(rows)+3, len(columnHeaders)+1)).value = rows
# insert column labels To Excel
ws.Range(ws.cells(3, 2),ws.cells(3, len(columnHeaders)+1)).value = columnHeaders
ws.Columns.AutoFit()
ws.PageSetup.Orientation = 2
ws.cells(1, 2).value = "Project"
ws.cells(2, 2).value = "Site"
ws.cells(1, 3).value = f": {projname} - {category}"
ws.cells(2, 3).value = f": {projsite}"
ws.Range(ws.Cells(1,3),ws.Cells(1,7)).MergeCells = True
ws.Range(ws.Cells(2,3),ws.Cells(2,7)).MergeCells = True
def process_date(date):
index = 0
start = 0
flag1 = True
flag2 = False
flag3 = False
while index < len(date):
if flag1 and (date[index] == ","):
year = date[start:index]
start = index + 1
flag1 = False
flag2 = True
elif flag2 and (date[index] == ","):
month = date[start:index]
start = index + 1
flag2 = False
flag3 = True
if flag3:
day = date[start:len(date)]
break
index = index + 1
return QDate(int(year),int(month),int(day))
def insert_trans(status,date_status):
try:
# Price & Quantity Num Validator
my_regex = QtCore.QRegExp("^\\d{1,6}(\\.\\d{1,2})?$")
my_regex_num = QtCore.QRegExp("^[0-9]*$")
#Font for Input
font = QtGui.QFont()
font.setFamily("Calibri")
font.setPointSize(12)
cursor = con.cursor()
cursor.execute(f"SELECT * FROM `transaction` WHERE `project_id` = {Ui_Trans.project_id}")
res = cursor.fetchall()
# Remove Rows
while(Ui_Trans.TBLTrans.rowCount() > 0):
Ui_Trans.TBLTrans.removeRow(0)
Ui_Trans.TBLTrans.setRowCount(len(res))
rowcount = len(res)
Ui_Trans.TBLTrans_rowcount = len(res)
row = 0
for x in res:
# Set Vertical Item (For Trans ID)
item = QtWidgets.QTableWidgetItem()
Ui_Trans.TBLTrans.setVerticalHeaderItem(row, item)
item = Ui_Trans.TBLTrans.verticalHeaderItem(row)
item.setText(str(x[0]))
#transaction data array
trans_data = []
DateTrans = QtWidgets.QDateEdit(Ui_Trans.TBLTrans)
DateTrans.setCalendarPopup(True)
DateTrans.setFont(font)
DateTrans.setDate(Ui_Trans.process_date(x[3]))
DateTrans.setAlignment(QtCore.Qt.AlignCenter)
DateTrans.setEnabled(date_status)
DateTrans.setStyleSheet("color: rgb(255, 255, 255);")
#LEReceipt
LEReceipt = QtWidgets.QLineEdit(Ui_Trans.TBLTrans)
LEReceipt.setGeometry(QtCore.QRect(0, 0, 100, 31))
LEReceipt.setAlignment(QtCore.Qt.AlignCenter)
LEReceipt.setStyleSheet("color:white;")
LEReceipt.setObjectName("LEReceipt")
LEReceipt.setText(str(x[2]))
LEReceipt.setFont(font)
LEReceipt.setEnabled(date_status)
my_validator = QtGui.QRegExpValidator(my_regex_num,LEReceipt)
LEReceipt.setValidator(my_validator)
#LEPrice
LEPrice = QtWidgets.QLineEdit(Ui_Trans.TBLTrans)
LEPrice.setGeometry(QtCore.QRect(0, 0, 100, 31))
LEPrice.setAlignment(QtCore.Qt.AlignCenter)
LEPrice.setStyleSheet("color:white;")
LEPrice.setObjectName("LEPrice")
LEPrice.setText(str(x[8]))
LEPrice.setFont(font)
LEPrice.setEnabled(date_status)
my_validator = QtGui.QRegExpValidator(my_regex,LEPrice)
LEPrice.setValidator(my_validator)
#LEQuantity
LEQuantity = QtWidgets.QLineEdit(Ui_Trans.TBLTrans)
LEQuantity.setGeometry(QtCore.QRect(0, 0, 100, 31))
LEQuantity.setAlignment(QtCore.Qt.AlignCenter)
LEQuantity.setStyleSheet("color:white;")
LEQuantity.setObjectName("LEQuantity")
LEQuantity.setText(str(x[9]))
LEQuantity.setFont(font)
LEQuantity.setEnabled(date_status)
my_validator = QtGui.QRegExpValidator(my_regex,LEQuantity)
LEQuantity.setValidator(my_validator)
# Append in Array (In Order)
trans_data.append(DateTrans)
trans_data.append(LEReceipt)
trans_data.append(x[4])
trans_data.append(x[5])
trans_data.append(x[6])
trans_data.append(x[7])
trans_data.append(LEPrice)
trans_data.append(LEQuantity)
trans_data.append(x[10])
#Set Cell Data
for column in range(0,9):
item = QtWidgets.QTableWidgetItem()
item.setTextAlignment(QtCore.Qt.AlignCenter)
# Total Not Editable
if column == 8:
item.setFlags(Ui_Trans.not_editable)
else:
item.setFlags(status) # Default not editable
# Date Format for First Column
if (column == 0) | (column == 1) | (column == 6) | (column == 7):
Ui_Trans.TBLTrans.setCellWidget(row, column,trans_data[column])
else:
item.setText(str(trans_data[column])) # trans data
Ui_Trans.TBLTrans.setItem(row, column, item)
row = row + 1
except mysql.connector.Error as e:
Dialog.msg_dialog("Server Error Please Try Again")
def default():
Ui_Trans.BtnPrint.show()
Ui_Trans.BtnBack.show()
Ui_Trans.ProjectTab.setEnabled(True)
def remove_trans():
if Ui_Trans.TBLTrans_id > 0:
if Dialog.confirm_dialog(f"Are you sure you want to remove transaction record at row number {Ui_Trans.TBLTrans_selectedRow + 1} ?") == QMessageBox.Ok:
try:
cursor = con.cursor()
query = (f"DELETE FROM `transaction` WHERE `id` = {Ui_Trans.TBLTrans_id}")
cursor.execute(query)
con.commit()
Dialog.msg_dialog(f"Transaction Record at row number {Ui_Trans.TBLTrans_selectedRow + 1} successfuly removed !")
Ui_Activity.record_activity("admin",f"Removed Transaction Record from Project: {Ui_Trans.projectName}")
# Reset Values
Ui_Trans.insert_trans(Ui_Trans.not_editable,False)
Ui_Trans.TBLTrans_id = 0
Ui_Trans.TBLTrans_selectedRow = 0
except mysql.connector.Error as e:
Dialog.msg_dialog("Server Error Please Try Again Later")
else:
Dialog.msg_dialog("Please select a row first")
def cancel_trans():
if (Dialog.confirm_dialog("Are you sure you want to discard changes?") == QMessageBox.Ok):
Ui_Trans.insert_trans(Ui_Trans.not_editable,False)
# Set Default Button
Ui_Trans.default()
def edit_trans():
Ui_Trans.insert_trans(Ui_Trans.editable,True)
#Reset Selected Row
Ui_Trans.TBLTrans_id = 0
Ui_Trans.TBLTrans_selectedRow = 0
Ui_Trans.BtnBack.hide()
Ui_Trans.ProjectTab.setEnabled(False)
def save_trans():
if (Dialog.confirm_dialog("Are you sure you want to update changes?") == QMessageBox.Ok):
rows = Ui_Trans.TBLTrans.rowCount()
x=0
trans_id = ""
for i in range(rows):
trans_id = Ui_Trans.TBLTrans.verticalHeaderItem(x).text()
trans_date = (f"{Ui_Trans.TBLTrans.cellWidget(x,0).date().year()},{Ui_Trans.TBLTrans.cellWidget(x,0).date().month()},{Ui_Trans.TBLTrans.cellWidget(x,0).date().day()}")
receipt = Ui_Trans.TBLTrans.cellWidget(x,1).text()
supplier = Ui_Trans.TBLTrans.item(x,2).text()
address = Ui_Trans.TBLTrans.item(x,3).text()
articles = Ui_Trans.TBLTrans.item(x,4).text()
unit = Ui_Trans.TBLTrans.item(x,5).text()
price = Ui_Trans.TBLTrans.cellWidget(x,6).text()
quantity = Ui_Trans.TBLTrans.cellWidget(x,7).text()
total = float(price) * float(quantity)
try:
cursor = con.cursor()
query1 = f"UPDATE `transaction` SET `trans_date`= '{trans_date}', `receipt_no` = {receipt}, `supplier` = '{supplier}', `address` = '{address}', `articles` = '{articles}', `unit` = '{unit}', `unit_price` = {price}, `quantity` = {quantity}, `total` = {total} WHERE `id`={trans_id}"
cursor.execute(query1)
con.commit()
except mysql.connector.Error as e:
Dialog.msg_dialog(str(e))
#Dialog.msg_dialog("Server Error Please Try Again")
x = x + 1 # Another Row
# Refresh Table
Ui_Trans.insert_trans(Ui_Trans.not_editable,False)
# Set Default Button
Ui_Trans.default()
Dialog.msg_dialog("Transaction Update Success")
Ui_Activity.record_activity("admin",f"Updated Transaction Record from Project: {Ui_Trans.projectName}")
def TBLTrans_select(selected, deselected):
for x in selected.indexes():
x=x.row()
Ui_Trans.TBLTrans_selectedRow = x
Ui_Trans.TBLTrans_id = int(Ui_Trans.TBLTrans.verticalHeaderItem(x).text())
'''
for x in range(0,14):
Ui_Trans.TBLTrans.item(Ui_Trans.TBLTrans_selectedRow,x).setBackground(QColor('#666666'))
'''
def Transaction(TransactionWidget,DashbaordWindow,BtnBack,ProjectTab):
#Font for Title
font = QtGui.QFont()
font.setFamily("Calibri")
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
# Transaction Title
LBTransTitle = QtWidgets.QLabel(TransactionWidget)
LBTransTitle.setGeometry(QtCore.QRect(10, 10, 271, 31))
LBTransTitle.setFont(font)
LBTransTitle.setStyleSheet("color: rgb(255, 255, 255);")
LBTransTitle.setAlignment(QtCore.Qt.AlignCenter)
LBTransTitle.setObjectName("LBTransTitle")
# Set Font to 12 (Buttons)
font.setPointSize(12)
# Print Button
Ui_Trans.BtnPrint = QtWidgets.QPushButton(TransactionWidget)
Ui_Trans.BtnPrint.setGeometry(QtCore.QRect(950, 10, 100, 31))
Ui_Trans.BtnPrint.setFont(font)
Ui_Trans.BtnPrint.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
Ui_Trans.BtnPrint.setStyleSheet("background-color: rgb(0, 0, 0.9);color: rgb(255, 255, 255);border-radius:5px;")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/Icons/Assets/PrintIcon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Ui_Trans.BtnPrint.setIcon(icon)
Ui_Trans.BtnPrint.setObjectName("BtnPrint")
# Transaction TGroup (Table)
Transaction = QtWidgets.QGroupBox(TransactionWidget)
Transaction.setGeometry(QtCore.QRect(10, 60, 1041, 345))
Transaction.setStyleSheet("border:none;color:white;")
Transaction.setTitle("")
Transaction.setObjectName("Transaction")
# BG Transaction Table
BgTrans = QtWidgets.QLabel(Transaction)
BgTrans.setGeometry(QtCore.QRect(0, 0, 1041, 345))
BgTrans.setStyleSheet("background-color: rgb(148, 0, 2,.4);border-radius:8px;")
BgTrans.setText("")
BgTrans.setObjectName("BGTrans")
# Item Fonts ( ! Bold )
font = QtGui.QFont()
font.setFamily("Calibri")
font.setPointSize(12)
# Transaction Table
Ui_Trans.TBLTrans = QtWidgets.QTableWidget(Transaction)
Ui_Trans.TBLTrans.setGeometry(QtCore.QRect(10, 11, 1021, 321))
Ui_Trans.TBLTrans.setFont(font)
Ui_Trans.TBLTrans.setStyleSheet("QTableWidget::item{border:1px solid white;}QTableWidget{border:1px solid white;color:white;}")
Ui_Trans.TBLTrans.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
Ui_Trans.TBLTrans.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
Ui_Trans.TBLTrans.setVerticalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
Ui_Trans.TBLTrans.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
Ui_Trans.TBLTrans.setGridStyle(QtCore.Qt.SolidLine)
Ui_Trans.TBLTrans.setObjectName("TBLTrans")
Ui_Trans.TBLTrans.setColumnCount(9) # Fix 9 Columns
Ui_Trans.TBLTrans.horizontalHeader().setVisible(True)
Ui_Trans.TBLTrans.horizontalHeader().setCascadingSectionResizes(False)
Ui_Trans.TBLTrans.horizontalHeader().setDefaultSectionSize(112)
Ui_Trans.TBLTrans.horizontalHeader().setStyleSheet('''::section{background-color:transparent;color:white;border:1px solid white;font-weight:bold;height:50px;font-size:14px;}''')
Ui_Trans.TBLTrans.verticalHeader().setVisible(False)
Ui_Trans.TBLTrans.verticalHeader().setCascadingSectionResizes(False)
Ui_Trans.TBLTrans.verticalHeader().setDefaultSectionSize(35)
Ui_Trans.TBLTrans.verticalHeader().setHighlightSections(False)
# Transaction Table Row slection
Ui_Trans.TBLTrans.selectionModel().selectionChanged.connect(Ui_Trans.TBLTrans_select)
#Table Properties
Ui_Trans.TBLTrans.setColumnWidth(2,400) # Article
Ui_Trans.TBLTrans.setColumnWidth(3,400) # Supplier
Ui_Trans.TBLTrans.setColumnWidth(4,400) # Address
Ui_Trans.TBLTrans.setColumnWidth(5,100) # Unit
Ui_Trans.TBLTrans.setColumnWidth(6,100) # Price
Ui_Trans.TBLTrans.setColumnWidth(7,100) # Quantity
Ui_Trans.TBLTrans.setColumnWidth(8,100) # Amount
# SetText Defaults
_translate = QtCore.QCoreApplication.translate
LBTransTitle.setText(_translate("DashbaordWindow", "Transaction Record"))
Ui_Trans.BtnPrint.setText(_translate("DashbaordWindow", " Print"))
__sortingEnabled = Ui_Trans.TBLTrans.isSortingEnabled()
Ui_Trans.TBLTrans.setSortingEnabled(False)
Ui_Trans.TBLTrans.setSortingEnabled(__sortingEnabled)
# Horizontal Headers
hheader = ['Transaction \n Date','Receipt \n Number','Supplier \n Name','Address','Article','Unit','Price \n Per Unit','Quantity','Amount']
for x in range(0,9):
item = QtWidgets.QTableWidgetItem()
Ui_Trans.TBLTrans.setHorizontalHeaderItem(x, item)
item = Ui_Trans.TBLTrans.horizontalHeaderItem(x)
item.setText(hheader[x])
# Functions
Ui_Trans.BtnPrint.clicked.connect(Ui_Trans.print_trans)
Ui_Trans.BtnBack=BtnBack
Ui_Trans.ProjectTab=ProjectTab