Esempio n. 1
0
        def __init__(self, master):

            self.frame = Frame(master)
            self.frame.pack(side = LEFT)
            self.frame_lower_button = Frame(self.frame)
            self.frame_lower_button.pack(side=BOTTOM, fill=Y)
            #------------------------ Поле под списком --------#7
            self.memo = Text(self.frame, height=LOST_COMMENT_HEIGHT,
                  width = LOST_WIDTH+1, font=('Lucida Console', BILL_FONT_SIZE))
            self.memo.pack(side=BOTTOM)
            Label(self.frame, text=u'Дополнительный комментарий:',
                font=('Lucida Console', FONT_SIZE)).pack(side=BOTTOM, pady=5)
            #------------------------ Кнопки слева от списка ---------#
            self.frame_left_button = Frame(self.frame)
            self.frame_left_button.pack(side=LEFT, fill=Y)
            self.button_up = Button(self.frame_left_button,
                               image=data.IMG_INTERFACE[2], command=self.b_up)
            self.button_up.pack(side=TOP, padx=5, pady=10)
            self.button_down = Button(self.frame_left_button,
                               image=data.IMG_INTERFACE[1], command=self.b_down)
            self.button_down.pack(side=TOP, padx=5, pady=0)
            #------------------------ Собственно список ---------------#
            self.scrollbar = Scrollbar(self.frame)
            self.listbox = Listbox(self.frame,
                                   yscrollcommand=self.scrollbar.set,
                                   width = LOST_WIDTH, height=LOST_HEIGHT,
                                   activestyle='dotbox',
                                   font=('Lucida Console', BILL_FONT_SIZE))
            self.listbox.pack(side=LEFT, fill=BOTH)
            self.scrollbar.config(command=self.listbox.yview)
            self.scrollbar.pack(side=LEFT, fill=Y)
            #------------------------ Кнопки справа от списка --------#
            self.frame_right_button = Frame(self.frame)
            self.frame_right_button.pack(side=LEFT, fill=Y)
            self.button_plus = Button(self.frame_right_button,
                              image=data.IMG_INTERFACE[6],command=self.b_plus)
            self.button_plus.pack(side=TOP, padx=5, pady=2)
            self.button_minus = Button(self.frame_right_button,
                              image=data.IMG_INTERFACE[7],command=self.b_minus)
            self.button_minus.pack(side=TOP, padx=5, pady=2)
            self.button_info = Button(self.frame_right_button,
                              image=data.IMG_INTERFACE[9],command=self.b_info)
            self.button_info.pack(side=TOP, padx=5, pady=2)
            self.button_del = Button(self.frame_right_button,
                              image=data.IMG_INTERFACE[5],command=self.b_del,
                              state=DISABLED)
            self.button_del.pack(side=TOP, padx=5, pady=25)
            #-------------------------- Кнопки снизу от списка ------------№
            self.button_clear = Button(self.frame_lower_button,
                                text=u'Очистить\nсписок',
                                style='Little.TButton',command=self.b_clear)
            self.button_clear.pack(side=LEFT, padx=10, pady=10, fill=X)
            self.button_save = Button(self.frame_lower_button,
                                text=u'Сохранить\nсписок', style='Little.TButton',
                                command=self.b_save, state=DISABLED)
            self.button_save.pack(side=LEFT, padx=10, pady=10, fill=X)
            self.button_accept = Button(self.frame_lower_button,
                                text=u'Провести\nсписание',
                                style='Little.TButton', command=self.b_accept)
            self.button_accept.pack(side=LEFT, padx=10, pady=10, fill=X)
            #------------------- Причина списания под списком -----------------#
            self.lost_reason_frame = Frame(self.frame_lower_button,
                            relief=GROOVE, width=LOST_REASON_WIDTH, height=50)
            self.lost_reason_frame.pack_propagate(False)
            self.lost_reason_frame.pack(side=LEFT, fill=X)
            self.lostReasonsMenu = Menubutton(self.lost_reason_frame,
                                          text=u'Причина: ----',
                                          direction='below',style='TMenubutton')
            self.lostReasonsMenu.pack(fill=X, pady=5, padx=5)
            self.lostReasonsMenu.update()   #Подгонка по высоте
            self.lost_reason_frame.configure(
                                height=self.lostReasonsMenu.winfo_height() + 10)
            self.lostReasonsMenu.menu  =  Menu(self.lostReasonsMenu, tearoff=0)
            self.lostReasonsMenu['menu'] = self.lostReasonsMenu.menu

            for item in queries.lost_reasons_list():
                self.lostReasonsMenu.menu.add_command(label=item.reason,
                    font=('Verdana', FONT_SIZE_MENU),
                    command=lambda key=item.id: self.reason_change(key))
                                                               # Текущая скидка.
            if queries.lost_reasons_list():
                self.reason = queries.lost_reasons_list()[0]
                self.lostReasonsMenu.configure(text=u'Причина: %s' %
                                                             self.reason.reason)
            else:
                self.reason = None

            self.bill = []        # Содержание текущего списка (Wasted)
