Пример #1
0
class MedicSalesSearch(SearchDialog):
    title = _(u"Sold Items by medic")
    size = (800, 450)
    search_spec = MedicSoldItemsView
    fast_iter = True

    #
    # SearchDialog Hooks
    #

    def setup_widgets(self):
        self.add_csv_button(_("Sold Products"), _("sold-products"))
        self.sale_details_button = self.add_button(label=_("Sale Details"))
        self.sale_details_button.show()
        self.sale_details_button.set_sensitive(False)

    def update_widgets(self):
        item = self.results.get_selected()
        self.sale_details_button.set_sensitive(bool(item))

    def create_filters(self):
        self.set_text_field_columns(["medic_name", "description", "code"])

        # Dont set a limit here, otherwise it might break the summary
        executer = self.search.get_query_executer()
        executer.set_limit(-1)

        branch_filter = self.create_branch_filter(_("In Branch:"))
        self.add_filter(branch_filter, SearchFilterPosition.TOP, columns=[Sale.branch_id])

        self._date_filter = DateSearchFilter(_("Date:"))
        self._date_filter.select(data=DateSearchFilter.Type.USER_INTERVAL)
        self.add_filter(self._date_filter, SearchFilterPosition.BOTTOM, columns=[Sale.confirm_date])
        self.search.set_summary_label("total", label=_(u"Total:"), format="<b>%s</b>")

    def get_columns(self):
        columns = [
            IdentifierColumn("identifier", title=_("Sale #")),
            SearchColumn("open_date", title=_("Open date"), data_type=datetime.date, visible=False),
            SearchColumn("confirm_date", title=_("Confirm date"), data_type=datetime.date, visible=False),
            SearchColumn("code", title=_("Code"), data_type=str, sorted=True),
            SearchColumn("category", title=_("Category"), data_type=str, visible=False),
            SearchColumn("branch_name", title=_("Branch"), data_type=str, visible=False),
            SearchColumn("description", title=_("Description"), data_type=str, expand=True),
            SearchColumn("manufacturer", title=_("Manufacturer"), data_type=str, visible=False),
            SearchColumn("medic_name", title=_("Medic"), data_type=str),
            SearchColumn("crm_number", title=_("CRM"), data_type=str),
            SearchColumn("partner", title=_("Partner"), data_type=bool, visible=False, width=40),
            SearchColumn("batch_number", title=_("Batch"), data_type=str, visible=False),
            SearchColumn("batch_date", title=_("Batch Date"), data_type=datetime.date, visible=False),
            SearchColumn("quantity", title=_("Qty"), data_type=decimal.Decimal, format_func=format_quantity),
            SearchColumn("total", title=_("Total"), data_type=currency),
        ]

        return columns

    def on_sale_details_button__clicked(self, widget):
        item = self.results.get_selected()
        sale_view = self.store.find(SaleView, id=item.sale_id).one()
        run_dialog(SaleDetailsDialog, self, self.store, sale_view)
Пример #2
0
 def search_for_date(self, date):
     dfilter = DateSearchFilter(_("Expected receival date"))
     dfilter.set_removable()
     dfilter.mode.select_item_by_position(5)
     self.add_filter(dfilter, columns=["expected_receival_date"])
     dfilter.start_date.set_date(date)
     self.refresh()
Пример #3
0
class ProductsSoldSearch(ProductSearch):
    title = _('Products Sold Search')
    search_spec = SoldItemView
    report_class = ProductsSoldReport
    csv_data = None
    has_print_price_button = False
    advanced_search = False
    text_field_columns = [SoldItemView.description]
    branch_filter_column = Sale.branch_id

    def __init__(self, store, hide_footer=True, hide_toolbar=True):
        ProductSearch.__init__(self, store, hide_footer=hide_footer,
                               hide_toolbar=hide_toolbar)

    #
    #  ProductSearch
    #

    def create_filters(self):
        self.date_filter = DateSearchFilter(_('Date:'))
        self.date_filter.select(Today)
        self.add_filter(self.date_filter, columns=[Sale.confirm_date])

    def get_columns(self):
        return [Column('code', title=_('Code'), data_type=str,
                       sorted=True),
                Column('description', title=_('Description'),
                       data_type=str, expand=True),
                QuantityColumn('quantity', title=_('Sold')),
                Column('average_cost', title=_('Avg. Cost'),
                       data_type=currency), ]
class FinancialReportDialog(BasicDialog):
    title = _("Financial Report Dialog")

    def __init__(self, store):
        self.store = store

        self.date_filter = DateSearchFilter(_("Year:"))
        self.date_filter.clear_options()
        self._populate_date_filter(self.date_filter)
        self.date_filter.select()
        self.date_filter.set_use_date_entries(False)

        BasicDialog.__init__(self, title=self.title)
        self.main_label.set_justify(gtk.JUSTIFY_CENTER)

        self.ok_button.set_label(_("Generate"))
        self.add(self.date_filter)
        self.date_filter.show()

    def confirm(self):
        start = self.date_filter.get_start_date()
        if start is None:
            warning(_("There are no transactions yet"))
            return

        f = FinancialIntervalReport(self.store, start.year)
        if not f.run():
            return
        temporary = tempfile.NamedTemporaryFile(
            # Translators: This will be part of a filename
            prefix=_("stoq-yearly-report"),
            suffix=".xls",
            delete=False,
        )
        f.write(temporary)
        sse = SpreadSheetExporter()
        sse.export_temporary(temporary)

        self.close()
        self.temporary = temporary

    #
    # Private
    #

    def _populate_date_filter(self, date_filter):
        transaction = self.store.find(AccountTransaction).order_by(AccountTransaction.date).first()
        if transaction is None:
            return

        for i in range(transaction.date.year, localtoday().year + 1):
            year = datetime.datetime(i, 1, 1)
            date_filter.add_option_fixed_interval(_("Year %d") % (i,), year, year.replace(month=12, day=31), position=0)

    def _date_filter_query(self, search_spec, column):
        executer = QueryExecuter(self.store)
        executer.set_filter_columns(self.date_filter, [column])
        executer.set_search_spec(search_spec)
        return executer.search([self.date_filter.get_state()])
Пример #5
0
 def search_for_date(self, date):
     self.main_filter.select(None)
     dfilter = DateSearchFilter(_("Paid or due date"))
     dfilter.set_removable()
     dfilter.mode.select_item_by_position(5)
     self.add_filter(dfilter, columns=["paid_date", "due_date"])
     dfilter.start_date.set_date(date)
     self.search.refresh()
Пример #6
0
 def search_for_date(self, date):
     self.main_filter.combo.select(self._not_delivered_filter_item)
     dfilter = DateSearchFilter(_("Estimated finish"))
     dfilter.set_removable()
     dfilter.select(data=DateSearchFilter.Type.USER_DAY)
     self.add_filter(dfilter, columns=["estimated_finish"])
     dfilter.start_date.set_date(date)
     self.refresh()
Пример #7
0
 def search_for_date(self, date):
     self.main_filter.select(None)
     dfilter = DateSearchFilter(_("Paid or due date"))
     dfilter.set_removable()
     dfilter.select(data=DateSearchFilter.Type.USER_DAY)
     self.add_filter(dfilter, columns=["paid_date", "due_date"])
     dfilter.start_date.set_date(date)
     self.refresh()
Пример #8
0
    def create_filters(self):
        # Extra filters (that are not columns)
        self.search.add_filter_option(SellableCategory.description, title=_(u"Product category"), data_type=str)
        self.search.add_filter_option(Sellable.description, title=_(u"Product"), data_type=str)

        # Date
        date_filter = DateSearchFilter(_("Date:"))
        date_filter.select(Today)
        self.add_filter(date_filter, columns=[Sale.confirm_date])
Пример #9
0
    def create_filters(self):
        self.set_text_field_columns(["description", "identifier_str"])
        self.search.set_query(self.executer_query)

        # Date
        date_filter = DateSearchFilter(_("Date:"))
        date_filter.select(0)
        columns = [Payment.due_date, Payment.open_date, Payment.paid_date]
        self.add_filter(date_filter, columns=columns)
        self.date_filter = date_filter
