Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from tkinter import *
- from widget_factory import *
- from mapped_acc_calculations import *
- from json_file_io import JsonFileIo
- from Opiti.from_excel.classes.global_inc import registry
- from import_excel import *
- class StockInventory(Tk):
- def __init__(self):
- Tk.__init__(self)
- self.account_tree = AccountTree()
- self.widget_factory = WidgetsFactory()
- self.excel_acc_data = ExcelAccData()
- self.mapped_calculations = MappedCalculations()
- self.excel_acc_data.convert_json_data()
- self.acc_data_bycode = self.excel_acc_data.get_acc_data_bycode()
- self.min_top_group_digits = self.excel_acc_data.get_min_top_group_digits()
- self.max_top_group_digits = self.excel_acc_data.get_max_top_group_digits()
- self.max_groups = self.excel_acc_data.get_max_groups()
- self.rpa = {}
- self.rpa_list = [] # Списък[] с редовете както са прочетени от Ексел (и поставени в в JSON)
- self.rpna_assets = self.read_rpna_assets() # Чете от acc_rec_dna
- json_file_io = JsonFileIo(file_name=registry["mapped_account_file_name"])
- acc_data_mapped = json_file_io.read_content() # {"121": ["СК"], "121-13": ["СК"], "121-14": ["СК"],
- if acc_data_mapped is None:
- print("?? acc_data_mapped is NONE!!!")
- self.acc_data_mapped_da = {} # Речник с маркираните сметки с вид 'ДА'
- for acc_code in self.acc_data_bycode:
- self.account_tree.add_code(acc_code) # Захранваме наследственото дърво
- self.acc_data = []
- self.max_depth_rx = 0
- for acc_code in acc_data_mapped:
- acc_types = acc_data_mapped[acc_code]
- # TODO -> 'МЗ' и 'Рх' ако Рх имат Дебитно НС или КС !!!!
- if 'МЗ' in acc_types and len(acc_types) == 1:
- self.acc_data_mapped_da[acc_code] = acc_data_mapped[acc_code]
- depth = self.account_tree.get_depth(acc_code)
- if depth > self.max_depth_rx:
- self.max_depth_rx = depth
- for acc_code in self.acc_data_bycode:
- if acc_code in self.acc_data_mapped_da:
- acc_row = self.acc_data_bycode[acc_code]
- self.acc_data.append(acc_row)
- # -----------------------
- self.acc_rec_mz = {
- 'mat': {'ns': 0, 'ks': 0, 'assets': []},
- 'st': {'ns': 0, 'ks': 0, 'assets': []},
- 'prod': {'ns': 0, 'ks': 0, 'assets': []},
- 'nezpr': {'ns': 0, 'ks': 0, 'assets': []},
- 'mzadv': {'ns': 0, 'ks': 0, 'assets': []},
- 'prod_diff': {'ns': 0, 'ks': 0},
- 'nezpr_diff': {'ns': 0, 'ks': 0},
- 'total_diff': {'ns': 0, 'ks': 0},
- }
- # -------------------------
- self.last_entry = Entry() # Четене на Entry code
- self.acc_data = []
- self.scr_bar = None
- self.term = None
- self.all_accounts = []
- self.list_unadded_accs = []
- self.unadded_spin = ''
- self.selected_accs = [] # Данните, които трябва да се запишат във файл за да се маркират сметките в Treeview
- self.dict_entries = {} # Списък с Ентритата на Активите
- self.get_sums = {}
- self.get_total = {'total': {'od': 0.0, 'oc': 0.0, 'td': 0.0, 'tc': 0.0, 'cd': 0.0, 'cc': 0.0}}
- self.pop_message_answer = ''
- self.total_cd = 0
- # Списъци с индексите на редовете, които юзъра слага като ПДНА или ПДМА
- self.pdna_bag = []
- self.pdma_bag = []
- # TODO -> Главен прозорец
- self.title('Разходи за придобиване на нетекущи активи') # TODO -> Главен прозорец
- self.geometry('1300x600+200+150') # 480
- self.resizable(True, False)
- # self.attributes('-topmost', 'true')
- # TODO -> Label frame top
- self.lab_frame_top = self.widget_factory.get_label_frame(self, 'Импорт на данни')
- self.lab_frame_top.configure(width=540, height=300, padx=1, pady=2, relief='sunken', font=('Timesbd', 12, 'italic') )
- self.lab_frame_top.place(x=10, y=20, )
- # TODO -> LABELS
- self.widget_factory.get_label_un(self, 'Налични сметки:', 650, 1, 'w', 20, 'blue', bg_color=None, bg_border='red')
- self.widget_factory.get_label_un(self.lab_frame_top, 'колони', 270, 16, 'w', 6, 'black', bg_border='red', j='center')
- self.l_mat = self.widget_factory.get_label_un(self.lab_frame_top, 'Кредит по с/ка', 150, 60, 'w', 12, 'black', bg_border='green', j='left')
- self.widget_factory.get_label_un(self.lab_frame_top, 'Оборот Дебит', 150, 90, 'w', 13, 'black', bg_border='red', j='center')
- self.widget_factory.get_label_un(self.lab_frame_top, 'Оборот Кредит', 150, 120, 'w', 13, 'black', bg_border='red', j='center')
- self.l_ks_st = self.widget_factory.get_label_un(self.lab_frame_top, 'Дебит по с/ка', 150, 150, 'w', 12, 'black', bg_border='green', j='left')
- # self.widget_factory.get_label_un(self.lab_frame_top, 'ред:\n(сума)', 460, 1, 'center', 4, 'black', bg_border='green')
- self.widget_factory.get_label_un(self.lab_frame_top, 'Свързване с Excel', 20, 60, 'w', 14, bg_border='green', j='left')
- self.col_entries = {}
- self.col_entries["c_acc"] = self.widget_factory.get_entry(self.lab_frame_top, 280, 60, 3, 'right')
- #self.col_entries["c_acc"].bind("<KeyRelease>", lambda e: self.update_total_sum_ks())
- self.col_entries["od"] = self.widget_factory.get_entry(self.lab_frame_top, 280, 90, 3, 'right')
- # self.ks_mat.bind("<KeyRelease>", lambda e: self.update_total_sum_ks())
- self.col_entries["oc"] = self.widget_factory.get_entry(self.lab_frame_top, 280, 120, 3, 'right')
- self.col_entries["d_acc"] = self.widget_factory.get_entry(self.lab_frame_top, 280, 150, 3, 'right')
- for col_entry_key, col_entry in self.col_entries.items():
- col_entry.bind("<KeyRelease>", lambda e: self.check_import_entries())
- # TODO -> DOWN LABELS
- self.widget_factory.get_label(self.lab_frame_top, 150, 210, 'Редове от:', 10, 'w', font=10)
- self.row_start = self.widget_factory.get_entry(self.lab_frame_top, 240, 205, 4, 'right')
- self.row_start.bind("<KeyRelease>", lambda e: self.check_import_entries())
- self.widget_factory.get_label(self.lab_frame_top, 280, 210, 'до:', 4, 'w', font=10)
- self.row_end = self.widget_factory.get_entry(self.lab_frame_top, 320, 205, 4, 'right')
- self.row_end.bind("<KeyRelease>", lambda e: self.check_import_entries())
- # Button Connect
- self.b_connect = self.widget_factory.get_connection(self.lab_frame_top, 420, 205)
- self.b_connect.bind('<ButtonRelease-1>', lambda e: self.on_excel_connect())
- # Button Start
- self.b_start = self.widget_factory.get_start(self.lab_frame_top, 420, 240)
- self.b_start.config(command=self.on_start_import)
- # TODO -> Label_frame_Bottom
- self.lab_frame_bottom = self.widget_factory.get_label_frame(self, 'Разходи за придобиване на нетекущи активи')
- self.lab_frame_bottom.configure(width=540, height=200, padx=1, pady=2, relief='sunken', font=('Timesbd', 12, 'italic'), fg='darkgreen')
- self.lab_frame_bottom.place(x=10, y=350)
- self.widget_factory.get_label_un(self.lab_frame_bottom, '2022\n(хил.лв)', 275, 20, 'w', 6, 'black', bg_border='red', j='center')
- self.widget_factory.get_label_un(self.lab_frame_bottom, '2023\n(хил.лв)', 350, 20, 'center', 6, 'black', bg_border='red', j='center')
- self.widget_factory.get_label_un(self.lab_frame_bottom, '2023\n(лева)', 420, 20, 'center', 11, 'black', bg_border='green')
- self.widget_factory.get_label_un(self.lab_frame_bottom, 'Разходи за ПНА:', 20, 80, 'w', 15, bg_border='green', j='left')
- self.widget_factory.get_label(self.lab_frame_bottom, 20, 120, '613', 100, 'w')
- self.ns_prod_diff = self.widget_factory.get_entry(self.lab_frame_bottom, 280, 80, 5, 'right')
- # self.ns_prod_diff.bind("<KeyRelease>", lambda e: self.update_ns_diff('ns_prod_diff'))
- # TODO 1-wo entry
- self.ks_prod_diff = self.widget_factory.get_entry(self.lab_frame_bottom, 360, 80, 5, 'right')
- # self.ks_prod_diff.bind("<KeyRelease>", lambda e: self.update_total_diff())
- self.l_prod_diff = self.widget_factory.get_label_un(self.lab_frame_bottom, '0', 420, 80, 'e', 11, 'black', bg_border='green', j='left')
- # TODO TREEVIEW
- self.tv_frame = Frame(self) # 'open_di', 'turn_di', 'turn_ci':, "close_di": -> ширината на колоните в Treeview
- self.tv_frame.place(x=560, y=30)
- self.dict_columns = {"c_acc": 'Кредит по с/ка', "od": 'Оборот Дт', 'oc': 'Оборот Кт', 'd_acc': 'Дебит по с/ка'}
- self.treeview_acc = self.widget_factory.get_acc_report_treeview(self.tv_frame, **self.dict_columns)
- self.treeview_acc.config(selectmode='browse')
- # self.treeview_acc.bind('<ButtonRelease-1>', lambda e: self.on_selected_acc(self.treeview_acc))
- self.treeview_acc.pack(side=LEFT)
- # # TODO SCROLLBAR
- # self.scr_bar = Scrollbar(self.tv_frame, orient=VERTICAL)
- # self.scr_bar.pack(side=RIGHT, fill=Y)
- # self.treeview_acc.config(yscrollcommand=self.scr_bar.set)
- # self.scr_bar.config(command=self.treeview_acc.yview, bg="red", activebackground="orange")
- # TODO Spinboxes
- # self.min_spin_2 = self.min_top_group_digits
- # self.max_spin_2 = self.max_top_group_digits + self.max_groups
- self.var_spin_1 = StringVar(self)
- self.list_spin_1 = []
- if self.rpna_assets:
- self.list_spin_1 = self.rpna_assets
- print("self.list_spin_1", self.list_spin_1)
- self.spin_1 = self.widget_factory.get_list_spinbox(self, self.list_spin_1, 12, 'center',
- self.var_spin_1, 560, 4)
- self.spin_1.configure(command=lambda: self.fill_treeview())
- # max_spin_2 = self.max_depth_rx
- # if max_spin_2 < self.min_spin_2:
- # max_spin_2 = self.min_spin_2
- # print("self.min_spin_2", self.min_spin_2, "self.max_depth_rx", self.max_depth_rx, "max_spin_2", max_spin_2)
- # self.var_spin_2 = StringVar(self, value=str(max_spin_2))
- # self.spin_1 = self.widget_factory.get_spinbox(self, self.min_spin_2, str(max_spin_2), 9,
- # 'center', self.var_spin_2, 560, 4)
- # self.spin_1.configure(command=lambda: self.fill_treeview())
- # TODO Buttons
- # Button Помощ
- self.b_help = self.widget_factory.get_help_button(self, 20, 555)
- self.b_help.bind('<ButtonRelease-1>')
- # Button Корекции
- self.b_note = self.widget_factory.get_correction_button(self, 350, 555)
- #self.b_note.bind('<ButtonRelease-1>', lambda e: self.on_correction())
- # Button Добави
- self.b_add = self.widget_factory.get_save_button(self, 456, 555, text='ДОБАВИ') # 460, 435
- self.b_add.bind('<ButtonRelease-1>', lambda e: self.on_add())
- # Button Save
- self.b_save = self.widget_factory.get_ok_button(self, 830, 555)
- self.b_save.bind('<ButtonRelease-1>', lambda e: self.on_save())
- # Button Отказ
- self.b_exit = self.widget_factory.get_correction_esc(self, 930, 555)
- self.b_exit.config(command=self.destroy)
- def on_start_import(self):
- test_cols = {'c_acc': 'a', 'od': 'b', 'oc': 'c', 'd_acc': 'd'}
- test_rows = {"first": 5, "last": 10}
- #acc = self.var_spin_1.get() # сметката, която е в момента в spinbox-а
- file_path = "..\\rpna_test.txt"
- import_excel = ImportExcel()
- import_excel.defineCols(test_cols)
- import_excel.defineRows(test_rows["first"], test_rows["last"])
- import_excel.defineFilePath(file_path)
- print("Начало импорт")
- import_excel.run_import()
- print("Край импорт")
- print("Начало четене от JSON")
- #self.rpa[acc] = []
- self.rpa_list = []
- try:
- json_file_io = JsonFileIo(file_name=file_path)
- #self.update()
- #self.update_idletasks()
- tmp = json_file_io.read_content()
- if tmp is not None:
- self.rpa_list = tmp
- #self.rpa[acc] = tmp
- #print(f"self.rpa[{acc}] ", self.rpa[acc])
- print(f"self.rpa_list ", self.rpa_list)
- #self.refill_form()
- self.update()
- self.update_idletasks()
- print(f"Успяхме да прочетем {file_path}")
- except:
- print(f"Не можахме да прочетем {file_path}")
- pass
- print("Край четене от JSON")
- self.fill_treeview()
- def set_pop_message_answer(self, answer):
- self.pop_message_answer = answer
- def on_save(self):
- # TODO -> Попълваме Началното салдо, въведено от потребителя:
- # for entry in self.user_ns:
- # self.acc_rec_rx[entry]['ns'] = self.user_ns[entry]
- # for entry in self.user_ns_amo:
- # self.acc_rec_rx[entry]['ns_amo'] = self.user_ns_amo[entry]
- # TODO -> Попълваме сметките, по Ентрита на активи и амортизации
- if not self.dict_entries: # Речника е празен
- for entry in self.acc_rec_rx:
- self.acc_rec_rx[entry]['assets'].clear()
- # if not self.dict_entries_amo: # Речника е празен
- # for entry in self.acc_rec_rx:
- # self.acc_rec_rx[entry]['amort'].clear()
- for entry in self.dict_entries:
- if self.dict_entries[entry] is None:
- self.dict_entries[entry] = []
- self.acc_rec_rx[entry]['assets'] = self.dict_entries[entry]
- # for entry in self.dict_entries_amo:
- # if self.dict_entries_amo[entry] is None:
- # self.dict_entries_amo[entry] = []
- # self.acc_rec_rx[entry]['amort'] = self.dict_entries_amo[entry]
- # TODO -> попълване на сумите на преоценката
- # for entry in self.assets_re:
- # for dir in self.assets_re[entry]:
- # self.acc_rec_rx[entry]['assets_re'][dir] = self.assets_re[entry][dir]
- # for entry in self.amort_re:
- # for dir in self.amort_re[entry]:
- # self.acc_rec_rx[entry]['amort_re'][dir] = self.amort_re[entry][dir]
- # print('self.acc_rec_rx: ', self.acc_rec_rx)
- json_file_io = JsonFileIo(file_name=registry['mz_import_form_acc_rec_mz_file_name'])
- json_file_io.write_content(self.acc_rec_rx)
- # TODO -> Проверка за недобавена сметка и съобщение !!!!!
- if len(self.list_unadded_accs) > 0:
- # TODO -> Показва pop_message "Има недобавени сметки !
- pop_message = self.widget_factory.get_pop_message(self, lambda answer: self.set_pop_message_answer(answer),
- "Има недобавени сметки !", 1, 'red')
- self.wait_window(pop_message.pop)
- # TODO -> Ако "ДА"
- self.destroy()
- return
- else:
- pop_message = self.widget_factory.get_pop_message(self, lambda answer: self.set_pop_message_answer(answer),
- "Всички сметки са добавени !", 1, 'green')
- self.wait_window(pop_message.pop)
- # TODO -> Ако "ДА"
- self.destroy()
- return
- def on_correction(self):
- # TODO -> Махаме маркировката на Treeview и забраната за селекция
- for code in self.selected_accs:
- self.treeview_acc.tag_configure(code, background='lightgrey')
- self.selected_accs.clear()
- # TODO -> Изтриваме стойностите на речника, на ентритата и лейбълите
- self.dict_entries.clear()
- self.get_total = {'total': {'od': 0.0, 'oc': 0.0, 'td': 0.0, 'tc': 0.0, 'cd': 0.0, 'cc': 0.0}}
- self.ns_mat.delete(0, 'end')
- self.ks_mat.delete(0, 'end')
- self.l_mat['text'] = '0.00'
- self.ns_st.delete(0, 'end')
- self.ks_st.delete(0, 'end')
- self.l_ks_st['text'] = '0.00'
- self.ns_prod.delete(0, 'end')
- self.ks_prod.delete(0, 'end')
- self.l_ks_prod['text'] = '0.00'
- self.ns_nezpr.delete(0, 'end')
- self.ks_nezpr.delete(0, 'end')
- self.l_ks_nezpr['text'] = '0.00'
- self.ns_mzadv.delete(0, 'end')
- self.ks_mzadv.delete(0, 'end')
- self.l_ks_mzadv['text'] = '0.00'
- self.ns_prod_diff.delete(0, 'end')
- self.ks_prod_diff.delete(0, 'end')
- self.l_prod_diff['text'] = '0.00'
- self.ns_nezpr_diff.delete(0, 'end')
- self.ks_nezpr_diff.delete(0, 'end')
- self.l_nezpr_diff['text'] = '0.00'
- self.tot_ns_diff.delete(0, 'end')
- self.l_tot_ks_diff['text'] = '0'
- self.tot_ns_diff.configure(state='normal')
- self.ns_prod_diff.configure(state='normal')
- self.ns_nezpr_diff.configure(state='normal')
- self.fill_labels()
- self.fill_treeview()
- def update_total_sum_ks(self):
- ks_mat = self.ks_mat.get()
- ks_st = self.ks_st.get()
- ks_prod = self.ks_prod.get()
- ks_nezpr = self.ks_nezpr.get()
- ks_mzadv = self.ks_mzadv.get()
- dict_ks = {'ks_mat': ks_mat, 'ks_st': ks_st, 'ks_prod': ks_prod, 'ks_nezpr': ks_nezpr, 'ks_mzadv': ks_mzadv}
- for _ in range(len(dict_ks)):
- for ks in dict_ks:
- try:
- int(dict_ks[ks])
- dict_ks[ks] = int(dict_ks[ks])
- except:
- dict_ks[ks] = 0
- total_ks = dict_ks['ks_mat'] + dict_ks['ks_st'] + dict_ks['ks_prod'] + dict_ks['ks_nezpr'] + dict_ks['ks_mzadv']
- if total_ks != self.total_cd:
- self.l_user_cd_total.configure(fg='red')
- else:
- self.l_user_cd_total.configure(fg='black')
- def update_total_sum_ns(self):
- ns_mat = self.ns_mat.get()
- ns_st = self.ns_st.get()
- ns_prod = self.ns_prod.get()
- ns_nezpr = self.ns_nezpr.get()
- ns_mzadv = self.ns_mzadv.get()
- dict_ns = {'ns_mat': ns_mat, 'ns_st': ns_st, 'ns_prod': ns_prod, 'ns_nezpr': ns_nezpr, 'ns_maadv': ns_mzadv}
- for _ in range(len(dict_ns)):
- for ns in dict_ns:
- try:
- int(dict_ns[ns])
- dict_ns[ns] = int(dict_ns[ns])
- except:
- dict_ns[ns] = 0
- total_ns = dict_ns['ns_mat'] + dict_ns['ns_st'] + dict_ns['ns_prod'] + dict_ns['ns_nezpr'] + dict_ns['ns_maadv']
- self.l_user_od_total['text'] = total_ns
- def update_total_diff(self):
- prod_diff = self.ks_prod_diff.get()
- nezpr_diff = self.ks_nezpr_diff.get()
- try:
- int(nezpr_diff)
- nezpr_diff = int(nezpr_diff)
- except:
- nezpr_diff = 0
- try:
- int(prod_diff)
- prod_diff = int(prod_diff)
- except:
- prod_diff = 0
- if (prod_diff >= 0 and nezpr_diff >= 0) or (prod_diff <= 0 and nezpr_diff <= 0):
- self.l_tot_ks_diff['text'] = prod_diff + nezpr_diff
- else:
- self.l_tot_ks_diff['text'] = 'n/a'
- def update_ns_diff(self, name_entry):
- ns_prod = self.ns_prod_diff.get()
- ns_nezpr = self.ns_nezpr_diff.get()
- tot_ns = self.tot_ns_diff.get()
- print(f'ns_prod: {ns_prod} ns_nezpr: {ns_nezpr} tot_ns: {tot_ns}')
- if ns_prod == '' and ns_nezpr == '' and tot_ns == '':
- self.tot_ns_diff.configure(state='normal')
- self.ns_prod_diff.configure(state='normal')
- self.ns_nezpr_diff.configure(state='normal')
- elif name_entry == 'ns_prod_diff' or name_entry == 'ns_nezpr_diff':
- self.tot_ns_diff.configure(state='disabled')
- elif name_entry == 'tot_ns_diff':
- self.ns_prod_diff.configure(state='disabled')
- self.ns_nezpr_diff.configure(state='disabled')
- def round_1000(self, sum):
- try:
- sum = float(sum)
- except:
- sum = 0.0
- sum_1000 = float(round(sum / 1000))
- return sum_1000
- def fill_labels(self):
- for entry in self.dict_entries:
- if self.dict_entries[entry] is None:
- self.dict_entries[entry] = []
- if len(self.dict_entries) > 0:
- self.get_sums, self.get_total = self.mapped_calculations.get_sum_list_accounts(self.dict_entries)
- for entr in self.get_sums:
- if entr == 'mat':
- self.l_mat['text'] = f"{self.get_sums['mat']['cd']:,.2f}".replace(',', ' ')
- sum = self.get_sums['mat']['cd']
- round_sum = int(self.round_1000(sum))
- self.ks_mat.delete(0, 'end')
- self.ks_mat.insert(0, round_sum)
- elif entr == 'st':
- self.l_ks_st['text'] = f"{self.get_sums['st']['cd']:,.2f}".replace(',', ' ')
- sum = self.get_sums['st']['cd']
- round_sum = int(self.round_1000(sum))
- self.ks_st.delete(0, 'end')
- self.ks_st.insert(0, round_sum)
- elif entr == 'prod':
- self.l_ks_prod['text'] = f"{self.get_sums['prod']['cd']:,.2f}".replace(',', ' ')
- sum = self.get_sums['prod']['cd']
- round_sum = int(self.round_1000(sum))
- self.ks_prod.delete(0, 'end')
- self.ks_prod.insert(0, round_sum)
- elif entr == 'nezpr':
- self.l_ks_nezpr['text'] = f"{self.get_sums['nezpr']['cd']:,.2f}".replace(',', ' ')
- sum = self.get_sums['nezpr']['cd']
- round_sum = int(self.round_1000(sum))
- self.ks_nezpr.delete(0, 'end')
- self.ks_nezpr.insert(0, round_sum)
- elif entr == 'mzadv':
- self.l_ks_mzadv['text'] = f"{self.get_sums['mzadv']['cd']:,.2f}".replace(',', ' ')
- sum = self.get_sums['mzadv']['cd']
- round_sum = int(self.round_1000(sum))
- self.ks_mzadv.delete(0, 'end')
- self.ks_mzadv.insert(0, round_sum)
- self.total_cd = self.round_1000(self.get_total['total']['cd'])
- self.l_user_cd_total['text'] = f"{self.total_cd:,.0f}".replace(',', ' ')
- ks_mat = self.ks_mat.get()
- ks_st = self.ks_st.get()
- ks_prod = self.ks_prod.get()
- ks_nezpr = self.ks_nezpr.get()
- ks_mzadv = self.ks_mzadv.get()
- dict_ks = {'ks_mat': ks_mat, 'ks_st': ks_st, 'ks_prod': ks_prod, 'ks_nezpr': ks_nezpr, 'ks_mzadv': ks_mzadv}
- for _ in range(len(dict_ks)):
- for ks in dict_ks:
- try:
- int(dict_ks[ks])
- dict_ks[ks] = int(dict_ks[ks])
- except:
- dict_ks[ks] = 0
- total_ks = dict_ks['ks_mat'] + dict_ks['ks_st'] + dict_ks['ks_prod'] + dict_ks['ks_nezpr'] + dict_ks['ks_mzadv']
- if total_ks != int(self.total_cd):
- self.l_user_cd_total.configure(fg='red')
- else:
- self.l_user_cd_total.configure(fg='black')
- self.l_cd_total['text'] = f"{self.get_total['total']['cd']:,.2f}".replace(',', ' ')
- # TODO -> Попълване на долната таблица
- # TODO -> Изменение на продукцията
- suma_p = suma = 0
- for ent in self.dict_entries:
- if ent == 'prod' and len(self.dict_entries['prod']) > 0:
- prod_leva = self.mapped_calculations.sum_by_accs(self.dict_entries['prod'])
- suma_p = prod_leva['cd'] - prod_leva['od']
- suma_1000 = suma_p / 1000
- summa = f"{suma_p:,.2f}".replace(',', ' ')
- self.l_prod_diff['text'] = summa
- suma_1000 = f"{suma_1000:,.0f}".replace(',', ' ')
- self.ks_prod_diff.delete(0, 'end')
- self.ks_prod_diff.insert(0, suma_1000)
- # TODO -> Изменение на незавършеното производство
- elif ent == 'nezpr' and len(self.dict_entries['nezpr']) > 0:
- prod_leva = self.mapped_calculations.sum_by_accs(self.dict_entries['nezpr'])
- suma = prod_leva['cd'] - prod_leva['od']
- suma_1000 = suma / 1000
- summa = f"{suma:,.2f}".replace(',', ' ')
- self.l_nezpr_diff['text'] = summa
- suma_1000 = f"{suma_1000:,.0f}".replace(',', ' ')
- self.ks_nezpr_diff.delete(0, 'end')
- self.ks_nezpr_diff.insert(0, suma_1000)
- # TODO -> Изменения в TOTAL
- if (suma_p >= 0 and suma >= 0) or (suma_p <= 0 and suma <= 0):
- tot_diff_leva = suma_p + suma
- self.l_tot_diff_leva['text'] = f'{tot_diff_leva:,.2f}'.replace(',', ' ')
- self.l_tot_ks_diff['text'] = f'{tot_diff_leva / 1000:,.0f}'.replace(',', ' ')
- else:
- self.l_tot_diff_leva['text'] = 'n/a'
- self.l_tot_ks_diff['text'] = 'n/a'
- def on_add(self):
- acc_code = self.last_entry.get() # '203'
- if acc_code is None or acc_code == '':
- return
- tuple_accs = self.treeview_acc.selection()
- self.selected_accs.append(tuple_accs[0])
- # TODO -> На името на Entry да добавим сметката
- name_entry = self.last_entry.winfo_name()
- if name_entry not in self.dict_entries:
- self.dict_entries[name_entry] = ()
- self.dict_entries[name_entry] += self.treeview_acc.selection() # Добавям маркираната сметка
- # TODO -> Добавяне на децата и родителите на добавената сметка
- all_children = self.account_tree.get_all_children(acc_code) # all_children: ['200', '203', '205']
- all_parents = self.account_tree.get_all_parents(acc_code) # acc_code = 223
- self.selected_accs.extend(all_children)
- self.selected_accs.extend(all_parents)
- # TODO -> След добавяне да се изпразват всички ентрита, а не само добавеното !!!!!
- if self.e_mat.get() != '': self.e_mat.delete(0, 'end')
- if self.e_st.get() != '': self.e_st.delete(0, 'end')
- if self.e_prod.get() != '': self.e_prod.delete(0, 'end')
- if self.e_nezpr.get() != '': self.e_nezpr.delete(0, 'end')
- if self.e_mzadv.get() != '': self.e_mzadv.delete(0, 'end')
- self.fill_labels()
- # TODO -> Попълваме Treeview
- self.fill_treeview()
- def verify_selection(self): # Забрана за маркиране
- for code in self.selected_accs:
- if self.treeview_acc.exists(code):
- self.treeview_acc.selection_remove(code)
- def on_selected_acc(self, source_treeview):
- self.verify_selection()
- current_item = source_treeview.focus()
- if current_item in self.selected_accs: # <class 'list'>
- return
- values = source_treeview.item(current_item)["values"]
- if not isinstance(values, list):
- return
- code = values[0]
- self.last_entry.delete(0, END)
- self.last_entry.insert(0, code)
- def entry_on_focus(self, entry):
- self.last_entry = entry
- def on_entry_key_release(self, entry):
- self.last_entry = entry
- entry_text = entry.get()
- if len(entry_text) < 2:
- self.fill_treeview()
- return
- term = entry_text
- self.fill_treeview(term=term)
- def read_rpna_assets(self):
- try:
- json_file_io = JsonFileIo(file_name=registry["dna_import_form_acc_rec_dna_file_name"])
- tmp_acc_rec_dna = json_file_io.read_content()
- if tmp_acc_rec_dna is not None:
- return tmp_acc_rec_dna["rpna"]["assets"]
- #print("self.rpna_assets", self.rpna_assets)
- #self.refill_form()
- except:
- print("Не можахме да прочетем self.rpna_assets")
- pass
- return None
- def mz(self):
- # try:
- # json_file_io = JsonFileIo(file_name=registry["mz_import_form_acc_rec_mz_file_name"])
- # tmp_acc_rec_rx = json_file_io.read_content()
- # if tmp_acc_rec_rx is not None:
- # self.acc_rec_rx = tmp_acc_rec_rx
- # self.refill_form()
- # except:
- # pass
- #self.fill_treeview()
- self.mainloop()
- def refill_form(self):
- # TODO -> Попълваме Treeview с маркирани и забранени за селектиране сметки
- for entry in self.acc_rec_rx:
- self.dict_entries[entry] = self.acc_rec_rx[entry]['assets']
- for entry in self.acc_rec_rx:
- self.dict_entries_amo[entry] = self.acc_rec_rx[entry]['amort']
- # TODO -> Попълваме сметките, децата и родителите на сметките в self.selected_accs, self.selected_accs_amo
- for entry_name in self.dict_entries:
- for acc_code in self.dict_entries[entry_name]:
- if acc_code not in self.selected_accs:
- self.selected_accs.append(acc_code)
- all_children = self.account_tree.get_all_children(acc_code) # all_children:['200', '203'']
- all_parents = self.account_tree.get_all_parents(acc_code) # acc_code = 223 all_parents:['22',]
- self.selected_accs.extend([a for a in all_children if a not in self.selected_accs])
- self.selected_accs.extend([a for a in all_parents if a not in self.selected_accs])
- # for entry_name in self.dict_entries_amo:
- # for acc_code in self.dict_entries_amo[entry_name]:
- # if acc_code not in self.selected_accs_amo:
- # self.selected_accs_amo.append(acc_code)
- # all_children = self.account_tree.get_all_children(acc_code) # all_children:['200', '203',]
- # all_parents = self.account_tree.get_all_parents(acc_code)
- # self.selected_accs_amo.extend([a for a in all_children if a not in self.selected_accs_amo])
- # self.selected_accs_amo.extend([a for a in all_parents if a not in self.selected_accs_amo])
- # TODO -> Попълваме Ентритата с НС user_ns и user_ns_amo
- for entry_name in self.user_ns:
- self.user_ns[entry_name] = self.acc_rec_rx[entry_name]['ns']
- if self.user_ns['adp'] > 0:
- self.user_adp.insert(0, self.user_ns['adp'])
- if self.user_ns['pzp'] > 0:
- self.user_pzp.insert(0, self.user_ns['pzp'])
- if self.user_ns['adas'] > 0:
- self.user_a.insert(0, self.user_ns['a'])
- if self.user_ns['pzas'] > 0:
- self.user_pzas.insert(0, self.user_ns['pzas'])
- if self.user_ns['di'] > 0:
- self.user_di.insert(0, self.user_ns['di'])
- if self.user_ns['drz'] > 0:
- self.user_drz.insert(0, self.user_ns['drz'])
- if self.user_ns['isa'] > 0:
- self.user_isa.insert(0, self.user_ns['isa'])
- for entry_name in self.user_ns_amo:
- self.user_ns_amo[entry_name] = self.acc_rec_rx[entry_name]['ns_amo']
- if self.user_ns_amo['di'] > 0:
- self.user_amo_di.insert(0, self.user_ns_amo['di'])
- # TODO -> Попълваме Ентритата с Преоценките
- print('self.assets_re: ', self.assets_re)
- for entry in self.assets_re:
- for dir in self.assets_re[entry]:
- self.assets_re[entry][dir] = self.acc_rec_rx[entry]['assets_re'][dir]
- print('self.assets_re след refill: ', self.assets_re)
- if self.assets_re['adp']['inc'] > 0:
- self.turn_d_adp.insert(0, self.assets_re['adp']['inc'])
- if self.assets_re['adp']['dec'] > 0:
- self.turn_c_adp.insert(0, self.assets_re['adp']['dec'])
- if self.assets_re['pzp']['inc'] > 0:
- self.turn_d_pzp.insert(0, self.assets_re['pzp']['inc'])
- if self.assets_re['pzp']['dec'] > 0:
- self.turn_c_pzp.insert(0, self.assets_re['pzp']['dec'])
- if self.assets_re['adas']['inc'] > 0:
- self.turn_d_adas.insert(0, self.assets_re['adas']['inc'])
- if self.assets_re['adas']['dec'] > 0:
- self.turn_c_adas.insert(0, self.assets_re['adas']['dec'])
- if self.assets_re['pzas']['inc'] > 0:
- self.turn_d_pzas.insert(0, self.assets_re['pzas']['inc'])
- if self.assets_re['pzas']['dec'] > 0:
- self.turn_c_pzas.insert(0, self.assets_re['pzas']['dec'])
- if self.assets_re['di']['inc'] > 0:
- self.turn_d_di.insert(0, self.assets_re['di']['inc'])
- if self.assets_re['di']['dec'] > 0:
- self.turn_c_di.insert(0, self.assets_re['di']['dec'])
- if self.assets_re['drz']['inc'] > 0:
- self.turn_d_drz.insert(0, self.assets_re['drz']['inc'])
- if self.assets_re['drz']['dec'] > 0:
- self.turn_c_drz.insert(0, self.assets_re['drz']['dec'])
- if self.assets_re['isa']['inc'] > 0:
- self.turn_d_isa.insert(0, self.assets_re['isa']['inc'])
- if self.assets_re['isa']['dec'] > 0:
- self.turn_c_isa.insert(0, self.assets_re['isa']['dec'])
- for entry in self.amort_re:
- for dir in self.amort_re[entry]:
- self.amort_re[entry][dir] = self.acc_rec_rx[entry]['amort_re'][dir]
- print('self.amort_re след refill: ', self.amort_re)
- if self.amort_re['di']['inc'] > 0:
- self.turn_d_amo_di.insert(0, self.amort_re['di']['inc'])
- if self.amort_re['di']['dec'] > 0:
- self.turn_c_amo_di.insert(0, self.amort_re['di']['dec'])
- def fill_treeview(self, term=None):
- self.treeview_acc.delete(*self.treeview_acc.get_children()) # Вградена функция за изтриване на Treeview
- # TODO -> Spinboxes
- #self.unadded_spin = self.var_spin_1.get() # Взима стойността на спинбокса с сметките от rpdna_assets
- #spin_2 = int(self.var_spin_2.get())
- #self.all_accounts.extend(self.selected_accs)
- #self.list_unadded_accs = self.account_tree.get_unadded_acc(self.all_accounts, self.acc_data_mapped_da)
- count_rows = 0
- for xl_row_idx, xl_row in enumerate(self.rpa_list):
- tw_row = [xl_row['c_acc'], xl_row['od'], xl_row['oc'], xl_row['d_acc']]
- count_rows += 1
- # Понеже нямаме "естествен" идентификатор на реда,
- # за такъв ползваме поредния номер на реда както е взет от Ексел
- tags = xl_row_idx
- iid = tags
- self.treeview_acc.insert('', END, values=tw_row, tags=tags, iid=iid) # ????
- self.treeview_acc.config(height=count_rows)
- if count_rows > 20:
- self.treeview_acc.configure(height=20)
- # for code in self.selected_accs: # Оцветяване на добавените сметки
- # if self.treeview_acc.exists(code):
- # self.treeview_acc.tag_configure(code, background='powderblue')
- # count_rows = 0
- # for acc_code in self.acc_data_bycode:
- # if acc_code not in self.acc_data_mapped_da:
- # continue
- # if term is not None: # Искаме само сметките дето кода им започва с term
- # term_len = len(term)
- # code_piece = self.acc_data_bycode[acc_code]['code'][0:term_len]
- # # Ако сметката не започва с term
- # if term != code_piece:
- # continue # прескачаме тая сметка, не отговаря на търсеното
- # # TODO -> Ако spin_1 = 'недобавени' -> извежда само недобавените сметки в ентритата
- # # if self.unadded_spin == 'недобавени':
- # # if acc_code not in self.list_unadded_accs:
- # # continue
- # # TODO -> spin_2 type of spin_2: <class 'int'>
- # groups_in_acc_code = re.findall('[0-9]+', acc_code) # Връща list със групите на сметката
- # top_group = groups_in_acc_code[0]
- # depth = self.account_tree.get_depth(acc_code)
- # if len(top_group) > spin_2 or depth > spin_2:
- # continue
- #
- #
- # count_rows += 1
- # row = [self.acc_data_bycode[acc_code]['code'],
- # self.acc_data_bycode[acc_code]['name'],
- # self.acc_data_bycode[acc_code]['str_open_d'],
- # self.acc_data_bycode[acc_code]['str_turn_d'],
- # self.acc_data_bycode[acc_code]['str_turn_c'],
- # self.acc_data_bycode[acc_code]['str_close_d']]
- # tags = acc_code
- # iid = acc_code
- # self.treeview_acc.insert('', END, values=row, tags=tags, iid=iid) # ????
- # self.treeview_acc.config(height=count_rows)
- # if count_rows > 20:
- # self.treeview_acc.configure(height=20)
- # for code in self.selected_accs: # Оцветяване на добавените сметки
- # if self.treeview_acc.exists(code):
- # self.treeview_acc.tag_configure(code, background='powderblue')
- def import_form(self):
- pass
- def set_entry_good(self, entry, is_good):
- if is_good:
- entry.configure(bg='white')
- else:
- entry.configure(bg='red')
- def check_import_entries(self):
- is_good = True
- start_val = self.row_start.get().strip()
- try:
- start_val = int(start_val)
- self.set_entry_good(self.row_start, True)
- except:
- self.set_entry_good(self.row_start, False)
- is_good = False
- end_val = self.row_end.get().strip()
- try:
- end_val = int(end_val)
- self.set_entry_good(self.row_end, True)
- except:
- self.set_entry_good(self.row_end, False)
- is_good = False
- if isinstance(start_val, int) and isinstance(end_val, int):
- if start_val > end_val:
- self.set_entry_good(self.row_start, False)
- self.set_entry_good(self.row_end, False)
- is_good = False
- else:
- self.set_entry_good(self.row_start, True)
- self.set_entry_good(self.row_end, True)
- for col_key, col_entry in self.col_entries.items():
- col_value = col_entry.get().strip()
- print("col_value", col_value)
- if col_value == "":
- self.set_entry_good(col_entry, False)
- is_good = False
- else:
- self.set_entry_good(col_entry, True)
- return is_good
- def on_excel_connect(self):
- is_good = self.check_import_entries()
- if not is_good:
- return
- global col_results
- col_results = {} # Списък с резултатите
- first_row = str(self.row_start.get())
- for ent_key in self.col_entries:
- ent = self.col_entries[ent_key]
- result = str(ent.get())
- col_results[ent_key] = result
- # Тук col_results е напр {"c_acc": "A", "od": "B", "oc": "C", "d_acc": "H"}
- #print(col_entries)
- #print(row_entries)
- print(col_results)
- y = 60
- for c_key in col_results:
- c = col_results[c_key]
- z_address = f'{c}{first_row}'
- z = Range(z_address).value
- if z is None or z == 0.0:
- z = int(0)
- border_colour = Frame(self.lab_frame_top, background='white')
- border_colour.pack(padx=40, pady=40)
- border_colour.place(x=320, y=y)
- l = Label(border_colour, text=z, font=('Times New Roman', 10, 'italic'), padx=5, pady=5, bd=-1, width=20,
- anchor='w')
- l.pack(padx=0, pady=(0, 1))
- y += 30
- if __name__ == '__main__':
- mz = StockInventory()
- mz.mz()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement