3
\$\begingroup\$

My task was : Create a Python application to display the active status of your IT project. Everyone the project has its own unique number that is generated at the stage of receipt project into the company. The company offers three types of project implementation: Standard Project, 10 Day Project, and Investor Project. "Project for 10 days "has a markup of 60% of the total cost of the project, and" Project for investor ”provides a 20% discount for the customer, if available investor company. If the investment does not meet the deadlines, the company bears losses - 5% of the project cost for each overdue week. The program must provide the user with the following functionality:

-show projects by id

-type of project and his price

-your data must be saved in json format

I want you to give me some recommendations about this code.This is my code.

**#Data_module.py**
import random
import datetime

#dict in which i will save project data
json_data={}
class StandartProject():
    '''Base class of projects'''

    def __init__(self,price,deadline):
        #random indentificator of every project
        self.id=self.create_id()
        #start price of project
        self.price=price
        self.deadline=deadline
        #price after calculating of difference
        self.__endprice=None
        self.handler_end_price()
    def create_id(self):
        while True :
            id = random.randint(10000,99999)
            if id not in json_data:
                return id

    @property
    def endprice(self):
        return self.__endprice

    @endprice.setter
    def endprice(self,value):
        if 0<value:
            self.__endprice=value
        else:
            self.__endprice=0

    def __str__(self):
        return 'Standart'

    def handler_end_price(self):
        '''calculate weeks difference to fine new price'''
        today=datetime.datetime.today()
        deadline=datetime.datetime.strptime(self.deadline,"%d.%m.%Y")
        time_delta=(deadline-today).days # obj delta with attribute days
        if time_delta<0:
            weeks_later=abs(time_delta)//7
            self.endprice=self.price*(1-weeks_later*0.05) #value can be "-" (fixed in property)
        else:
            self.endprice=self.price

class TenDaysProject(StandartProject):
    def __init__(self,price,deadline,bonus=1.6):
        StandartProject.__init__(self,price,deadline)
        self.price*=bonus

    def __str__(self):
        return "TenDays"

class InvestorsProgect(StandartProject):
    def __init__(self,price,deadline,bonus=0.8):
        StandartProject.__init__(self,price,deadline)
        self.price*=bonus

    def __str__(self):
        return "Investors"


#**main_file.py**
import sys
from design import *
from PyQt5 import QtCore, QtGui, QtWidgets
import Data_module
import inspect
import random
import json
from Data_module import json_data

TYPES_PROJECTS_DICT = {cls.__name__: cls for cls in Data_module.__dict__.values()
                       if inspect.isclass(cls) and issubclass(cls, Data_module.StandartProject)}

class MyWin(QtWidgets.QWidget):

    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.setFixedSize(500, 500)
        self.setObjectName('MainWidget')
        self.setStyleSheet('''#MainWidget {
                                background-color: #267;
                            }''')

        # key - str format of project class ; value - class
        for key in TYPES_PROJECTS_DICT:
            self.ui.comboBox_type.addItem(key)

        # self.ui.tabWidget.indexOf(self.ui.tab).clicked.connect(self.print__)
        self.ui.pushButton_add.clicked.connect(self.addProject)

        self.ui.pushButton_find.clicked.connect(self.handler_find_button)
        self.ui.pushButton_clear.clicked.connect(self.ui.textEdit_result.clear)

    # self.ui.pushButton_del_item.clicked.connect(self.handler_del_item)

    def closeEvent(self, event, *args, **kwargs):
        reply = QtWidgets.QMessageBox.question(
            self, "Message",
            "Do you want to save your Projects Data ?",
            QtWidgets.QMessageBox.Save | QtWidgets.QMessageBox.Close ,
            QtWidgets.QMessageBox.Save)
        if reply==QtWidgets.QMessageBox.Save:
            self.write_json_data()
        event.accept()

    def handler_find_button(self):
        id = int(self.ui.lineEdit_id.text())
        if 9999 < id < 100000 and (id in json_data):  # !
            result = ""
            for key, value in json_data[id].items():
                result += str(key) + " = " + str(value) + "\n"
                self.ui.textEdit_result.setText(result)
            '''self.ui.textEdit_result.setText(f"Searched id = {id}"
                                            f"Type = {json_data[id][]}")'''
        else:
            self.ui.textEdit_result.setText("Write correct id :)")
        self.ui.lineEdit_id.setText("")

    def write_one_data_in_table(self, id, data=json_data):
        raw = len(json_data) - 1
        # when our table hasn't any empty rows

        if raw == (self.ui.tableWidget.rowCount() - 1):
            pass
        self.ui.tableWidget.setItem(raw, 0, QtWidgets.QTableWidgetItem(str(id)))
        data = list(json_data[id].values())
        for column in range(len(data)):
            self.ui.tableWidget.setItem(raw, column + 1, QtWidgets.QTableWidgetItem(str(data[column])))

    '''def write_all_date_in_table(self, data=json_data):
        raw = 0
        for key in json_data:
            raw += 1
            self.ui.tableWidget.setItem(raw, 0, QtWidgets.QTableWidgetItem(str(key)))
            tmp_list = list(json_data[key].values())
            for column in range(len(tmp_list)):
                self.ui.tableWidget.setItem(raw, column + 1, QtWidgets.QTableWidgetItem(str(tmp_list[column])))'''

    def addProject(self):

        TYPE, base_price, deadline = self.collectingProjectData()
        obj = TYPES_PROJECTS_DICT[TYPE](base_price, deadline)
        json_data[obj.id] = {"Type": TYPE,
                             "Price": base_price,
                             "EndPrice": obj.endprice,
                             "Deadline": obj.deadline
                             }
        # import pprint
        # pprint.pprint(json_data,indent=4)

        self.write_one_data_in_table(obj.id)

    def write_json_data(self, data=json_data):
        with open("data_file.json", "w") as write_file:
            json.dump(data, write_file)

    '''def get_data_now(self):
        return QtCore.QDate.currentDate()'''

    def collectingProjectData(self):

        TYPE = self.ui.comboBox_type.currentText()
        base_price = self.ui.spinBox_baseprice.value()
        deadline = self.ui.dateEdit_deadline.date().toString("dd.MM.yyyy")
        return TYPE, base_price, deadline


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myapp = MyWin()
    myapp.show()
    sys.exit(app.exec_())