Пример #10
0
 def create_filters(self):
     # Date
     date_filter = DateSearchFilter(_('Date:'))
     date_filter.select(Today)
     columns = [ProductHistory.sold_date,
                ProductHistory.received_date,
                ProductHistory.production_date,
                ProductHistory.decreased_date]
     self.add_filter(date_filter, columns=columns)
     self.date_filter = date_filter
Пример #11
0
    def create_filters(self):
        self.set_text_field_columns(['description'])
        self.executer.set_query(self.executer_query)

        # Date
        date_filter = DateSearchFilter(_('Date:'))
        date_filter.select(0)
        columns = [Payment.due_date,
                   Payment.open_date,
                   Payment.paid_date]
        self.add_filter(date_filter, columns=columns)
        self.date_filter = date_filter
Пример #12
0
class PaymentFlowHistoryDialog(BasicDialog):
    title = _(u'Payment Flow History Dialog')
    desc = _("Select a date or a range to be visualised in the report:")
    size = (-1, -1)
    model_type = PaymentFlowDay

    def __init__(self, store):
        """A dialog to print the PaymentFlowHistoryReport report.

        :param store: a store
        """
        self.store = store
        BasicDialog.__init__(self, header_text='<b>%s</b>' % self.desc,
                             title=self.title)
        self._setup_widgets()

    #
    # BasicDialog
    #

    def confirm(self):
        state = self._date_filter.get_state()
        from stoqlib.database.queryexecuter import DateQueryState
        if isinstance(state, DateQueryState):
            start, end = state.date, state.date
        else:
            start, end = state.start, state.end

        results = PaymentFlowDay.get_flow_history(self.store, start, end)
        if not results:
            info(_('No payment history found.'))
            return False

        print_report(PaymentFlowHistoryReport, payment_histories=results)
        return True

    #
    # Private
    #

    def _setup_widgets(self):
        self.ok_button.set_label(gtk.STOCK_PRINT)

        self._date_filter = DateSearchFilter(_(u'Date:'))
        # FIXME: add a remove_option method in DateSearchFilter.
        self._date_filter.clear_options()
        self._date_filter.add_custom_options()
        for option in [Today, Yesterday, LastWeek, LastMonth]:
            self._date_filter.add_option(option)
        self._date_filter.select(position=0)

        self.vbox.pack_start(self._date_filter, False, False)
        self._date_filter.show_all()
Пример #13
0
    def __init__(self, store):
        BasicDialog.__init__(self, title=self.title)
        self.main_label.set_justify(Gtk.Justification.CENTER)

        self.store = store
        self.ok_button.set_label(_("Generate"))

        self.date_filter = DateSearchFilter(_('Month:'))
        self.date_filter.set_use_date_entries(False)
        self.date_filter.clear_options()
        self._populate_date_filter(self.date_filter)
        self.date_filter.select()

        self.add(self.date_filter)
        self.date_filter.show()
Пример #14
0
    def __init__(self, store):
        self.store = store

        self.date_filter = DateSearchFilter(_('Year:'))
        self.date_filter.clear_options()
        self._populate_date_filter(self.date_filter)
        self.date_filter.select()
        self.date_filter.set_use_date_entries(False)

        BasicDialog.__init__(self, title=self.title)
        self.justify_label(gtk.JUSTIFY_CENTER)

        self.ok_button.set_label(_("Generate"))
        self.add(self.date_filter)
        self.date_filter.show()
Пример #15
0
    def create_filters(self):
        self.set_text_field_columns(['description'])
        self.search.set_query(self.executer_query)

        # Date
        date_filter = DateSearchFilter(_('Date:'))
        date_filter.select(Today)
        self.add_filter(date_filter)
        self.date_filter = date_filter

        # Branch
        branch_filter = self.create_branch_filter(_('In branch:'))
        self.add_filter(branch_filter, columns=[],
                        position=SearchFilterPosition.TOP)
        self.branch_filter = branch_filter
Пример #16
0
    def create_filters(self):
        self.set_text_field_columns(['salesperson_name', 'identifier_str'])

        self._salesperson_filter = self.create_salesperson_filter(_("Sold by:"))
        self.add_filter(self._salesperson_filter, SearchFilterPosition.TOP,
                        callback=self._get_salesperson_query)

        # Adding a filter by date with custom interval
        self._date_filter = DateSearchFilter(_("Date:"))
        self._date_filter.select(data=DateSearchFilter.Type.USER_INTERVAL)
        if sysparam.get_bool('SALE_PAY_COMMISSION_WHEN_CONFIRMED'):
            self.add_filter(self._date_filter, SearchFilterPosition.BOTTOM,
                            columns=[self.search_spec.confirm_date])
        else:
            self.add_filter(self._date_filter, SearchFilterPosition.BOTTOM,
                            columns=[self.search_spec.paid_date])
Пример #17
0
    def create_filters(self):
        self.set_text_field_columns(['client_name', 'removed_by',
                                     'identifier_str'])

        # Date
        self.date_filter = DateSearchFilter(_('Date:'))
        self.add_filter(self.date_filter, columns=['expire_date', 'open_date'])
Пример #18
0
    def create_filters(self):
        self.set_text_field_columns(['name'])
        self.search.set_query(self.executer_query)

        date_filter = DateSearchFilter(_('Date:'))
        self.search.add_filter(date_filter)
        self.date_filter = date_filter
Пример #19
0
    def _setup_widgets(self):
        # Branches combo
        items = api.get_branches_for_filter(self.store)
        self.branch.prefill(items)

        # Daterange filter
        self.date_filter = DateSearchFilter(_(u'Date:'))
        self.date_filter.clear_options()
        self.date_filter.add_custom_options()
        for option in [Today, Yesterday, LastWeek, LastMonth]:
            self.date_filter.add_option(option)
        self.date_filter.select(position=0)
        self.daterange_hbox.pack_start(self.date_filter, False, False, 0)
        self.date_filter.show_all()

        # Setting report lists' columns
        self.sales_list.set_columns(self._get_sales_columns())
        self.inpayments_list.set_columns(self._get_lonely_payments_columns())
        self.purchases_list.set_columns(self._get_purchases_columns())
        self.outpayments_list.set_columns(self._get_lonely_payments_columns())
        self.return_sales_list.set_columns(self._get_return_sales_columns())
        self.supplies_list.set_columns(self._get_till_columns())
        self.removals_list.set_columns(self._get_till_columns())
        self.permethod_list.set_columns(self._get_permethod_columns())
        self.percard_list.set_columns(self._get_percard_columns())

        # Print button is insensitive, until the first report is generated
        self.print_button.set_sensitive(False)

        self._setup_summary_labels()
Пример #20
0
 def _add_date_filter(self):
     self.date_filter = DateSearchFilter(_('Date:'))
     self.date_filter.clear_options()
     self.date_filter.add_option(Any, 0)
     year = datetime.datetime.today().year
     month_names = get_month_names()
     for i, month in enumerate(month_names):
         name = month_names[i]
         option = type(name + 'Option', (MonthOption, ),
                       {'name': _(name),
                        'month': i + 1,
                        'year': year})
         self.date_filter.add_option(option, i + 1)
     self.date_filter.add_custom_options()
     self.date_filter.mode.select_item_by_position(0)
     self.search.add_filter(self.date_filter)
Пример #21
0
class DateRangeDialog(BasicDialog):
    """A simple dialog for selecting a date range

    When confirmed, a :class:`date_range` object will be returned
    containig the information about the date range selected
    """

    title = _(u'Select a date range')
    size = (-1, -1)

    def __init__(self, title=None, header_text=None):
        title = title or self.title
        header_text = '<b>%s</b>' % header_text if header_text else ''
        BasicDialog.__init__(self, title=title, header_text=header_text)

        self._setup_widgets()

    #
    #  BasicDialog
    #

    def confirm(self):
        BasicDialog.confirm(self)

        state = self.date_filter.get_state()
        if isinstance(state, DateQueryState):
            start, end = state.date, state.date
        else:
            start, end = state.start, state.end

        self.retval = date_range(start=start, end=end)

    #
    #  Private
    #

    def _setup_widgets(self):
        self.date_filter = DateSearchFilter(_(u'Date:'))
        # FIXME: add a remove_option method in DateSearchFilter.
        self.date_filter.clear_options()
        self.date_filter.add_custom_options()
        for option in [Today, Yesterday, LastWeek, LastMonth]:
            self.date_filter.add_option(option)
        self.date_filter.select(position=0)

        self.vbox.pack_start(self.date_filter, False, False)
        self.date_filter.show_all()