Esempio n. 2
0
def show_report(master, data):
    """Выводит панель генерации отчетов."""


    def choose_assortiment(event):
        """Функция, срабатывающая при выборе товара из списка товаров."""

        select = listbox_goods.curselection()
        if select:
            index = int(select[0])
            if assortiment[index]:
                show_report.goods = assortiment[index]
                title.configure(text=assortiment[index].name)
            else:
                show_report.goods = None
                title.configure(text=u'Товары:')
        checks_fill()

    #---------------------------------------

    def assortiment_fill():
        """Функция заполнения списков товаров/ингредиентов"""

        for q in range(len(assortiment)):       # Очищаем список товаров
            del(assortiment[0])
        listbox_goods.delete(0, END)

        for cath in queries.cathegories():
            assortiment.append(None)
            listbox_goods.insert(END, '')
            assortiment.append(None)
            head = '-' * (REPORT_WIDTH - len(cath.name) -1) + cath.name + u'-'
            listbox_goods.insert(END, head)

            for item in queries.items_in_cathegory(cath):
                assortiment.append(item)
                listbox_goods.insert(END, ' ' + item.name)
                if not item.show:
                    listbox_goods.itemconfig(END, {'fg':'grey'})

        assortiment.append(None)
        listbox_goods.insert(END, '')
        assortiment.append(None)
        head = '-' * (REPORT_WIDTH - len(u'Ингредиенты') -1) + u'Ингредиенты-'
        listbox_goods.insert(END, head)

        for item in queries.items_in_cathegory(None):
            assortiment.append(item)
            listbox_goods.insert(END, ' ' + item.name)
            if not item.show:
                listbox_goods.itemconfig(END, {'fg':'grey'})

    #---------------------------------------

    def checks_fill(event=None):
        """Функция заполнения списка параметров для отчета"""

        listbox_checks.delete(0, END)
        reporing = radioVar.get()
        listbox_checks.insert(END, reporing + ':')

        if varGoods.get():
            listbox_checks.insert(END, u'- товар' )
            if reporing == u'Расходы':
                listbox_checks.itemconfig(END, {'fg':'grey'})
            elif not show_report.goods:
                listbox_checks.itemconfig(END, {'fg':'red'})

        if varDate.get():
            listbox_checks.insert(END, u'- дата' )
            if reporing == u'Остатки':
                listbox_checks.itemconfig(END, {'fg':'grey'})
            elif not (cal_from.selection or cal_to.selection):
                listbox_checks.itemconfig(END, {'fg':'red'})

            elif (cal_from.selection and cal_to.selection) and (
                  cal_from.selection > cal_to.selection):
                listbox_checks.itemconfig(END, {'fg':'red'})

        if varCath.get():
            listbox_checks.insert(END, u'- категория' )
            if reporing == u'Расходы':
                listbox_checks.itemconfig(END, {'fg':'grey'})

        if varCheck.get():
            listbox_checks.insert(END, u'- чек' )
            if reporing <> u'Продажи':
                listbox_checks.itemconfig(END, {'fg':'grey'})
            else:
                try:
                    check1 = int(chekVar1.get())
                    check2 = int(chekVar2.get())
                except:
                    listbox_checks.itemconfig(END, {'fg':'red'})
                else:
                    if check1 > check2:
                        listbox_checks.itemconfig(END, {'fg':'red'})

        if varLost.get():
            listbox_checks.insert(END, u'- причина' )
            if reporing <> u'Списания':
                listbox_checks.itemconfig(END, {'fg':'grey'})

        if radioVar2.get() <> u'Не учитывать':
            listbox_checks.insert(END, u'- скидка' )
            if reporing <> u'Продажи':
                listbox_checks.itemconfig(END, {'fg':'grey'})


    #---------------------------------------

    class Calendar2(Calendar):
        """Класс с переопределенным (дополненным) методом клика по календарю."""

        def _pressed(self, evt):
            """Clicked somewhere in the calendar."""

            Calendar._pressed(self, evt)
            checks_fill()

    #---------------------------------------

    def apply():
        """Открывает окно с выбранным отчетом на основании выбранных фильтров"""

        args = {}

        if varGoods.get() and radioVar.get() <> u'Расходы':
            if show_report.goods:
                args['item'] = show_report.goods
            else:
                tkMessageBox.showinfo(u'Внимание!',
                          u'Товар не был выбран, так что учитываться не будет!')

        if varDate.get() and radioVar.get() <> u'Остатки':
            if cal_from.selection or cal_to.selection:
                if (cal_from.selection > cal_to.selection):
                    tkMessageBox.showinfo(u'Ошибка!',
              u'Начальный день акции больше конечного!\nФильтр не учитывается.')
                else:
                    if cal_from.selection:
                        args['from_date'] = cal_from.selection
                    if cal_to.selection:
                        args['to_date'] = cal_to.selection
            else:
                tkMessageBox.showinfo(u'Внимание!',
                         u'Даты не были выбраны, так что учитываться не будут!')

        if varCath.get():
            if radioVar.get() <> u'Расходы':
                args['cathegory'] = show_report.cathegory

        if varCheck.get():
            if radioVar.get() == u'Продажи':
                try:
                    check1 = int(chekVar1.get())
                    check2 = int(chekVar2.get())
                except:
                    tkMessageBox.showinfo(u'Ошибка!',
            u'Проверьте содержимое числовых полей чека!\nФильтр не учитвается.')
                else:
                    if check1 > check2:
                        tkMessageBox.showinfo(u'Ошибка!',
              u'Начальный номер чека больше конечного!\nФильтр не учитывается.')
                    else:
                        args['from_check'] = check1
                        args['to_check'] = check2

        if varLost.get():
            if radioVar.get() == u'Списания':
                args['reason'] = show_report.lost


        if radioVar2.get() <> u'Не учитывать':
            if radioVar.get() == u'Продажи':
                if radioVar2.get() == u'Со скидкой':
                    args['discount'] = True
                else:
                    args['discount'] = False


        if radioVar.get() == u'Продажи':
            report_sell(master, **args)
        elif radioVar.get() == u'Списания':
            report_lost(master, **args)
        elif radioVar.get() == u'Остатки':
            report_storage(master, **args)
        elif radioVar.get() == u'Приход':
            report_incoming(master, **args)
        elif radioVar.get() == u'Расходы':
            report_cash(master, **args)

    #=========================== СОЗДАНИЕ ИНТЕРФЕЙСА ===========================

    frame = Canvas(master, relief=GROOVE, highlightthickness=0)
    frame.pack(side=TOP, fill=BOTH, expand=YES)
    if USE_BACKGROUND:
        frame.create_image(0,0, anchor='nw', image=data.photo)

    #------------------------------ ЛЕВЫЙ ФРЕЙМ --------------------------------

    leftFrame = Frame(frame, relief=GROOVE)
    leftFrame.pack(side=LEFT, fill=Y, pady=CONTROL_PAD, padx=CONTROL_PAD/2)

    title = Label(leftFrame, text=u'Товары:',
                                        font=('Lucida Console', FONT_SIZE_BIG))
    title.pack(pady=5)

    varGoods = IntVar(leftFrame)
    chb_goods = Checkbutton(leftFrame, text=u'Фильтр по товару',
                                         variable=varGoods, command=checks_fill)
    chb_goods.pack(side=BOTTOM)

    assortiment = []
    show_report.goods = None

    scrollbar_goods = Scrollbar(leftFrame)
    listbox_goods = Listbox(leftFrame,
                       yscrollcommand=scrollbar_goods.set,
                       width = REPORT_WIDTH,
                       activestyle='dotbox',
                       font=('Lucida Console', BILL_FONT_SIZE))
    listbox_goods.pack(side=LEFT, fill=BOTH)
    scrollbar_goods.config(command=listbox_goods.yview)
    scrollbar_goods.pack(side=LEFT, fill=Y)

    listbox_goods.bind('<<ListboxSelect>>', choose_assortiment)

    #------------------------------ СРЕДНИЙ ФРЕЙМ ------------------------------

    middleFrame = Frame(frame, relief=GROOVE)
    middleFrame.pack(side=TOP, pady=CONTROL_PAD, padx=CONTROL_PAD, anchor='w',
                                       ipadx=CONTROL_PAD/3, ipady=CONTROL_PAD/3)

    radioVar = StringVar(middleFrame)
    radioVar.set("Продажи")

    variants = ("Продажи", "Остатки", "Приход", "Списания", "Расходы")

    listbox_checks = Listbox(middleFrame, width = 12, height=6,
                  activestyle='dotbox', font=('Lucida Console', BILL_FONT_SIZE))
    listbox_checks.pack(side=RIGHT, fill=Y, padx=CONTROL_PAD/2,
                                                             pady=CONTROL_PAD/2)

    Button(middleFrame, text='СФОРМИРОВАТЬ\nОТЧЕТ', style='Chosen.TButton',
                             command=apply).pack(side=RIGHT, padx = CONTROL_PAD,
                                         pady = CONTROL_PAD, ipadx=10, ipady=10)

    for txt in variants:
        Radiobutton(middleFrame, text=txt,indicatoron = 0, width = 10,
                         variable=radioVar, command=checks_fill, value=txt,
                         font=('Verdana', FONT_SIZE)).pack(padx = CONTROL_PAD,
                                                   pady=CONTROL_PAD/3, anchor=W)

    #-----------------------------------------

    middleFrame2 = Frame(frame, relief=GROOVE)
    middleFrame2.pack(padx=CONTROL_PAD, pady=CONTROL_PAD, anchor='w')


    date_from = Label(middleFrame2, text=u'Начальная дата:',
                                                  font = ('Verdana', FONT_SIZE))
    date_from.grid(column=0, row=0)
    cal_from = Calendar2(middleFrame2, firstweekday=0)
    cal_from.grid(column=0, row=1, pady=CONTROL_PAD, padx=CONTROL_PAD)

    date_to = Label(middleFrame2, text=u'Конечная дата\n(включительно):',
                                                  font = ('Verdana', FONT_SIZE))
    date_to.grid(column=1, row=0)
    cal_to = Calendar2(middleFrame2, firstweekday=0)
    cal_to.grid(column=1, row=1, pady=CONTROL_PAD, padx=CONTROL_PAD)

    varDate = IntVar(leftFrame)
    chb_date = Checkbutton(middleFrame2, text=u'Фильтр по датам',
                                          variable=varDate, command=checks_fill)
    chb_date.grid(column=0, row=2, columnspan=2, pady=CONTROL_PAD/3)


    #---------------------- Меню выбора категории --------------

    middleFrame3 = Frame(frame, relief=GROOVE)
    middleFrame3.pack(padx=CONTROL_PAD, pady=CONTROL_PAD, anchor='w')


    def menu_change(key):
        """Меняет текущую категорию."""
        if key:
            cathMenu.configure(text=key.name)
        else:
            cathMenu.configure(text=u'-Отсутствует-')
        show_report.cathegory = key


    def menu_update():
        """Обновляет меню выбора категорий."""

        menu  =  Menu(cathMenu, tearoff=0)
        cathMenu['menu'] = menu

        for cath in queries.cathegories():
            menu.add_command(label=cath.name, font=('Verdana', FONT_SIZE_BIG),
                                      command=lambda key=cath: menu_change(key))
        menu.add_command(label=u'-Отсутствует-', font=('Verdana',FONT_SIZE_BIG),
                                    command=lambda: menu_change(None))


    Style().configure('TMenubutton', font=('lucida console', FONT_SIZE_BIG),
                                                                justify='left')
    show_report.cathegory = None

    varCath = IntVar(middleFrame3)
    chb_cath = Checkbutton(middleFrame3, text=u'Фильтр по категории',
                                          variable=varCath, command=checks_fill)
    chb_cath.grid(column=0, row=1, columnspan=2,
                                              pady=(0, CONTROL_PAD))

    Label(middleFrame3, text='Категория:', font=('Verdana', FONT_SIZE_BIG)
                       ).grid(column=0, row=0, pady=CONTROL_PAD/3)

    smallFrame = Frame(middleFrame3, relief=GROOVE)
    smallFrame.grid(column=1, row=0, pady=CONTROL_PAD/3)


    cathMenu = Menubutton(smallFrame, text=u'-Отсутствует-', width=15,
                                                            style='TMenubutton')
    cathMenu.pack(fill=BOTH, pady=5, padx=5)
    menu_update()

    #----------------------------- ЧЕКИ ----------------------------

    check_frame = TkFrame(middleFrame3, relief=GROOVE, bg='#' + REPORT_COLOR)
    check_frame.grid(column=0, row=2, columnspan=2, pady=(CONTROL_PAD/3, 0),
                                                                  sticky='nwes')
    varCheck = IntVar(middleFrame3)
    chb_check = Checkbutton(middleFrame3, text=u'Фильтр по номеру чека',
                variable=varCheck, command=checks_fill, activebackground='#' +
                                     REPORT_COLOR, bg='#' + REPORT_COLOR)
    chb_check.grid(column=0, row=3, columnspan=2, pady=(0, CONTROL_PAD),
                                                                  sticky='nwes')

    chekVar1 = StringVar(check_frame, value=u'')
    ent1 = Entry(check_frame, textvariable=chekVar1, width=7,font=('Verdana',
       FONT_SIZE_BIG))
    ent1.pack(side=LEFT, pady=CONTROL_PAD/3, padx=CONTROL_PAD)
    ent1.bind("<KeyRelease>", checks_fill)

    Label(check_frame, text=u'<= номера чеков <=', bg='#' + REPORT_COLOR,
                                font = ('Verdana', FONT_SIZE)).pack(side=LEFT,
                                           pady=CONTROL_PAD/3, padx=CONTROL_PAD)
    chekVar2 = StringVar(check_frame, value=u'')
    ent2 = Entry(check_frame, textvariable=chekVar2, width=7,font=('Verdana',
       FONT_SIZE_BIG))
    ent2.pack(side=LEFT, pady=CONTROL_PAD/3, padx=CONTROL_PAD)
    ent2.bind("<KeyRelease>", checks_fill)

    #---------------------- Меню выбора причины списания --------------

    def menu_change_lost(key):
        """Меняет текущую причину списания."""
        if key:
            lostMenu.configure(text=key.reason)
        show_report.lost = key


    def menu_update_lost():
        """Обновляет меню выбора причин списания."""

        menu  =  Menu(cathMenu, tearoff=0)
        lostMenu['menu'] = menu

        for lost in queries.full_lost_reasons_list():
            menu.add_command(label=lost.reason, font=('Verdana', FONT_SIZE_BIG),
                                 command=lambda key=lost: menu_change_lost(key))


    Style().configure('TMenubutton', font=('lucida console', FONT_SIZE_BIG),
                                                                justify='left')
    lost_reasons_list = queries.lost_reasons_list()
    show_report.lost = lost_reasons_list[0] if lost_reasons_list else None

    varLost = IntVar(middleFrame)
    chb_lost = Checkbutton(middleFrame3, text=u'Фильтр по причине списания',
                                          variable=varLost, command=checks_fill)
    chb_lost.grid(column=0, row=5, columnspan=2, pady=(0, CONTROL_PAD))

    Label(middleFrame3, text='Причина списания:', font=('Verdana', FONT_SIZE_BIG)
                 ).grid(column=0, row=4, pady=CONTROL_PAD/3, padx=CONTROL_PAD/3)

    smallFrame2 = Frame(middleFrame3, relief=GROOVE)
    smallFrame2.grid(column=1, row=4, pady=CONTROL_PAD/3)

    lostMenu = Menubutton(smallFrame2, text=u'брак', width=19,
                                                            style='TMenubutton')
    lostMenu.pack(fill=BOTH, pady=5, padx=5)
    menu_update_lost()

    #--------------------------------------------------------------

    Label(middleFrame3, text='Фильтр по скидке.', font=('Verdana', FONT_SIZE),
            bg='#' + REPORT_COLOR).grid(column=0, row=7, sticky='nwes',
                                                                   columnspan=2)

    discFrame = TkFrame(middleFrame3, relief=GROOVE, bg='#' + REPORT_COLOR)
    discFrame.grid(column=0, row=6, columnspan=2, ipady=(CONTROL_PAD),
                                                                  sticky='nwes')
    radioVar2 = StringVar(middleFrame)
    radioVar2.set(u'Не учитывать')

    variants = (u'Не учитывать', u'Со скидкой', u'Без скидки')

    for txt in variants:
        Radiobutton(discFrame, text=txt,indicatoron = 0, width = 13,
            variable=radioVar2, command=checks_fill, value=txt,
            font=('Verdana', FONT_SIZE)).pack(side=LEFT, padx = CONTROL_PAD/2,
                                                  pady=CONTROL_PAD/3, anchor=W)

    #--------------------------------первый запуск-----------------------------

    assortiment_fill()
    checks_fill()