**#design.py**
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(478, 475)
        self.tabWidget = QtWidgets.QTabWidget(Form)
        self.tabWidget.setGeometry(QtCore.QRect(10, 10, 480, 480))
        self.tabWidget.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.tab)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label_tab1_projects = QtWidgets.QLabel(self.tab)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_tab1_projects.setFont(font)
        self.label_tab1_projects.setAlignment(QtCore.Qt.AlignCenter)
        self.label_tab1_projects.setObjectName("label_tab1_projects")
        self.verticalLayout.addWidget(self.label_tab1_projects)
        self.tableWidget = QtWidgets.QTableWidget(self.tab)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(6)
        self.tableWidget.setRowCount(12)
        self.tableWidget.setHorizontalHeaderLabels(["Id", "Type", "Price", "EndPrice", "Deadline", "WorkDoneReally"])
        self.verticalLayout.addWidget(self.tableWidget)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        self.label_tab2_Type = QtWidgets.QLabel(self.tab_2)
        self.label_tab2_Type.setGeometry(QtCore.QRect(40, 60, 91, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_tab2_Type.setFont(font)
        self.label_tab2_Type.setObjectName("label_tab2_Type")
        self.spinBox_baseprice = QtWidgets.QSpinBox(self.tab_2)
        self.spinBox_baseprice.setGeometry(QtCore.QRect(260, 100, 141, 31))
        self.spinBox_baseprice.setMaximum(100000)
        self.spinBox_baseprice.setMinimum(1)
        self.spinBox_baseprice.setObjectName("spinBox_baseprice")
        self.dateEdit_done = QtWidgets.QDateEdit(self.tab_2)
        self.dateEdit_done.setGeometry(QtCore.QRect(260, 200, 141, 31))
        self.dateEdit_done.setMinimumDate(QtCore.QDate(2019, 10, 2))
        self.dateEdit_done.setObjectName("dateEdit_done")
        self.label_tab2_defdline = QtWidgets.QLabel(self.tab_2)
        self.label_tab2_defdline.setGeometry(QtCore.QRect(40, 160, 71, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_tab2_defdline.setFont(font)
        self.label_tab2_defdline.setObjectName("label_tab2_deadline")
        self.label_tab2_workwillbe = QtWidgets.QLabel(self.tab_2)
        self.label_tab2_workwillbe.setGeometry(QtCore.QRect(40, 200, 151, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_tab2_workwillbe.setFont(font)
        self.label_tab2_workwillbe.setObjectName("label_tab2_workwillbe")
        self.comboBox_type = QtWidgets.QComboBox(self.tab_2)
        self.comboBox_type.setGeometry(QtCore.QRect(260, 50, 141, 31))
        self.comboBox_type.setObjectName("comboBox_type")
        self.label_tab2_baseprise = QtWidgets.QLabel(self.tab_2)
        self.label_tab2_baseprise.setGeometry(QtCore.QRect(40, 110, 91, 20))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_tab2_baseprise.setFont(font)
        self.label_tab2_baseprise.setObjectName("label_tab2_baseprise")
        self.label_tab2_addingprojects = QtWidgets.QLabel(self.tab_2)
        self.label_tab2_addingprojects.setGeometry(QtCore.QRect(10, 0, 431, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setItalic(True)
        self.label_tab2_addingprojects.setFont(font)
        self.label_tab2_addingprojects.setAlignment(QtCore.Qt.AlignCenter)
        self.label_tab2_addingprojects.setObjectName("label_tab2_addingprojects")
        self.dateEdit_deadline = QtWidgets.QDateEdit(self.tab_2)
        self.dateEdit_deadline.setGeometry(QtCore.QRect(260, 150, 141, 31))
        self.dateEdit_deadline.setMinimumDateTime(QtCore.QDateTime(QtCore.QDate(2017, 10, 1), QtCore.QTime(0, 0, 0)))
        self.dateEdit_deadline.setMinimumDate(QtCore.QDate(2017, 10, 1))
        self.dateEdit_deadline.setObjectName("dateEdit_deadline")
        self.pushButton_add = QtWidgets.QPushButton(self.tab_2)
        self.pushButton_add.setGeometry(QtCore.QRect(40, 280, 361, 31))
        self.pushButton_add.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.pushButton_add.setObjectName("pushButton_add")
        self.tabWidget.addTab(self.tab_2, "")
        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setObjectName("tab_3")
        self.label_writeid = QtWidgets.QLabel(self.tab_3)
        self.label_writeid.setGeometry(QtCore.QRect(20, 20, 131, 41))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_writeid.setFont(font)
        self.label_writeid.setObjectName("label_writeid")
        self.lineEdit_id = QtWidgets.QLineEdit(self.tab_3)
        self.lineEdit_id.setGeometry(QtCore.QRect(170, 30, 181, 21))
        self.lineEdit_id.setMaxLength(5)
        self.lineEdit_id.setValidator(QtGui.QIntValidator(10000,99999))
        self.lineEdit_id.setObjectName("lineEdit_id")
        self.textEdit_result = QtWidgets.QTextEdit(self.tab_3)
        self.textEdit_result.setGeometry(QtCore.QRect(20, 120, 421, 251))
        self.textEdit_result.setObjectName("textEdit_result")
        self.textEdit_result.setFontPointSize (16)
        self.textEdit_result.setReadOnly(True)
        self.label_result_table = QtWidgets.QLabel(self.tab_3)
        self.label_result_table.setGeometry(QtCore.QRect(20, 80, 421, 21))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_result_table.setFont(font)
        self.label_result_table.setObjectName("label_result_table")
        #self.pushButton_del_item = QtWidgets.QPushButton(self.tab_3)
        #self.pushButton_del_item.setGeometry(QtCore.QRect(20, 390, 191, 23))
        #self.pushButton_del_item.setObjectName("pushButton_del_item")
        self.pushButton_clear = QtWidgets.QPushButton(self.tab_3)
        self.pushButton_clear.setGeometry(QtCore.QRect(224, 390, 211, 23))
        self.pushButton_clear.setObjectName("pushButton_clear")
        self.pushButton_find = QtWidgets.QPushButton(self.tab_3)
        self.pushButton_find.setGeometry(QtCore.QRect(360, 30, 81, 23))
        self.pushButton_find.setObjectName("pushButton_find")
        self.tabWidget.addTab(self.tab_3, "")

        self.retranslateUi(Form)
        self.tabWidget.setCurrentIndex(1)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_tab1_projects.setText(_translate("Form", "Projects "))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Form", "Tab 1"))
        self.label_tab2_Type.setText(_translate("Form", "Type :"))
        self.label_tab2_defdline.setText(_translate("Form", "Dedline :"))
        self.label_tab2_workwillbe.setText(_translate("Form", "Work will be done :"))
        self.label_tab2_baseprise.setText(_translate("Form", "Base price :"))
        self.label_tab2_addingprojects.setText(_translate("Form", "Adding Projects"))
        self.pushButton_add.setText(_translate("Form", "ADD"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Form", "Tab 2"))
        self.label_writeid.setText(_translate("Form", "Write  Id :"))
        self.label_result_table.setText(_translate("Form", "Result table :"))
        #self.pushButton_del_item.setText(_translate("Form", "Delete item"))
        self.pushButton_clear.setText(_translate("Form", "Clear \"Result table\""))
        self.pushButton_find.setText(_translate("Form", "Find"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("Form", "Tab 3"))
\$\endgroup\$
1
\$\begingroup\$

Your data is saved in the file data_file.json, but when you re-enter you do not read the data to put it in thetableWidget.


The handler_find_button method I would start like this:

def handler_find_button(self):
    if not self.ui.lineEdit_id.text():
        self.ui.textEdit_result.setText("Write correct id :)")
        return
        ...

Shaping id randomly will cause you problems sooner or later. This is your key and should never be repeated!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.