Пример #22
0
    def create_filters(self):
        self.set_text_field_columns(['description'])
        self.search.set_query(self.executer_query)

        # Date
        date_filter = DateSearchFilter(_('Date:'))
        date_filter.select(Today)
        self.add_filter(date_filter)
        self.date_filter = date_filter

        # Branch
        branch_filter = self.create_branch_filter(_('In branch:'))
        branch_filter.select(None)
        self.add_filter(branch_filter,
                        columns=[],
                        position=SearchFilterPosition.TOP)
        self.branch_filter = branch_filter
Пример #23
0
    def create_filters(self):
        self.set_text_field_columns(
            ['salesperson_name', 'description', 'code'])

        self._date_filter = DateSearchFilter("Data:")
        self.add_filter(self._date_filter,
                        SearchFilterPosition.BOTTOM,
                        columns=[Sale.confirm_date])
Пример #24
0
    def create_filters(self):
        self.set_text_field_columns(['medic_name', 'description', 'code'])

        # Dont set a limit here, otherwise it might break the summary
        executer = self.search.get_query_executer()
        executer.set_limit(-1)

        branch_filter = self.create_branch_filter(_('In Branch:'))
        self.add_filter(branch_filter, SearchFilterPosition.TOP,
                        columns=[Sale.branch_id])

        self._date_filter = DateSearchFilter(_("Date:"))
        self._date_filter.select(data=DateSearchFilter.Type.USER_INTERVAL)
        self.add_filter(self._date_filter, SearchFilterPosition.BOTTOM,
                        columns=[Sale.confirm_date])
        self.search.set_summary_label('total', label=_(u'Total:'),
                                      format='<b>%s</b>')
Пример #25
0
    def create_filters(self):
        self.set_text_field_columns(
            ['source_branch_name', 'destination_branch_name'])

        # Date
        self.date_filter = DateSearchFilter(_('Date:'))
        self.add_filter(self.date_filter,
                        columns=['open_date', 'receival_date'])
Пример #26
0
    def create_filters(self):
        self.set_text_field_columns(['description'])

        # Date
        date_filter = DateSearchFilter(_('Date:'))
        date_filter.select(Today)
        columns = [ProductHistory.sold_date,
                   ProductHistory.received_date,
                   ProductHistory.production_date,
                   ProductHistory.decreased_date]
        self.add_filter(date_filter, columns=columns)
        self.date_filter = date_filter

        # Branch
        self.branch_filter = self.create_branch_filter(_('In branch:'))
        self.add_filter(self.branch_filter, columns=['branch'],
                        position=SearchFilterPosition.TOP)
        # remove 'Any' option from branch_filter
        self.branch_filter.combo.remove_text(0)
Пример #27
0
    def create_filters(self):
        self.set_text_field_columns(["description"])

        self.date_filter = DateSearchFilter(_("Date:"))
        self.date_filter.select(Today)
        self.add_filter(self.date_filter, columns=["date"])
        # add summary label
        value_format = "<b>%s</b>"
        total_label = "<b>%s</b>" % api.escape(_(u"Total:"))
        self.search.set_summary_label("value", total_label, value_format)
Пример #28
0
    def create_filters(self):
        self.set_text_field_columns(['description'])

        # Date
        date_filter = DateSearchFilter(_('Date:'))
        date_filter.select(Today)
        columns = [ProductHistory.sold_date,
                   ProductHistory.received_date,
                   ProductHistory.production_date,
                   ProductHistory.decreased_date]
        self.add_filter(date_filter, columns=columns)
        self.date_filter = date_filter

        # Branch
        self.branch_filter = self.create_branch_filter(_('In branch:'))
        self.add_filter(self.branch_filter, columns=['branch'],
                        position=SearchFilterPosition.TOP)
        # remove 'Any' option from branch_filter
        self.branch_filter.combo.remove_text(0)
Пример #29
0
    def create_filters(self):
        self.set_text_field_columns(['description'])

        self.date_filter = DateSearchFilter(_('Date:'))
        self.date_filter.select(Today)
        self.add_filter(self.date_filter, columns=['date'])
        # add summary label
        value_format = '<b>%s</b>'
        total_label = '<b>%s</b>' % api.escape(_(u'Total:'))
        self.search.set_summary_label('value', total_label, value_format)
Пример #30
0
    def _setup_widgets(self):
        self.date_filter = DateSearchFilter(_(u'Date:'))
        # FIXME: add a remove_option method in DateSearchFilter.
        self.date_filter.clear_options()
        self.date_filter.add_custom_options()
        for option in [Today, Yesterday, LastWeek, LastMonth]:
            self.date_filter.add_option(option)
        self.date_filter.select(position=0)

        self.vbox.pack_start(self.date_filter, False, False)
        self.date_filter.show_all()
Пример #31
0
class SoldItemsByClientSearch(SearchDialog):
    title = _(u'Sold Items by Client')
    report_class = SoldItemsByClientReport
    search_spec = SoldItemsByClient
    size = (800, 450)
    unlimited_results = True
    text_field_columns = [SoldItemsByClient.client_name,
                          SoldItemsByClient.description,
                          SoldItemsByClient.code]
    branch_filter_column = Sale.branch_id

    def setup_widgets(self):
        self.add_csv_button(_('Sale items'), _('sale items'))

    def create_filters(self):
        self._date_filter = DateSearchFilter(_("Date:"))
        self._date_filter.select(data=DateSearchFilter.Type.USER_INTERVAL)
        self.add_filter(self._date_filter, columns=[Sale.confirm_date])
        self.search.set_summary_label('quantity', label=_(u'Total:'),
                                      format='<b>%s</b>')

    def get_columns(self):
        columns = [
            SearchColumn('code', title=_('Code'), data_type=str, sorted=True,
                         order=Gtk.SortType.DESCENDING),
            SearchColumn('description', title=_('Description'),
                         data_type=str, expand=True),
            SearchColumn('client_name', title=_('Client'), data_type=str),
            SearchColumn('phone_number', title=_('Phone'), data_type=str,
                         visible=False, format_func=format_phone_number),
            SearchColumn('email', title=_('Email'), data_type=str,
                         visible=False),
            SearchColumn('sellable_category', title=_('Category'), data_type=str,
                         visible=False),
            QuantityColumn('quantity', title=_('Qty'), use_having=True),
            SearchColumn('price', title=_('Avg price'), data_type=currency,
                         use_having=True),
            SearchColumn('total', title=_('Total'), data_type=currency,
                         use_having=True)
        ]
        return columns
Пример #32
0
    def create_filters(self):
        self.set_text_field_columns(['description', 'message'])
        self.search.set_query(self.executer_query)

        # Date
        date_filter = DateSearchFilter(_("Date:"))
        self.search.add_filter(date_filter)
        self.date_filter = date_filter
        if self._date:
            date_filter.mode.select_item_by_position(5)
            date_filter.start_date.set_date(self._date)
            self.search.refresh()
Пример #33
0
 def search_for_date(self, date):
     dfilter = DateSearchFilter(_("Expected receival date"))
     dfilter.set_removable()
     dfilter.select(data=DateSearchFilter.Type.USER_DAY)
     self.add_filter(dfilter, columns=["expected_receival_date"])
     dfilter.start_date.set_date(date)
     self.refresh()
