class PriceMasterExporter(Exporter): def __init__(self, main): super().__init__(main) self.toplevel.title('Создать шаблон базы данных прайс-мастера') self.db = main.db lblProvider = Label(self.frmFields, text='Выберите поставщика') self.cmbProvider = Searchbox( master=self.frmFields, postcommand=self.update_provider_list, source = [d['name'] for d in self.db.data['provider_list']], width=32) self.lblHint = Label(self.frmFields) lblProvider.grid(row=0, **self.grd.cl1_pdSt) self.cmbProvider.grid(row=1, **self.grd.cl1_pdSt) self.lblHint.grid(row=2, **self.grd.cl1_pdSt) self.okButton['text'] = 'Сохранить как' self.okButton['command'] = self.saveFile hintA = 'Поле поставщик — раскрывающийся список с вариантами выбора и встроенным поиском.' hintB = 'Клавиши ↑, ↓ — раскрыть список и перемещаться по вариантам, Esc — скрыть, Enter — выбрать.' hintC = 'Чтобы вернуть все варианты — очистите соответствующее поле ввода.' self.lblHint['text'] = '\n%s\n\n%s\n\n%s' % (hintA, hintB, hintC) self.toplevel.bind('<Configure>', self.hint_resize) def hint_resize(self, event): self.lblHint['wraplength'] = self.toplevel.winfo_reqwidth() - 8 def update_provider_list(self, event=None): values = [d['name'] for d in self.db.data['provider_list']] self.cmbProvider.source = values self.cmbProvider.filter_values() def clear(self): self.cmbProvider.set('') self.cmbProvider.delete(0, END) def fillAndShow(self): self.clear() self.show() def saveFile(self): data = self.db.data.copy() data['provider'] = None data['price_list'] = [] del(data['provider_list']) prvName = self.trn.getNameSting(self.cmbProvider.get()) path = asksaveasfilename( defaultextension='.pmt', initialfile=prvName+'.pmt', filetypes=[('Шаблон базы данных прайс-мастера', '.pmt')], parent=self.toplevel) if prvName and path: for record in self.db.data['provider_list']: if prvName == record['name']: data['provider'] = record break with open(path, 'wb') as filePickle: dumpPickle(data, filePickle, protocol=4) self.hide()
class PriceAddition(Addition): def __init__(self, tab): super().__init__(tab) [ Label(self.frmFields, text=s).grid(row=i, **self.grd.cl0_pdSt) for i, s in enumerate(['Изготовитель', 'Цена', 'Срок годности']) ] self.cmbManufacturer = Searchbox( master=self.frmFields, postcommand=self.update_manufacturer_list, width=32) self.entPrice = Entry(self.frmFields, width=12, **self.vld.vldFlt2) self.entDate = Entry(self.frmFields, width=12, **self.vld.vldDate) self.cmbManufacturer.grid(row=0, **self.grd.cl1_pdSt) self.entPrice.grid(row=1, sticky='w', **self.grd.cl1_pdSt) self.entDate.grid(row=2, sticky='w', **self.grd.cl1_pdSt) self.lblHint = Label(self.frmFields) self.lblHint.grid(row=3, columnspan=2, **self.grd.pdSt) self.lblHint['wraplength'] = self.toplevel.winfo_reqwidth() - 8 hintA = 'Поле изготовитель — раскрывающийся список с вариантами выбора и встроенным поиском.' hintB = 'Клавиши ↑, ↓ — раскрыть список и перемещаться по вариантам, Esc — скрыть, Enter — выбрать.' hintC = 'Чтобы вернуть все варианты — очистите соответствующее поле ввода.' self.lblHint['text'] = '\n%s\n\n%s\n\n%s' % (hintA, hintB, hintC) self.toplevel.bind('<Configure>', self.hint_resize) def hint_resize(self, event): self.lblHint['wraplength'] = self.toplevel.winfo_reqwidth() - 8 def fillAndShow(self): self.clear() self.show() def update_manufacturer_list(self, event=None): selected_tag = None if self.tv.selection(): if len(self.tv.parent(self.tv.selection()[0])) == 0: selected_tag = self.tv.selection()[0] elif len(self.tv.parent(self.tv.selection()[0])) > 0: selected_tag = self.tv.parent(self.tv.selection()[0]) if selected_tag is not None: itemName = self.tv.item(int(selected_tag))['text'] itemCode = self.db.getCode('item_list', itemName) for record in self.db.data['item_list']: if record['code'] == itemCode: mcl = record['manufacturers'] break values = [self.db.getName('manufacturer_list', i) for i in mcl] self.cmbManufacturer.source = values self.cmbManufacturer.filter_values() def apply(self): if len(self.tv.parent(self.tv.selection()[0])) == 0: slcParentTag = self.tv.selection()[0] elif len(self.tv.parent(self.tv.selection()[0])) > 0: slcParentTag = self.tv.parent(self.tv.selection()[0]) itemCode = int(slcParentTag) providerCode = self.db.data['provider']['code'] manufacturerName = self.cmbManufacturer.get() manufacturerCode = self.db.getCode('manufacturer_list', manufacturerName) code = [itemCode, manufacturerCode, providerCode] repeatFlag = True for offer in self.db.data['price_list']: if offer['code'] == code: repeatFlag = False break price = self.trn.getFltOrZero(self.entPrice.get()) date = self.entDate.get() tag = '%i.%i.%i' % (itemCode, manufacturerCode, providerCode) mcl = self.db.data['item_list'][itemCode]['manufacturers'] if (repeatFlag is True and manufacturerCode != -1 and manufacturerCode in mcl and providerCode != -1): self.db.data['price_list'] += [{ 'code': code, 'price': price, 'date': date }] providerName = self.db.data['provider']['name'] manufacturerName = self.db.getName('manufacturer_list', manufacturerCode) strPrice = '{:.2f}'.format(price) value = [manufacturerName, providerName, strPrice, date] self.tv.insert(slcParentTag, 'end', iid=tag, text=tag, value=value) self.endAddition(tag) elif repeatFlag is False: messagebox.showerror( 'Ошибка', 'Предложение поставщика c кодом %s уже добавлено.' % (tag), parent=self.toplevel) elif manufacturerCode == -1: messagebox.showerror('Ошибка', 'Указанный изготовитель не найден.', parent=self.toplevel) elif manufacturerCode not in mcl: messagebox.showerror( 'Ошибка', 'Изготовитель не ассоциирован с выбранным наименованием.', parent=self.toplevel) elif providerCode == -1: messagebox.showerror( 'Ошибка', 'Название и код поставщика следует указать в настройках "Информация о поставщике".', parent=self.toplevel) def clear(self): self.cmbManufacturer.set('') [ w.delete(0, END) for w in (self.cmbManufacturer, self.entPrice, self.entDate) ]
class ImportXlsTab(XlsTab): def __init__(self, basis): super().__init__(basis) self.path = '' self.btnClose = Button(self.frmFile, text='Закрыть', command=self.closeFile) [ w.grid(row=0, column=i, sticky='w', **self.grd.pdSt) for i, w in enumerate([self.btnOpen, self.btnClose, self.lblPath]) ] [ Label(self.frmOptions, text=s).grid(row=i, **self.grd.cl0_pdSt_stW) for i, s in enumerate( ['Наименование:', 'Изготовитель:', 'Цена:', 'Срок годности:'], start=2) ] lblProvider = Label(self.frmOptions, text='Название поставщика:') lblPriceDate = Label(self.frmOptions, text='Дата прайса: ') self.cmbItmCol, self.cmbMnfCol, self.cmbPrcCol, self.cmbExpDtCol = [ Combobox(**self.argOptionReadonly) for i in range(4) ] self.cmbProvider = Searchbox( postcommand=self.update_provider_list, source=[d['name'] for d in self.db.data['provider_list']], **self.argOpt_wd6) self.entPriceDate = Entry(**self.argOptionDate) self.btnImportData = Button(self.frmOptions, text='Импортировать данные', command=self.importData) [ w.grid(row=i, **self.grd.cl1_sp2_pdSt_stWE) for i, w in enumerate((self.cmbItmCol, self.cmbMnfCol, self.cmbPrcCol, self.cmbExpDtCol), start=2) ] lblProvider.grid(row=6, **self.grd.cl0_sp3_pdSt_stWE) self.cmbProvider.grid(row=7, **self.grd.cl0_sp3_pdSt_stWE) lblPriceDate.grid(row=8, **self.grd.cl0_pdSt_stW) self.entPriceDate.grid(row=8, **self.grd.cl1_sp2_pdSt_stWE) self.btnImportData.grid(row=9, **self.grd.cl0_sp3_pdSt_stWE) [ w.bind('<<ComboboxSelected>>', self.previewData) for w in (self.cmbItmCol, self.cmbMnfCol, self.cmbPrcCol, self.cmbExpDtCol) ] self.frmTab.pack() def update_provider_list(self, event=None): values = [d['name'] for d in self.db.data['provider_list']] self.cmbProvider.source = values self.cmbProvider.filter_values() def selectData(self, event=None): self.resetOptions() self.resetView() self.sheetID = self.trn.getNatMnsOrZero(self.cmbSheet.get()) if self.xlsData and len(self.xlsData[self.sheetID]): self.getScope() values = [(colname(colID)) for colID in range(self.colStart, self.colFinish + 1)] values.insert(0, '') self.cmbItmCol['values'] = values self.cmbMnfCol['values'] = values self.cmbPrcCol['values'] = values self.cmbExpDtCol['values'] = values def previewData(self, event=None): self.resetView() self.getParameters() self.tv.heading('#0', text='Строка') self.tv.column('#0', minwidth=50, stretch=True, width=75) columns = [] if self.itmColID > -1: columns.append('item') if self.mnfColID > -1: columns.append('manufacturer') if self.prcColID > -1: columns.append('price') if self.expDtColID > -1: columns.append('date') self.tv['columns'] = columns columnsLength = len(columns) colWidth = (self.tv.winfo_width() - 75) // columnsLength colMinWidth = colWidth // 2 tvArgs = {'minwidth': colMinWidth, 'stretch': True, 'width': colWidth} if self.itmColID > -1: self.tv.heading('item', text='Наименование') self.tv.column('item', **tvArgs) if self.mnfColID > -1: self.tv.heading('manufacturer', text='Изготовитель') self.tv.column('manufacturer', **tvArgs) if self.prcColID > -1: self.tv.heading('price', text='Цена') self.tv.column('price', anchor='e', **tvArgs) if self.expDtColID > -1: self.tv.heading('date', text='Срок годности') self.tv.column('date', anchor='c', **tvArgs) for rowID in range(self.rowStart, self.rowFinish + 1): tag = str(rowID) self.tv.insert(parent='', index='end', iid=tag, text=rowID + 1) valueID, row = 0, self.xlsData[self.sheetID][rowID] for colID in (self.itmColID, self.mnfColID, self.prcColID, self.expDtColID): if colID > -1: self.tv.set(tag, valueID, row[colID]) valueID += 1 def importData(self): self.getParameters() prvName = self.trn.getNameSting(self.cmbProvider.get()) priceDate = self.entPriceDate.get() providerCode = self.db.getCode('provider_list', prvName) if prvName != '' and providerCode == -1: providerCode = self.db.getNewCode('provider_list') self.db.data['provider_list'].append({ 'code': self.db.getNewCode('provider_list'), 'name': prvName, 'date': priceDate, 'phone': '', 'fax': '', 'email': '' }) self.lblProgress['text'] = 'Добавлен поставщик %s.' % (prvName) elif priceDate != '' and providerCode > -1: for provider in self.db.data['provider_list']: if provider['code'] == providerCode: provider['date'] = priceDate self.lblProgress['text'] = ( 'Обновлена дата прайса для поставщика %s.' % (prvName)) break if self.itmColID > -1 or self.mnfColID > -1: length = len( self.xlsData[self.sheetID][self.rowStart:self.rowFinish]) + 1 strLen = str(length) self.prgProgress['maximum'] = length self.db.clear_records_from_provider(providerCode) for index, rowID in enumerate( range(self.rowStart, self.rowFinish + 1)): itmName = self.xlsData[self.sheetID][rowID][self.itmColID] print(itmName) itmName = self.trn.getNameSting(itmName) itmCode = self.db.getCode('item_list', itmName) mnfName = self.xlsData[self.sheetID][rowID][self.mnfColID] mnfName = self.trn.getNameSting(mnfName) mnfСode = self.db.getCode('manufacturer_list', mnfName) price = self.xlsData[self.sheetID][rowID][self.prcColID] price = self.trn.getFltOrZero(price) expiryDate = self.xlsData[self.sheetID][rowID][self.expDtColID] expiryDate = self.trn.getNameSting(expiryDate) '''Импорт наименований''' if self.itmColID > -1: if itmCode == -1: itmCode = self.db.getNewCode('item_list') self.db.data['item_list'].append({ 'code': itmCode, 'name': itmName, 'substance': '', 'markup': 0, 'manufacturers': [] }) '''Импорт изготовителей''' if self.mnfColID > -1: if mnfСode == -1: mnfСode = self.db.getNewCode('manufacturer_list') self.db.data['manufacturer_list'].append({ 'code': mnfСode, 'name': mnfName }) '''Импорт наименований''' if self.itmColID > -1 and self.mnfColID > -1: itemLast = self.db.data['item_list'][ len(self.db.data['item_list']) - 1] itemMnfs = itemLast['manufacturers'] if mnfСode > -1 and mnfСode not in itemMnfs: itemMnfs.append(mnfСode) '''Импорт в общий прайс''' if prvName != '' and self.itmColID > -1 and self.mnfColID > -1: offerCode = [itmCode, mnfСode, providerCode] repeatFlag = True for offer in self.db.data['price_list']: if offer['code'] == offerCode: offer['price'] = price offer['date'] = expiryDate repeatFlag = False break if repeatFlag is True: self.db.data['price_list'].append({ 'code': offerCode, 'price': price, 'date': expiryDate }) self.progress('Импорт записей', index + 1, strLen) self.progress('Импорт завершён', index + 1, strLen) self.db.saveData() self.basis.prcTab.reset() def getParameters(self): self.itmColID, self.mnfColID, self.prcColID, self.expDtColID = [ self.getColID(w.get()) for w in [self.cmbItmCol, self.cmbMnfCol, self.cmbPrcCol, self.cmbExpDtCol] ] def resetOptions(self): [ w.delete(0, END) for w in (self.cmbItmCol, self.cmbMnfCol, self.cmbPrcCol, self.cmbExpDtCol) ] def resetView(self): for rec in self.tv.get_children(): self.tv.delete(rec) self.tv['columns'] = [] self.tv.heading('#0', text='') self.tv.column('#0', stretch=True, width=self.tv.winfo_reqwidth() - 2)