Пример #34
0
    def create_filters(self):
        self.set_text_field_columns(['description'])
        self.search.set_query(self.executer_query)

        # Date
        date_filter = DateSearchFilter(_('Date:'))
        self.search.add_filter(date_filter)
        self.date_filter = date_filter

        # Branch
        branch_filter = self.create_branch_filter(_('In Branch:'))
        self.add_filter(branch_filter, columns=[])
        self.branch_filter = branch_filter
Пример #35
0
 def search_for_date(self, date):
     self.main_filter.combo.select(self._not_delivered_filter_item)
     dfilter = DateSearchFilter(_("Estimated finish"))
     dfilter.set_removable()
     dfilter.select(data=DateSearchFilter.Type.USER_DAY)
     self.add_filter(dfilter, columns=["estimated_finish"])
     dfilter.start_date.set_date(date)
     self.refresh()
Пример #36
0
 def search_for_date(self, date):
     self.main_filter.select(None)
     dfilter = DateSearchFilter(_("Paid or due date"))
     dfilter.set_removable()
     dfilter.select(data=DateSearchFilter.Type.USER_DAY)
     self.add_filter(dfilter, columns=["paid_date", "due_date"])
     dfilter.start_date.set_date(date)
     self.refresh()
Пример #37
0
    def create_filters(self):
        self.set_text_field_columns(["medic_name", "description", "code"])

        # Dont set a limit here, otherwise it might break the summary
        executer = self.search.get_query_executer()
        executer.set_limit(-1)

        branch_filter = self.create_branch_filter(_("In Branch:"))
        self.add_filter(branch_filter, SearchFilterPosition.TOP, columns=[Sale.branch_id])

        self._date_filter = DateSearchFilter(_("Date:"))
        self._date_filter.select(data=DateSearchFilter.Type.USER_INTERVAL)
        self.add_filter(self._date_filter, SearchFilterPosition.BOTTOM, columns=[Sale.confirm_date])
        self.search.set_summary_label("total", label=_(u"Total:"), format="<b>%s</b>")
Пример #38
0
    def __init__(self, store):
        BasicDialog.__init__(self, title=self.title)
        self.justify_label(gtk.JUSTIFY_CENTER)

        self.store = store
        self.ok_button.set_label(_("Generate"))

        self.date_filter = DateSearchFilter(_('Month:'))
        self.date_filter.set_use_date_entries(False)
        self.date_filter.clear_options()
        self._populate_date_filter(self.date_filter)
        self.date_filter.select()

        self.add(self.date_filter)
        self.date_filter.show()
Пример #39
0
    def __init__(self, store):
        self.store = store

        self.date_filter = DateSearchFilter(_('Year:'))
        self.date_filter.clear_options()
        self._populate_date_filter(self.date_filter)
        self.date_filter.select()
        self.date_filter.set_use_date_entries(False)

        BasicDialog.__init__(self, title=self.title)
        self.main_label.set_justify(Gtk.Justification.CENTER)

        self.ok_button.set_label(_("Generate"))
        self.add(self.date_filter)
        self.date_filter.show()
Пример #40
0
    def create_filters(self):
        self.set_text_field_columns(['salesperson_name', 'identifier_str'])

        self._salesperson_filter = self.create_salesperson_filter(_("Sold by:"))
        self.add_filter(self._salesperson_filter, SearchFilterPosition.TOP,
                        callback=self._get_salesperson_query)

        # Adding a filter by date with custom interval
        self._date_filter = DateSearchFilter(_("Date:"))
        self._date_filter.select(data=DateSearchFilter.Type.USER_INTERVAL)
        if sysparam.get_bool('SALE_PAY_COMMISSION_WHEN_CONFIRMED'):
            self.add_filter(self._date_filter, SearchFilterPosition.BOTTOM,
                            columns=[self.search_spec.confirm_date])
        else:
            self.add_filter(self._date_filter, SearchFilterPosition.BOTTOM,
                            columns=[self.search_spec.paid_date])
Пример #41
0
    def create_filters(self):
        self.set_text_field_columns([
            'source_branch_name', 'destination_branch_name', 'identifier_str'
        ])

        # Date
        self.date_filter = DateSearchFilter(_('Date:'))
        self.add_filter(self.date_filter, columns=['open_date', 'finish_date'])

        # Status
        self.status_filter = ComboSearchFilter(_('With status:'),
                                               self._get_status_options())
        self.status_filter.select('pending')
        executer = self.search.get_query_executer()
        executer.add_filter_query_callback(self.status_filter,
                                           self._get_status_query)
        self.add_filter(self.status_filter, position=SearchFilterPosition.TOP)
Пример #42
0
    def create_filters(self):
        self.set_text_field_columns([
            'source_branch_name', 'destination_branch_name', 'identifier_str'
        ])

        # Date
        self.date_filter = DateSearchFilter(_('Date:'))
        self.add_filter(self.date_filter,
                        columns=['open_date', 'receival_date'])

        # Branch
        self.branch_filter = self.create_branch_filter(_('To branch:'))
        self.add_filter(self.branch_filter, columns=['destination_branch_id'])

        # Status
        statuses = self._get_status_values()
        self.status_filter = ComboSearchFilter(_('With status:'), statuses)
        self.status_filter.select(None)
        self.add_filter(self.status_filter,
                        columns=['status'],
                        position=SearchFilterPosition.TOP)
Пример #43
0
    def _setup_slaves(self):
        self.search = SearchSlave(self._get_columns(),
                                  restore_name=self.__class__.__name__,
                                  search_spec=QuotationView,
                                  store=self.store)
        self.attach_slave('search_group_holder', self.search)

        self.search.set_text_field_columns(['supplier_name', 'identifier_str'])
        filter = self.search.get_primary_filter()
        filter.set_label(_(u'Supplier:'))
        self.search.focus_search_entry()
        self.search.results.connect('selection-changed',
                                    self._on_searchlist__selection_changed)
        self.search.results.connect('row-activated',
                                    self._on_searchlist__row_activated)

        date_filter = DateSearchFilter(_('Date:'))
        self.search.add_filter(date_filter, columns=['open_date', 'deadline'])

        self.edit_button.set_sensitive(False)
        self.remove_button.set_sensitive(False)
Пример #44
0
 def create_filters(self):
     self._date_filter = DateSearchFilter(_("Date:"))
     self._date_filter.select(data=DateSearchFilter.Type.USER_INTERVAL)
     self.add_filter(self._date_filter, columns=[Sale.confirm_date])
     self.search.set_summary_label('quantity', label=_(u'Total:'),
                                   format='<b>%s</b>')
Пример #45
0
class TillDailyMovementDialog(BaseEditor):
    """Shows informations related to till operations over a daterange.
    It can also be filtered by branch.
    """

    title = _("Daily Movement")
    hide_footer = True
    size = (950, 450)
    model_type = Settable
    gladefile = "TillDailyMovementDialog"
    proxy_widgets = ['branch', 'in_subtotal', 'in_credit', 'in_total',
                     'out_subtotal', 'out_credit', 'out_total']

    #
    #  Private
    #

    def _setup_widgets(self):
        # Branches combo
        items = api.get_branches_for_filter(self.store)
        self.branch.prefill(items)

        # Daterange filter
        self.date_filter = DateSearchFilter(_(u'Date:'))
        self.date_filter.clear_options()
        self.date_filter.add_custom_options()
        for option in [Today, Yesterday, LastWeek, LastMonth]:
            self.date_filter.add_option(option)
        self.date_filter.select(position=0)
        self.daterange_hbox.pack_start(self.date_filter, False, False, 0)
        self.date_filter.show_all()

        # Setting report lists' columns
        self.sales_list.set_columns(self._get_sales_columns())
        self.inpayments_list.set_columns(self._get_lonely_payments_columns())
        self.purchases_list.set_columns(self._get_purchases_columns())
        self.outpayments_list.set_columns(self._get_lonely_payments_columns())
        self.return_sales_list.set_columns(self._get_return_sales_columns())
        self.supplies_list.set_columns(self._get_till_columns())
        self.removals_list.set_columns(self._get_till_columns())
        self.permethod_list.set_columns(self._get_permethod_columns())
        self.percard_list.set_columns(self._get_percard_columns())

        # Print button is insensitive, until the first report is generated
        self.print_button.set_sensitive(False)

        self._setup_summary_labels()

    def _get_sales_columns(self):
        return [IdentifierColumn('identifier', title=_('Sale #'), sorted=True),
                Column('salesperson', title=_('Sales Person'), data_type=str),
                Column('client', title=_('Client'), data_type=str, expand=True),
                Column('branch', title=_('Branch'), data_type=str, visible=False),
                Column('value', title=_('Value'), data_type=str,
                       justify=Gtk.Justification.RIGHT)]

    def _get_lonely_payments_columns(self):
        return [IdentifierColumn('identifier', title=_('Payment #'), sorted=True),
                Column('method', title=_('Method'), data_type=str),
                Column('description', title=_('Description'), expand=True,
                       data_type=str),
                Column('branch', title=_('Branch'), data_type=str, visible=False),
                Column('value', title=_('Payment Value'), data_type=currency)]

    def _get_purchases_columns(self):
        return [IdentifierColumn('identifier', title=_('Code #'), sorted=True),
                Column('status_str', title=_('Status'), data_type=str),
                Column('responsible_name', title=_('Responsible'), expand=True,
                       data_type=str),
                Column('branch_name', title=_('Branch'), data_type=str),
                Column('notes', title=_('Notes'), data_type=str),
                Column('supplier_name', title=_('Supplier'), data_type=str),
                Column('purchase_total', title=_('Value'), data_type=currency)]

    def _get_return_sales_columns(self):
        return [IdentifierColumn('identifier', title=_('Code #'), sorted=True),
                Column('salesperson', title=_('Sales Person'), data_type=str),
                Column('client', title=_('Client'), expand=True, data_type=str),
                Column('return_date', title=_('Return Date'),
                       data_type=datetime.date),
                Column('branch', title=_('Branch'), data_type=str, visible=False),
                Column('value', title=_('Sale Value'), data_type=currency)]

    def _get_till_columns(self):
        return [IdentifierColumn('identifier', title=_('Entry #'), sorted=True),
                Column('description', title=_('Description'), data_type=str,
                       expand=True),
                Column('branch_name', title=_('Branch'), data_type=str, visible=False),
                Column('value', title=_('Value'), data_type=currency)]

    def _get_permethod_columns(self):
        return [Column('method', title=_('Payment Method'), sorted=True,
                       expand=True),
                Column('in_value', title=_('Income Total'), data_type=currency),
                Column('out_value', title=_('Outgoing Total'),
                       data_type=currency)]

    def _get_percard_columns(self):
        return [Column('provider', title=_('Provider Name'), data_type=str,
                       expand=True),
                Column('income', title=_('Income Total'), data_type=currency)]

    def _create_summary_label(self, report, column='value', label=None):
        # Setting tha data
        obj_list = getattr(self, report + '_list')
        box = getattr(self, report + '_vbox')
        if label is None:
            label = _('Total:')
        label = '<b>%s</b>' % api.escape(label)
        value_format = '<b>%s</b>'

        # Creating the label
        label = SummaryLabel(klist=obj_list, column=column, label=label,
                             value_format=value_format)

        # Displaying the label
        box.pack_start(label, False, False, 0)
        label.show()
        return label

    def _setup_summary_labels(self):
        # Supplies
        self.supplies_label = self._create_summary_label('supplies')
        # Removals
        self.removals_label = self._create_summary_label('removals')
        # Percard
        self.percard_label = self._create_summary_label('percard',
                                                        column='income')

    def _update_summary_labels(self):
        self.supplies_label.update_total()
        self.removals_label.update_total()
        self.percard_label.update_total()
        self.proxy.update_many(('in_subtotal', 'in_credit', 'in_total',
                                'out_subtotal', 'out_credit', 'out_total'))

    def _generate_dailymovement_data(self, store):
        query = And(Payment.status.is_in([Payment.STATUS_PENDING,
                                          Payment.STATUS_PAID]),
                    self._get_query(Payment.open_date, Payment.branch))

        # Keys are the sale objects, and values are lists with all payments
        self.sales = collections.OrderedDict()

        # Keys are the returned sale objects, and values are lists with all payments
        self.return_sales = collections.OrderedDict()
        self.purchases = collections.OrderedDict()

        # lonely input and output payments
        self.lonely_in_payments = []
        self.lonely_out_payments = []

        # values are lists with the first element the summary of the input, and
        # the second the summary of the output
        method_summary = {}
        self.card_summary = {}

        result = store.find(DailyInPaymentView, query)
        for p in result.order_by(Sale.identifier, Payment.identifier):
            if p.sale:
                subtotal = p.sale_subtotal
                total = p.sale.get_total_sale_amount(subtotal)
                salesperson = p.salesperson_name or _('Not Specified')
                client = p.client_name or _('Not Specified')
                sale = DailyMovementSale(identifier=p.sale.identifier,
                                         salesperson=salesperson,
                                         client=client,
                                         branch=p.branch_name,
                                         value=get_formatted_price(total))
                sale_payments = self.sales.setdefault(sale,
                                                      collections.OrderedDict())
                details = ''
                method_desc = p.method.get_description()
                if p.check_data:
                    account = p.check_data.bank_account
                    numbers = sorted(
                        payment.payment_number for payment
                        in p.sale.payments if bool(payment.payment_number))
                    # Ensure that the check numbers are ordered
                    parts = []
                    if account.bank_number:
                        parts.append(_(u'Bank: %s') % account.bank_number)
                    if account.bank_branch:
                        parts.append(_(u'Agency: %s') % account.bank_branch)
                    if account.bank_account:
                        parts.append(_(u'Account: %s') % account.bank_account)
                    if numbers:
                        parts.append(_(u'Numbers: %s') % ', '.join(numbers))
                    details = ' / '.join(parts)

                if p.card_data:
                    if p.card_data.card_type == CreditCardData.TYPE_DEBIT:
                        method_desc += ' ' + _('Debit')
                    else:
                        method_desc += ' ' + _(u'Credit')
                    details = '%s - %s - %s' % (p.card_data.auth,
                                                p.card_data.provider.short_name or '',
                                                p.card_data.device.description or '')

                key = (method_desc, details)
                item = sale_payments.setdefault(key, [0, 0])
                item[0] += p.value
                item[1] += 1

            else:
                self.lonely_in_payments.append(p)

            method_summary.setdefault(p.method, [0, 0])
            method_summary[p.method][0] += p.value
            if p.card_data:
                type_desc = p.card_data.short_desc[p.card_data.card_type]
                key = (p.card_data.provider.short_name, type_desc)
                self.card_summary.setdefault(key, 0)
                self.card_summary[key] += p.value

        result = store.find(DailyOutPaymentView, query)
        for p in result.order_by(Payment.identifier):
            if p.purchase:
                purchase_payments = self.purchases.setdefault(p.purchase, [])
                purchase_payments.append(p)
            elif p.sale:
                subtotal = p.sale_subtotal
                value = p.sale.get_total_sale_amount(subtotal)
                salesperson = p.salesperson_name or _('Not Specified')
                client = p.client_name or _('Not Specified')
                sale = DailyMovementSale(identifier=p.sale.identifier,
                                         salesperson=salesperson,
                                         client=client,
                                         return_date=p.sale.return_date,
                                         branch=p.branch_name,
                                         value=value)
                return_sales_payment = self.return_sales.setdefault(sale, [])
                return_sales_payment.append(p)
            else:
                self.lonely_out_payments.append(p)

            method_summary.setdefault(p.method, [0, 0])
            method_summary[p.method][1] += p.value

        self.method_summary = []
        for method, (in_value, out_value) in method_summary.items():
            self.method_summary.append((method,
                                        in_value,
                                        out_value))
        self.method_summary.sort(key=lambda m: _(m[0].description))

        # Till removals
        query = And(Eq(TillEntry.payment_id, None),
                    self._get_query(TillEntry.date, TillEntry.branch),
                    TillEntry.value < 0)
        self.till_removals = store.find(TillEntry, query)

        # Till supply
        query = And(Eq(TillEntry.payment_id, None),
                    self._get_query(TillEntry.date, TillEntry.branch),
                    TillEntry.value > 0)
        self.till_supplies = store.find(TillEntry, query)

    def _show_lonely_payments(self, payments, widget):
        widget.clear()
        for payment in payments:
            payment_data = Settable(identifier=payment.identifier,
                                    method=payment.method.get_description(),
                                    description=payment.description,
                                    branch=payment.branch_name,
                                    value=payment.value)
            widget.append(payment_data)

    def _show_report(self):
        self._generate_dailymovement_data(self.store)

        # Sale data
        self.sales_list.clear()
        for sale, payments in self.sales.items():
            self.sales_list.append(None, sale)
            for details, values in payments.items():
                value = '%s (%sx)' % (get_formatted_price(values[0]), values[1])
                payment_data = Settable(identifier=None,
                                        salesperson=details[0],
                                        client=details[1],
                                        value=value)
                self.sales_list.append(sale, payment_data)

        # Lonely in payments
        self._show_lonely_payments(self.lonely_in_payments,
                                   self.inpayments_list)

        # Purchase data
        self.purchases_list.clear()
        for purchase, payments in self.purchases.items():
            self.purchases_list.append(None, purchase)
            for payment in payments:
                # TODO Add details refering to Bank, Agency later
                payment_data = Settable(identifier=payment.identifier,
                                        notes=payment.method.get_description())
                self.purchases_list.append(purchase, payment_data)

        # Lonely out payments
        self._show_lonely_payments(self.lonely_out_payments,
                                   self.outpayments_list)

        # Return sales
        self.return_sales_list.clear()
        for sale, payments in self.return_sales.items():
            self.return_sales_list.append(None, sale)
            for payment in payments:
                payment_data = Settable(identifier=payment.identifier,
                                        salesperson=payment.method.get_description(),
                                        client=payment.description,
                                        value=get_formatted_price(payment.value))
                self.return_sales_list.append(sale, payment_data)

        # Supplies
        self.supplies_list.clear()
        self.supplies_list.add_list(self.till_supplies)

        # Removals
        self.removals_list.clear()
        self.removals_list.add_list(self.till_removals)

        # Summary's per payment method data
        self.permethod_list.clear()
        self.model.in_subtotal = self.model.out_subtotal = 0
        self.model.in_credit = self.model.out_credit = currency(0)
        for method in self.method_summary:
            method_data = Settable(method=_(method[0].description),
                                   in_value=method[1],
                                   out_value=method[2])
            self.permethod_list.append(method_data)
            self.model.in_subtotal += method[1]
            self.model.out_subtotal += method[2]
            if method[0].method_name == 'credit':
                self.model.in_credit = currency(method[1])
                self.model.out_credit = currency(method[2])

        self.model.in_subtotal = currency(self.model.in_subtotal)
        self.model.out_subtotal = currency(self.model.out_subtotal)
        self.model.in_total = currency(self.model.in_subtotal -
                                       self.model.in_credit)
        self.model.out_total = currency(self.model.out_subtotal -
                                        self.model.out_credit)

        # Summary's per card provider data
        self.percard_list.clear()
        keys = list(self.card_summary.keys())
        for key in sorted(keys):
            card_summary_data = Settable(provider=key[0] + ' ' + key[1],
                                         income=self.card_summary[key])
            self.percard_list.append(card_summary_data)

        self._update_summary_labels()

    def _get_query(self, date_attr, branch_attr):
        daterange = self.get_daterange()
        query = [Date(date_attr) >= Date(daterange[0]),
                 Date(date_attr) <= Date(daterange[1])]

        branch = self.model.branch
        if branch is not None:
            query.append(branch_attr == branch)
        return And(*query)

    #
    # Public API
    #

    def get_daterange(self):
        start = self.date_filter.get_start_date()
        end = self.date_filter.get_end_date()
        return (start, end)

    def set_daterange(self, start, end=None):
        self.date_filter.set_state(start, end)

    #
    # BaseEditor Hooks
    #

    def create_model(self, store):
        return Settable(branch=api.get_current_branch(store),
                        in_total=currency(0), in_credit=currency(0),
                        in_subtotal=currency(0), out_total=currency(0),
                        out_credit=currency(0), out_subtotal=currency(0))

    def setup_proxies(self):
        self._setup_widgets()
        self.proxy = self.add_proxy(self.model, TillDailyMovementDialog.proxy_widgets)

    #
    # Callbacks
    #

    def on_search_button__clicked(self, widget):
        self._show_report()
        self.print_button.set_sensitive(True)

    def on_print_button__clicked(self, widget):
        branch = self.model.branch
        daterange = self.get_daterange()
        print_report(TillDailyMovementReport, self.store, branch, daterange, self)
Пример #46
0
 def create_filters(self):
     date_filter = DateSearchFilter(_('Date:'))
     self.search.add_filter(date_filter, columns=[Sale.confirm_date])
     self.date_filter = date_filter
Пример #47
0
 def create_filters(self):
     self.search.set_query(self.executer_query)
     date_filter = DateSearchFilter(_('Date:'))
     self.search.add_filter(date_filter)
     self.date_filter = date_filter
Пример #48
0
class TillHistoryDialog(SearchDialog):
    size = (780, -1)
    search_spec = TillEntry
    selection_mode = Gtk.SelectionMode.MULTIPLE
    searchbar_labels = _('Till Entries matching:')
    title = _('Till history')

    #
    # SearchDialog
    #

    def get_columns(self, *args):
        return [
            IdentifierColumn('identifier', title=_('Entry #'), sorted=True),
            Column('date', _('Date'), data_type=datetime.date),
            Column('time', _('Time'), data_type=datetime.time),
            Column('description', _('Description'), data_type=str,
                   expand=True),
            ColoredColumn('value',
                          _('Value'),
                          data_type=currency,
                          color='red',
                          data_func=payment_value_colorize,
                          width=140)
        ]

    def create_filters(self):
        self.set_text_field_columns(['description'])

        self.date_filter = DateSearchFilter(_('Date:'))
        self.date_filter.select(Today)
        self.add_filter(self.date_filter, columns=['date'])
        # add summary label
        value_format = '<b>%s</b>'
        total_label = '<b>%s</b>' % api.escape(_(u'Total:'))
        self.search.set_summary_label('value', total_label, value_format)

    def setup_widgets(self):
        self.results.set_visible_rows(10)
        self.results.connect('has-rows', self._has_rows)

        self._add_editor_button(_('Cash _Add...'), CashAdvanceEditor,
                                STOQ_MONEY)
        self._add_editor_button(_('Cash _In...'), CashInEditor, STOQ_MONEY_ADD)
        self._add_editor_button(_('Cash _Out...'), CashOutEditor,
                                STOQ_MONEY_REMOVE)

        self.print_button = Gtk.Button.new_from_stock(Gtk.STOCK_PRINT)
        self.print_button.set_property("use-stock", True)
        self.print_button.connect('clicked', self._print_button_clicked)
        self.action_area.set_layout(Gtk.ButtonBoxStyle.START)
        self.action_area.pack_end(self.print_button, False, False, 6)
        self.print_button.show()
        self.print_button.set_sensitive(False)

    #
    # Private API
    #

    def _add_editor_button(self, name, editor_class, stock):
        button = self.add_button(name, stock=stock)
        button.connect('clicked', self._run_editor, editor_class)
        button.show()

    def _print_button_clicked(self, button):
        print_report(TillHistoryReport,
                     self.results,
                     list(self.results),
                     filters=self.search.get_search_filters())

    def _run_editor(self, button, editor_class):
        with api.new_store() as store:
            run_dialog(editor_class, self, store)
        if store.committed:
            self.search.refresh()
            self.results.unselect_all()
            if len(self.results):
                self.results.select(self.results[-1])

    def _has_rows(self, results, obj):
        self.print_button.set_sensitive(obj)
Пример #49
0
    def add_filter_by_attribute(self, attr, title, data_type, valid_values=None,
                                callback=None, use_having=False,
                                multiple_selection=False):
        """Add a filter accordingly to the attributes specified

        :param attr: attribute that will be filtered. This can be either the
          name of the attribute or the attribute itself.
        :param title: the title of the filter that will be visible in the
                      interface
        :param data_type: the attribute type (str, bool, decimal, etc)
        :param callback: the callback function that will be triggered
        :param use_having: use having expression in the query
        """
        if data_type is not bool:
            title += ':'

        if data_type == datetime.date:
            filter = DateSearchFilter(title)
            if valid_values:
                filter.clear_options()
                filter.add_custom_options()
                for opt in valid_values:
                    filter.add_option(opt)
                filter.select(valid_values[0])

        elif (data_type == decimal.Decimal or
              data_type == int or
              data_type == currency):
            filter = NumberSearchFilter(title)
            if data_type != int:
                filter.set_digits(2)
        elif data_type == str:
            if multiple_selection:
                filter = MultiSearchFilter(title, valid_values)
            elif valid_values:
                filter = ComboSearchFilter(title, valid_values)
                filter.enable_advanced()
            else:
                filter = StringSearchFilter(title)
                filter.enable_advanced()
        elif data_type == bool:
            filter = BoolSearchFilter(title)
        else:
            raise NotImplementedError(title, data_type)

        filter.set_removable()
        self.add_filter(filter, columns=[attr],
                        callback=callback,
                        use_having=use_having)

        if data_type is not bool:
            label = filter.get_title_label()
            label.set_alignment(1.0, 0.5)
            self.label_group.add_widget(label)
        combo = filter.get_mode_combo()
        if combo:
            self.combo_group.add_widget(combo)

        return filter
Пример #50
0
class SintegraDialog(BasicDialog):
    title = _('Fiscal Printer History')

    def __init__(self, store):
        BasicDialog.__init__(self, title=self.title)
        self.main_label.set_justify(gtk.JUSTIFY_CENTER)

        self.store = store
        self.ok_button.set_label(_("Generate"))

        self.date_filter = DateSearchFilter(_('Month:'))
        self.date_filter.set_use_date_entries(False)
        self.date_filter.clear_options()
        self._populate_date_filter(self.date_filter)
        self.date_filter.select()

        self.add(self.date_filter)
        self.date_filter.show()

    def confirm(self):
        start = self.date_filter.get_start_date()
        end = self.date_filter.get_end_date()
        filename = save(_("Save Sintegra file"), self.get_toplevel(),
                        "sintegra-%s.txt" % (start.strftime('%Y-%m'), ))
        if not filename:
            return

        try:
            generator = StoqlibSintegraGenerator(self.store, start, end)
            generator.write(filename)
        except SintegraError as e:
            warning(str(e))
            return

        self.close()

    #
    # Private
    #

    def _populate_date_filter(self, date_filter):
        # The options we want to show to the users are the following:
        #   'May 2007'
        #   'June 2007'
        #   ...
        #   'September 2008'

        initial_date = self.store.find(SystemTable).min(
            SystemTable.updated).date()

        # Start is the first day of the month
        # End is the last day of the month
        start = initial_date + relativedelta(day=1)
        end = localtoday().date() + relativedelta(day=31)
        intervals = []
        while start < end:
            intervals.append((start, start + relativedelta(day=31)))
            start = start + relativedelta(months=1)

        # When we have the list of intervals, add them to the list and
        # make sure that they are translated
        month_names = get_month_names()
        for start, end in intervals:
            # Translators: Do not translate 'month' and 'year'. You can
            #              change it's positions. In the way it is,
            #              it will product for example 'December 2012'
            name = _('{month} {year}').format(month=month_names[start.month -
                                                                1],
                                              year=start.year)
            date_filter.add_option_fixed_interval(name, start, end, position=0)

    def _date_filter_query(self, search_spec, column):
        executer = QueryExecuter(self.store)
        executer.set_filter_columns(self.date_filter, [column])
        executer.set_table(search_spec)
        return executer.search([self.date_filter.get_state()])
Пример #51
0
    def add_filter_by_column(self, column):
        """Add a filter accordingly to the column specification

        :param column: a SearchColumn instance
        """
        title = column.get_search_label()
        if column.data_type is not bool:
            title += ':'

        if column.data_type == datetime.date:
            filter = DateSearchFilter(title)
            if column.valid_values:
                filter.clear_options()
                filter.add_custom_options()
                for opt in column.valid_values:
                    filter.add_option(opt)
                filter.select(column.valid_values[0])

        elif (column.data_type == decimal.Decimal or column.data_type == int
              or column.data_type == currency):
            filter = NumberSearchFilter(title)
            if column.data_type != int:
                filter.set_digits(2)
        elif column.data_type == str:
            if column.valid_values:
                filter = ComboSearchFilter(title, column.valid_values)
            else:
                filter = StringSearchFilter(title)
                filter.enable_advanced()
        elif column.data_type == bool:
            filter = BoolSearchFilter(title)
        else:
            raise NotImplementedError(title, column.data_type)

        filter.set_removable()
        attr = column.search_attribute or column.attribute
        self.add_filter(filter,
                        columns=[attr],
                        callback=column.search_func,
                        use_having=column.use_having)

        if column.data_type is not bool:
            label = filter.get_title_label()
            label.set_alignment(1.0, 0.5)
            self.label_group.add_widget(label)
        combo = filter.get_mode_combo()
        if combo:
            self.combo_group.add_widget(combo)

        return filter
Пример #52
0
class TransactionPage(object):
    # shows either a list of:
    #   - transactions
    #   - payments
    def __init__(self, model, app, parent):
        self.model = model
        self.app = app
        self.parent_window = parent
        self._block = False

        self._create_search()
        self._add_date_filter()

        self._setup_search()
        self.refresh()

    def get_toplevel(self):
        return self.parent_window

    def _create_search(self):
        self.search = SearchSlave(self._get_columns(self.model.kind),
                                  store=self.app.store)
        self.search.connect('result-item-activated',
                            self._on_search__item_activated)
        self.search.enable_advanced_search()
        self.search.set_result_view(FinancialSearchResults)
        self.result_view = self.search.result_view
        self.result_view.page = self
        tree_view = self.search.result_view.get_treeview()
        tree_view.set_rules_hint(True)
        tree_view.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)

    def _add_date_filter(self):
        self.date_filter = DateSearchFilter(_('Date:'))
        self.date_filter.clear_options()
        self.date_filter.add_option(Any, 0)
        year = datetime.datetime.today().year
        month_names = get_month_names()
        for i, month in enumerate(month_names):
            name = month_names[i]
            option = type(name + 'Option', (MonthOption, ),
                          {'name': _(name),
                           'month': i + 1,
                           'year': year})
            self.date_filter.add_option(option, i + 1)
        self.date_filter.add_custom_options()
        self.date_filter.mode.select_item_by_position(0)
        self.search.add_filter(self.date_filter)

    def _append_date_query(self, field):
        date = self.date_filter.get_state()
        queries = []
        if isinstance(date, DateQueryState) and date.date is not None:
            queries.append(Date(field) == date.date)
        elif isinstance(date, DateIntervalQueryState):
            queries.append(Date(field) >= date.start)
            queries.append(Date(field) <= date.end)
        return queries

    def _payment_query(self, store):
        executer = self.search.get_query_executer()
        search_spec = executer.search_spec
        queries = self._append_date_query(search_spec.due_date)
        if queries:
            return store.find(search_spec, And(*queries))

        return store.find(search_spec)

    def _transaction_query(self, store):
        queries = [Or(self.model.id == AccountTransaction.account_id,
                      self.model.id == AccountTransaction.source_account_id)]

        queries.extend(self._append_date_query(AccountTransaction.date))
        return store.find(AccountTransactionView, And(*queries))

    def show(self):
        self.search.show()

    def _setup_search(self):
        if self.model.kind == 'account':
            self.search.set_search_spec(AccountTransactionView)
            self.search.set_text_field_columns(['description'])
            self.search.set_query(self._transaction_query)
        elif self.model.kind == 'payable':
            self.search.set_text_field_columns(['description', 'supplier_name'])
            self.search.set_search_spec(OutPaymentView)
            self.search.set_query(self._payment_query)
        elif self.model.kind == 'receivable':
            self.search.set_text_field_columns(['description', 'drawee'])
            self.search.set_search_spec(InPaymentView)
            self.search.set_query(self._payment_query)
        else:
            raise TypeError("unknown model kind: %r" % (self.model.kind, ))

    def refresh(self):
        self.search.result_view.clear()
        if self.model.kind == 'account':
            transactions = AccountTransactionView.get_for_account(self.model, self.app.store)
            self.append_transactions(transactions)
        elif self.model.kind == 'payable':
            self._populate_payable_payments(OutPaymentView)
        elif self.model.kind == 'receivable':
            self._populate_payable_payments(InPaymentView)
        else:
            raise TypeError("unknown model kind: %r" % (self.model.kind, ))

    def _get_columns(self, kind):
        if kind in ['payable', 'receivable']:
            return self._get_payment_columns()
        else:
            return self._get_account_columns()

    def _get_account_columns(self):
        def format_withdrawal(value):
            if value < 0:
                return currency(abs(value)).format(symbol=True, precision=2)

        def format_deposit(value):
            if value > 0:
                return currency(value).format(symbol=True, precision=2)

        if self.model.account_type == Account.TYPE_INCOME:
            color_func = lambda x: False
        else:
            color_func = lambda x: x < 0
        return [Column('date', title=_("Date"), data_type=datetime.date, sorted=True),
                Column('code', title=_("Code"), data_type=unicode),
                Column('description', title=_("Description"),
                       data_type=unicode, expand=True),
                Column('account', title=_("Account"), data_type=unicode),
                Column('value',
                       title=self.model.account.get_type_label(out=False),
                       data_type=currency,
                       format_func=format_deposit),
                Column('value',
                       title=self.model.account.get_type_label(out=True),
                       data_type=currency,
                       format_func=format_withdrawal),
                ColoredColumn('total', title=_("Total"), data_type=currency,
                              color='red',
                              data_func=color_func)]

    def _get_payment_columns(self):
        return [SearchColumn('due_date', title=_("Due date"), data_type=datetime.date, sorted=True),
                IdentifierColumn('identifier', title=_("Code")),
                SearchColumn('description', title=_("Description"), data_type=unicode, expand=True),
                SearchColumn('value', title=_("Value"),
                             data_type=currency)]

    def append_transactions(self, transactions):
        for transaction in transactions:
            description = transaction.get_account_description(self.model)
            value = transaction.get_value(self.model)
            self._add_transaction(transaction, description, value)
        self.update_totals()

    def _populate_payable_payments(self, view_class):
        for view in self.app.store.find(view_class):
            self.search.result_view.append(view)

    def _add_transaction(self, transaction, description, value):
        item = Settable(transaction=transaction)
        self._update_transaction(item, transaction, description, value)
        self.search.result_view.append(item)
        return item

    def _update_transaction(self, item, transaction, description, value):
        item.account = description
        item.date = transaction.date
        item.description = transaction.description
        item.value = value
        item.code = transaction.code

    def update_totals(self):
        total = decimal.Decimal('0')
        for item in self.search.result_view:
            total += item.value
            item.total = total

    def _edit_transaction_dialog(self, item):
        store = api.new_store()
        if isinstance(item.transaction, AccountTransactionView):
            account_transaction = store.fetch(item.transaction.transaction)
        else:
            account_transaction = store.fetch(item.transaction)
        model = getattr(self.model, 'account', self.model)

        transaction = run_dialog(AccountTransactionEditor, self.app,
                                 store, account_transaction, model)

        if transaction:
            store.flush()
            self._update_transaction(item, transaction,
                                     transaction.edited_account.description,
                                     transaction.value)
            self.update_totals()
            self.search.result_view.update(item)
            self.app.accounts.refresh_accounts(self.app.store)
        store.confirm(transaction)
        store.close()

    def on_dialog__opened(self, dialog):
        dialog.connect('account-added', self.on_dialog__account_added)

    def on_dialog__account_added(self, dialog):
        self.app.accounts.refresh_accounts(self.app.store)

    def add_transaction_dialog(self):
        store = api.new_store()
        model = getattr(self.model, 'account', self.model)
        model = store.fetch(model)

        transaction = run_dialog(AccountTransactionEditor, self.app,
                                 store, None, model)
        if transaction:
            transaction.sync()
            value = transaction.value
            other = transaction.get_other_account(model)
            if other == model:
                value = -value
            item = self._add_transaction(transaction, other.description, value)
            self.update_totals()
            self.search.result_view.update(item)
            self.app.accounts.refresh_accounts(self.app.store)
        store.confirm(transaction)
        store.close()

    def _on_search__item_activated(self, objectlist, item):
        if self.model.kind == 'account':
            self._edit_transaction_dialog(item)
Пример #53
0
 def create_filters(self):
     self.set_text_field_columns(
         ['responsible_open_name', 'responsible_close_name'])
     self.date_filter = DateSearchFilter(_('Date:'))
     self.add_filter(self.date_filter,
                     columns=['opening_date', 'closing_date'])
Пример #54
0
class TillHistoryDialog(SearchDialog):
    size = (780, -1)
    search_spec = TillEntry
    selection_mode = gtk.SELECTION_MULTIPLE
    searchbar_labels = _('Till Entries matching:')
    title = _('Till history')

    #
    # SearchDialog
    #

    def get_columns(self, *args):
        return [IdentifierColumn('identifier', sorted=True),
                Column('date', _('Date'), data_type=datetime.date),
                Column('time', _('Time'), data_type=datetime.time),
                Column('description', _('Description'), data_type=str,
                       expand=True),
                ColoredColumn('value', _('Value'), data_type=currency,
                              color='red', data_func=payment_value_colorize,
                              width=140)]

    def create_filters(self):
        self.set_text_field_columns(['description'])

        self.date_filter = DateSearchFilter(_('Date:'))
        self.date_filter.select(Today)
        self.add_filter(self.date_filter, columns=['date'])
        # add summary label
        value_format = '<b>%s</b>'
        total_label = '<b>%s</b>' % api.escape(_(u'Total:'))
        self.search.set_summary_label('value', total_label, value_format)

    def setup_widgets(self):
        self.results.set_visible_rows(10)
        self.results.connect('has-rows', self._has_rows)

        self._add_editor_button(_('Cash _Add...'), CashAdvanceEditor,
                                STOQ_MONEY)
        self._add_editor_button(_('Cash _In...'), CashInEditor,
                                STOQ_MONEY_ADD)
        self._add_editor_button(_('Cash _Out...'), CashOutEditor,
                                STOQ_MONEY_REMOVE)

        self.print_button = gtk.Button(None, gtk.STOCK_PRINT, True)
        self.print_button.set_property("use-stock", True)
        self.print_button.connect('clicked', self._print_button_clicked)
        self.action_area.set_layout(gtk.BUTTONBOX_START)
        self.action_area.pack_end(self.print_button, False, False, 6)
        self.print_button.show()
        self.print_button.set_sensitive(False)

    #
    # Private API
    #

    def _add_editor_button(self, name, editor_class, stock):
        button = self.add_button(name, stock=stock)
        button.connect('clicked', self._run_editor, editor_class)
        button.show()

    def _print_button_clicked(self, button):
        till_entries = self.results.get_selected_rows() or list(self.results)
        print_report(TillHistoryReport, self.results, till_entries,
                     filters=self.search.get_search_filters())

    def _run_editor(self, button, editor_class):
        with api.trans() as store:
            run_dialog(editor_class, self, store)
        if store.committed:
            self.search.refresh()
            self.results.unselect_all()
            if len(self.results):
                self.results.select(self.results[-1])

    def _has_rows(self, results, obj):
        self.print_button.set_sensitive(obj)
Пример #55
0
    def create_filters(self):
        self.set_text_field_columns(['reason'])

        # Date
        date_filter = DateSearchFilter(_('Date:'))
        self.add_filter(date_filter, columns=['confirm_date'])