示例#1
0
文件: config.py 项目: 5l1v3r1/stoq-1
 def _set_admin_password(self, store):
     logger.info('_set_admin_password')
     adminuser = store.find(LoginUser,
                            username=USER_ADMIN_DEFAULT_NAME).one()
     if adminuser is None:
         raise DatabaseInconsistency(
             ("You should have a user with username: %s" %
              USER_ADMIN_DEFAULT_NAME))
     # Lets create a user without password and set a cookie so that it
     # auto login
     adminuser.set_password(u'')
     get_utility(ICookieFile).store('admin', '')
示例#2
0
 def _set_admin_password(self, store):
     logger.info('_set_admin_password')
     adminuser = store.find(LoginUser,
                            username=USER_ADMIN_DEFAULT_NAME).one()
     if adminuser is None:
         raise DatabaseInconsistency(
             ("You should have a user with username: %s"
              % USER_ADMIN_DEFAULT_NAME))
     # Lets create a user without password and set a cookie so that it
     # auto login
     adminuser.set_password(u'')
     get_utility(ICookieFile).store('admin', '')
示例#3
0
 def _idle_logout(self):
     # Before performing logout, verify that the currently opened window
     # is modal.
     from kiwi.component import get_utility
     from stoqlib.gui.base.dialogs import has_modal_window
     from stoqlib.lib.interfaces import ICookieFile
     # If not a modal window, logout.
     # Otherwise returns True to continue checking the automatic logout.
     if not has_modal_window():
         log.debug('Automatic logout')
         get_utility(ICookieFile).clear()
         self.quit(restart=True)
     return True
示例#4
0
    def _create_dialog(self):
        app_info = get_utility(IAppInfo, None)

        self._dialog = HIGAlertDialog(parent=self._parent,
                                      flags=gtk.DIALOG_MODAL,
                                      type=gtk.MESSAGE_WARNING)

        self._dialog.set_details_label(_("Details ..."))
        primary_fmt = _('We\'r sorry to inform you that an error occurred while '
                        'running %s. Please help us improving Stoq by sending a '
                        'automatically generated report about the incident.\n'
                        'Click on details to see the report text.')
        self._dialog.set_primary(primary_fmt % (app_info.get('name'), ),
                                 bold=False)

        self._create_details()
        self._create_comments()
        self._create_email()

        self._no_button = self._dialog.add_button(_('No thanks'),
                                                  gtk.RESPONSE_NO)
        self._yes_button = self._dialog.add_button(_('Send report'),
                                                   gtk.RESPONSE_YES)

        self._insert_tracebacks()
示例#5
0
    def cookie_login(self):
        if api.sysparam(api.get_default_store()).DISABLE_COOKIES:
            log.info("Cookies disable by parameter")
            return

        cookie_file = get_utility(ICookieFile)
        try:
            username, password = cookie_file.get()
        except CookieError:
            log.info("Not using cookie based login")
            return

        def is_md5(password):
            # This breaks for passwords that are 32 characters long,
            # uses only digits and lowercase a-f, pretty unlikely as
            # real-world password
            if len(password) != 32:
                return False
            for c in '1234567890abcdef':
                password = password.replace(c, '')
            return password == ''

        # Migrate old passwords to md5 hashes.
        if not is_md5(password):
            password = _encrypt_password(password)
            cookie_file.store(username, password)

        try:
            user = self._check_user(username, password)
        except (LoginError, UserProfileError, DatabaseError) as e:
            log.info("Cookie login failed: %r" % e)
            return

        log.info("Logging in using cookie credentials")
        return user
示例#6
0
    def _run_about(self):
        info = get_utility(IAppInfo)
        about = Gtk.AboutDialog()
        about.set_name(info.get("name"))
        about.set_version(info.get("version"))
        about.set_website(stoq.website)
        release_date = stoq.release_date
        about.set_comments(
            _('Release date: %s') %
            datetime.datetime(*release_date).strftime('%x'))
        about.set_copyright('Copyright (C) 2005-2012 Async Open Source')

        about.set_logo(render_logo_pixbuf('about'))

        # License

        if locale.getlocale()[0] == 'pt_BR':
            filename = 'COPYING.pt_BR'
        else:
            filename = 'COPYING'
        data = self._read_resource('docs', filename)
        about.set_license(data)

        # Authors & Contributors
        data = self._read_resource('docs', 'AUTHORS')
        lines = data.split('\n')
        lines.append('')  # separate authors from contributors
        data = self._read_resource('docs', 'CONTRIBUTORS')
        lines.extend([c.strip() for c in data.split('\n')])
        about.set_authors(lines)

        about.set_transient_for(get_current_toplevel())
        about.run()
        about.destroy()
示例#7
0
文件: operation.py 项目: rosalin/stoq
def get_payment_operation_manager():
    """Returns the payment operation manager"""
    pmm = get_utility(IPaymentOperationManager, None)

    if not pmm:
        from stoqlib.lib.payment import PaymentOperationManager
        pmm = PaymentOperationManager()
        provide_utility(IPaymentOperationManager, pmm)

        for method_name, klass in [
                (u'money', MoneyPaymentOperation),
                (u'check', CheckPaymentOperation),
                (u'bill', BillPaymentOperation),
                (u'card', CardPaymentOperation),
                (u'store_credit', StoreCreditPaymentOperation),
                (u'trade', TradePaymentOperation),
                (u'multiple', MultiplePaymentOperation),
                (u'deposit', DepositPaymentOperation),
                (u'online', OnlinePaymentOperation),
                (u'credit', CreditPaymentOperation),
        ]:
            pmm.register(method_name, klass())
        # Also, register InvalidPaymentOperation as a fallback operation
        pmm.register_fallback(InvalidPaymentOperation())

    return pmm
示例#8
0
def get_payment_operation_manager():
    """Returns the payment operation manager"""
    pmm = get_utility(IPaymentOperationManager, None)

    if not pmm:
        from stoqlib.lib.payment import PaymentOperationManager
        pmm = PaymentOperationManager()
        provide_utility(IPaymentOperationManager, pmm)

        for method_name, klass in [
            (u'money', MoneyPaymentOperation),
            (u'check', CheckPaymentOperation),
            (u'bill', BillPaymentOperation),
            (u'card', CardPaymentOperation),
            (u'store_credit', StoreCreditPaymentOperation),
            (u'trade', TradePaymentOperation),
            (u'multiple', MultiplePaymentOperation),
            (u'deposit', DepositPaymentOperation),
            (u'online', OnlinePaymentOperation),
            (u'credit', CreditPaymentOperation),
        ]:
            pmm.register(method_name, klass())
        # Also, register InvalidPaymentOperation as a fallback operation
        pmm.register_fallback(InvalidPaymentOperation())

    return pmm
示例#9
0
    def _run_about(self):
        info = get_utility(IAppInfo)
        about = gtk.AboutDialog()
        about.set_name(info.get("name"))
        about.set_version(info.get("version"))
        about.set_website(stoq.website)
        release_date = stoq.release_date
        about.set_comments(_('Release date: %s') %
                           datetime.datetime(*release_date).strftime('%x'))
        about.set_copyright('Copyright (C) 2005-2012 Async Open Source')

        about.set_logo(render_logo_pixbuf('about'))

        # License

        if locale.getlocale()[0] == 'pt_BR':
            filename = 'COPYING.pt_BR'
        else:
            filename = 'COPYING'
        data = self._read_resource('docs', filename)
        about.set_license(data)

        # Authors & Contributors
        data = self._read_resource('docs', 'AUTHORS')
        lines = data.split('\n')
        lines.append('')  # separate authors from contributors
        data = self._read_resource('docs', 'CONTRIBUTORS')
        lines.extend([c.strip() for c in data.split('\n')])
        about.set_authors(lines)

        about.set_transient_for(get_current_toplevel())
        about.run()
        about.destroy()
示例#10
0
    def do_button_press_event(self, event):
        if not self.flags() & gtk.HAS_FOCUS:
            self.grab_focus()

        if event.button == 1 and event.type == gtk.gdk.BUTTON_PRESS:
            app = get_utility(IGazpachoApp)
            # A widget type is selected in the palette.
            # Add a new widget of that type
            if app.add_class:
                gapi.create_gadget(app.get_current_project(), app.add_class,
                                   self)

            # Shift clicking circles through the widget tree by
            # choosing the parent of the currently selected widget.
            elif event.state & gtk.gdk.SHIFT_MASK:
                parent = get_parent(self)
                parent.project.selection.circle(self)

            # Control clicking adds or removes the widget from the
            # selection
            elif event.state & gtk.gdk.CONTROL_MASK:
                parent = get_parent(self)
                parent.project.selection.toggle(self)

            # otherwise we should be able to select placeholder
            # for paste operations
            else:
                parent = get_parent(self)
                parent.project.selection.set(self)

        elif event.button == 3 and event.type == gtk.gdk.BUTTON_PRESS:
            popup = PlaceholderPopup(command_manager, self)
            popup.pop(event)

        return True
示例#11
0
    def cookie_login(self):
        if api.sysparam.get_bool('DISABLE_COOKIES'):
            log.info("Cookies disable by parameter")
            return

        cookie_file = get_utility(ICookieFile)
        try:
            username, password = cookie_file.get()
        except CookieError:
            log.info("Not using cookie based login")
            return

        def is_md5(password):
            # This breaks for passwords that are 32 characters long,
            # uses only digits and lowercase a-f, pretty unlikely as
            # real-world password
            if len(password) != 32:
                return False
            for c in '1234567890abcdef':
                password = password.replace(c, '')
            return password == ''

        # Migrate old passwords to md5 hashes.
        if not is_md5(password):
            password = LoginUser.hash(password)
            cookie_file.store(username, password)

        try:
            user = self._check_user(username, password)
        except (LoginError, UserProfileError, DatabaseError) as e:
            log.info("Cookie login failed: %r" % e)
            return

        log.info("Logging in using cookie credentials")
        return user
示例#12
0
    def _create_dialog(self):
        app_info = get_utility(IAppInfo, None)

        self._dialog = HIGAlertDialog(parent=self._parent,
                                      flags=Gtk.DialogFlags.MODAL,
                                      type=Gtk.MessageType.WARNING)

        self._dialog.set_details_label(_("Details ..."))
        primary_fmt = _(
            'We\'r sorry to inform you that an error occurred while '
            'running %s. Please help us improving Stoq by sending a '
            'automatically generated report about the incident.\n'
            'Click on details to see the report text.')
        self._dialog.set_primary(primary_fmt % (app_info.get('name'), ),
                                 bold=False)

        self._create_details()
        self._create_comments()
        self._create_email()

        self._no_button = self._dialog.add_button(_('No thanks'),
                                                  Gtk.ResponseType.NO)
        self._yes_button = self._dialog.add_button(_('Send report'),
                                                   Gtk.ResponseType.YES)

        self._insert_tracebacks()
示例#13
0
    def _run_about(self):
        info = get_utility(IAppInfo)
        about = gtk.AboutDialog()
        about.set_name(info.get("name"))
        about.set_version(info.get("version"))
        about.set_website(stoq.website)
        release_date = stoq.release_date
        about.set_comments(_("Release date: %s") % datetime.datetime(*release_date).strftime("%x"))
        about.set_copyright("Copyright (C) 2005-2012 Async Open Source")

        about.set_logo(render_logo_pixbuf("about"))

        # License

        if locale.getlocale()[0] == "pt_BR":
            filename = "COPYING.pt_BR"
        else:
            filename = "COPYING"
        data = self._read_resource("docs", filename)
        about.set_license(data)

        # Authors & Contributors
        data = self._read_resource("docs", "AUTHORS")
        lines = data.split("\n")
        lines.append("")  # separate authors from contributors
        data = self._read_resource("docs", "CONTRIBUTORS")
        lines.extend([c.strip() for c in data.split("\n")])
        about.set_authors(lines)

        about.set_transient_for(get_current_toplevel())
        about.run()
        about.destroy()
示例#14
0
    def __init__(self, wizard, parent, store, order, payment_method,
                 outstanding_value=currency(0)):
        BaseEditor.__init__(self, store, order.group)

        self._method = payment_method
        dsm = get_utility(IDomainSlaveMapper)
        slave_class = dsm.get_slave_class(self._method)
        assert slave_class

        self.store.savepoint('before_payment_creation')

        #FIXME: This is a workaround to make the slave_class to ignore the
        #       payments created previously.
        class _InnerSlaveClass(slave_class):
            def get_created_adapted_payments(self):
                return []

        self.slave = _InnerSlaveClass(wizard, parent, self.store, order,
                                      self._method, outstanding_value)
        #FIXME: We need to control how many payments could be created, since
        #       we are ignoring the payments created previously.
        payments = order.group.get_valid_payments().find(
                                        Payment.method_id == self._method.id)
        max_installments = self._method.max_installments - payments.count()
        self.slave.installments_number.set_range(1, max_installments)

        self.attach_slave('place_holder', self.slave)
示例#15
0
    def _get_headers(self):
        user_agent = 'Stoq'
        app_info = get_utility(IAppInfo, None)
        if app_info:
            user_agent += ' %s' % (app_info.get('version'), )
        headers = {'User-Agent': [user_agent]}

        return headers
示例#16
0
    def get_permission_manager(cls):
        """Returns the payment operation manager"""
        pm = get_utility(IPermissionManager, None)

        if not pm:
            pm = PermissionManager()
            provide_utility(IPermissionManager, pm)
        return pm
示例#17
0
文件: webservice.py 项目: romaia/stoq
    def _get_headers(self):
        user_agent = "Stoq"
        app_info = get_utility(IAppInfo, None)
        if app_info:
            user_agent += " %s" % (app_info.get("version"),)
        headers = {"User-Agent": [user_agent]}

        return headers
示例#18
0
    def _get_headers(self):
        user_agent = 'Stoq'
        app_info = get_utility(IAppInfo, None)
        if app_info:
            user_agent += ' %s' % (app_info.get('version'), )
        headers = {'User-Agent': user_agent}

        return headers
示例#19
0
    def get_permission_manager(cls):
        """Returns the payment operation manager"""
        pm = get_utility(IPermissionManager, None)

        if not pm:
            pm = PermissionManager()
            provide_utility(IPermissionManager, pm)
        return pm
示例#20
0
    def _add_registers(self):
        appinfo = get_utility(IAppInfo)
        self.cat.add_software_house(async, appinfo.get('name'),
                                    appinfo.get('version'))

        self._add_ecf_identification()
        self._add_z_reduction_information()
        self._add_fiscal_coupon_information()
        self._add_other_documents()
示例#21
0
 def create_profile_template(cls, store, name,
                             has_full_permission=False):
     profile = cls(store=store, name=name)
     descr = get_utility(IApplicationDescriptions)
     for app_dir in descr.get_application_names():
         ProfileSettings(store=store,
                         has_permission=has_full_permission,
                         app_dir_name=app_dir, user_profile=profile)
     return profile
示例#22
0
    def _add_registers(self):
        appinfo = get_utility(IAppInfo)
        self.cat.add_software_house(company, appinfo.get('name'),
                                    appinfo.get('version'))

        self._add_ecf_identification()
        self._add_z_reduction_information()
        self._add_fiscal_coupon_information()
        self._add_other_documents()
示例#23
0
文件: splash.py 项目: 5l1v3r1/stoq-1
 def _get_label(self):
     info = get_utility(IAppInfo, None)
     if not info:
         return "Stoq"
     version = info.get("version")
     if ' ' in version:
         ver, rev = version.split(' ')
         version = '%s\n<span font="8">%s</span>' % (ver, GLib.markup_escape_text(rev))
     return _("Version %s") % (version, )
示例#24
0
    def setup_toplevel(self):
        """Add the action groups of Gazpacho to this toplevel and
        also set this toplevel transient for the main window.
        """
        widget = self.widget
        widget.add_accel_group(bar_manager.get_accel_group())

        # make window management easier by making created windows
        # transient for the editor window
        widget.set_transient_for(get_utility(IGazpachoApp).get_window())
示例#25
0
def get_payment_operation_manager():
    """Returns the payment operation manager"""
    pmm = get_utility(IPaymentOperationManager, None)

    if not pmm:
        from stoqlib.lib.payment import PaymentOperationManager
        pmm = PaymentOperationManager()
        provide_utility(IPaymentOperationManager, pmm)

    return pmm
示例#26
0
    def __init__(self):
        self.app = get_utility(IGazpachoApp)
        self.plugin_manager = get_utility(IPluginManager)
        ui_file = environ.find_resource('glade', 'preferences.glade')
        app_window = self.app.get_window()

        self.ob = ObjectBuilder(ui_file)
        self.dialog = self.ob.get_widget('dialog')

        # dialog setup
        self.dialog.set_modal(True)
        self.dialog.set_transient_for(app_window)

        # this should go into the glade file as soon as we get support for it
        close = self.ob.get_widget('close')
        close.connect('clicked', self.on_close__clicked)

        # setup each tab
        self._setup_plugins_tab()
示例#27
0
文件: runtime.py 项目: rg3915/stoq
def get_current_station(store):
    """Fetches the current station (computer) which we are running on

    :param store: a store
    :param: current station
    :rtype: BranchStation or ``None``
    """
    station = get_utility(ICurrentBranchStation, None)
    if station is not None:
        return store.fetch(station)
示例#28
0
def get_current_station(store):
    """Fetches the current station (computer) which we are running on

    :param store: a store
    :param: current station
    :rtype: BranchStation or ``None``
    """
    station = get_utility(ICurrentBranchStation, None)
    if station is not None:
        return store.fetch(station)
示例#29
0
def get_current_branch(store):
    """Fetches the current branch company.

    :param store: a store
    :returns: the current branch
    :rtype: a branch or ``None``
    """

    branch = get_utility(ICurrentBranch, None)
    if branch is not None:
        return store.fetch(branch)
示例#30
0
文件: runtime.py 项目: rg3915/stoq
def get_current_branch(store):
    """Fetches the current branch company.

    :param store: a store
    :returns: the current branch
    :rtype: a branch or ``None``
    """

    branch = get_utility(ICurrentBranch, None)
    if branch is not None:
        return store.fetch(branch)
示例#31
0
    def _quit_cb(self, action=None):
        unsaved_projects = [p for p in self._projects if p.changed]
        close = self._confirm_close_projects(unsaved_projects)
        if not close:
            return

        config.save()

        plugin_manager = get_utility(IPluginManager)
        plugin_manager.deactivate_all()
        gtk.main_quit()
示例#32
0
 def add_action_group(self):
     """Create and add an action group. This method will not create
     the action group directly but delegate to the command manager."""
     # nothing is selected, we create an action group
     dialog = GActionGroupDialog(
         get_utility(IGazpachoApp).get_window(), None)
     if dialog.run() == gtk.RESPONSE_OK:
         name = dialog.get_action_group_name()
         gaction_group = GActionGroup(name)
         cmd = CommandAddRemoveActionGroup(gaction_group, self.project, True)
         command_manager.execute(cmd, self.project)
     dialog.destroy()
示例#33
0
文件: shell.py 项目: romaia/stoq
 def get_app_by_name(self, appname):
     """
     @param appname: a string
     @returns: a :class:`Application` object
     """
     from kiwi.component import get_utility
     from stoq.lib.applist import Application
     from stoqlib.lib.interfaces import IApplicationDescriptions
     descriptions = get_utility(IApplicationDescriptions).get_descriptions()
     for name, full, icon, descr in descriptions:
         if name == appname:
             return Application(name, full, icon, descr)
示例#34
0
def update_profile_applications(store, profile=None):
    """This method checks for all available applications and perform a
    comparision with the application names stored in user profiles. If a
    certain application is not there it is added.
    """
    app_list = get_utility(IApplicationDescriptions).get_application_names()
    profiles = profile and [profile] or store.find(UserProfile)
    for app_name in app_list:
        for profile in profiles:
            settings = profile.profile_settings
            app_names = [s.app_dir_name for s in settings]
            if not app_name in app_names:
                profile.add_application_reference(app_name)
示例#35
0
    def edit_action(self, gaction):
        """Edit the action or action group. This method will not edit
        it directly but delegate to the command manager."""
        if isinstance(gaction, GAction):
            dialog = GActionDialog(
                get_utility(IGazpachoApp).get_window(),
                gaction.parent, gaction)
            if dialog.run() == gtk.RESPONSE_OK:
                new_values = dialog.get_values()
                cmd = CommandEditAction(gaction, new_values, self.project)
                command_manager.execute(cmd, self.project)

            dialog.destroy()
        else:
            dialog = GActionGroupDialog(get_utility(IGazpachoApp).get_window(),
                                        gaction)
            if dialog.run() == gtk.RESPONSE_OK:
                new_name = dialog.get_action_group_name()
                cmd = CommandEditActionGroup(gaction, new_name, self.project)
                command_manager.execute(cmd, self.project)

            dialog.destroy()
示例#36
0
def get_plugin_manager():
    """Provides and returns the plugin manager

    @attention: Try to always use this instead of getting the utillity
        by hand, as that could not have been provided before.

    :returns: an :class:`PluginManager` instance
    """
    manager = get_utility(IPluginManager, None)
    if not manager:
        manager = PluginManager()
        provide_utility(IPluginManager, manager)

    return manager
示例#37
0
def get_category_label(name):
    if name.startswith('app.common'):
        return _("General")
    elif name.startswith('app'):
        app_name = name.split('.', 2)[1]
        app_list = get_utility(IApplicationDescriptions)
        for item in app_list.get_descriptions():
            if item[0] == app_name:
                return item[1]  # the label

    elif name.startswith('plugin'):
        return _('%s plugin') % (name.split('.', 2)[1], )
    else:
        raise AssertionError(name)
示例#38
0
文件: runtime.py 项目: rg3915/stoq
def get_current_user(store):
    """Fetch the user which is currently logged into the system or None
    None means that there are no utilities available which in turn
    should only happens during startup, for example when creating
    a new database or running the migration script,
    at that point no users are logged in

    :param store: a store
    :returns: currently logged in user or None
    :rtype: a LoginUser or ``None``
    """
    user = get_utility(ICurrentUser, None)
    if user is not None:
        return store.fetch(user)
示例#39
0
 def _create_slave(self, method):
     dsm = get_utility(IDomainSlaveMapper)
     slave_class = dsm.get_slave_class(method)
     assert slave_class
     method = self.store.fetch(method)
     if slave_class is MultipleMethodSlave:
         slave = slave_class(self.wizard, self, self.store, self.model,
                             method, outstanding_value=self._outstanding_value,
                             finish_on_total=self._finish_on_total)
     else:
         slave = slave_class(self.wizard, self, self.store, self.model,
                             method, outstanding_value=self._outstanding_value)
     self._method_slave = slave
     return slave
示例#40
0
def get_plugin_manager():
    """Provides and returns the plugin manager

    @attention: Try to always use this instead of getting the utillity
        by hand, as that could not have been provided before.

    :returns: an :class:`PluginManager` instance
    """
    manager = get_utility(IPluginManager, None)
    if not manager:
        manager = PluginManager()
        provide_utility(IPluginManager, manager)

    return manager
示例#41
0
文件: salewizard.py 项目: romaia/stoq
 def _create_slave(self, method):
     dsm = get_utility(IDomainSlaveMapper)
     slave_class = dsm.get_slave_class(method)
     assert slave_class
     method = self.store.fetch(method)
     if slave_class is MultipleMethodSlave:
         slave = slave_class(self.wizard, self, self.store, self.model,
                             method, outstanding_value=self._outstanding_value,
                             finish_on_total=self._finish_on_total)
     else:
         slave = slave_class(self.wizard, self, self.store, self.model,
                             method, outstanding_value=self._outstanding_value)
     self._method_slave = slave
     return slave
示例#42
0
文件: runtime.py 项目: metrorede/stak
def get_current_user(store):
    """Fetch the user which is currently logged into the system or None
    None means that there are no utilities available which in turn
    should only happens during startup, for example when creating
    a new database or running the migration script,
    at that point no users are logged in

    :param store: a store
    :returns: currently logged in user or None
    :rtype: a LoginUser or ``None``
    """
    user = get_utility(ICurrentUser, None)
    if user is not None:
        return store.fetch(user)
示例#43
0
def get_category_label(name):
    if name.startswith('app.common'):
        return _("General")
    elif name.startswith('app'):
        app_name = name.split('.', 2)[1]
        app_list = get_utility(IApplicationDescriptions)
        for item in app_list.get_descriptions():
            if item[0] == app_name:
                return item[1]  # the label

    elif name.startswith('plugin'):
        return _('%s plugin') % (name.split('.', 2)[1], )
    else:
        raise AssertionError(name)
示例#44
0
def register_payment_slaves():
    dsm = get_utility(IDomainSlaveMapper)
    default_store = api.get_default_store()
    for method_name, slave_class in [
        (u'money', MoneyMethodSlave),
        (u'bill', BillMethodSlave),
        (u'check', CheckMethodSlave),
        (u'card', CardMethodSlave),
        (u'store_credit', StoreCreditMethodSlave),
        (u'multiple', MultipleMethodSlave),
        (u'deposit', DepositMethodSlave)]:

        method = PaymentMethod.get_by_name(default_store, method_name)
        dsm.register(method, slave_class)
示例#45
0
文件: runtime.py 项目: metrorede/stak
    def _setup_application_name(self):
        """Sets a friendly name for postgres connection

        This name will appear when selecting from pg_stat_activity, for instance,
        and will allow to better debug the queries (specially when there is a deadlock)
        """
        try:
            appinfo = get_utility(IAppInfo)
        except Exception:
            appname = 'stoq'
        else:
            appname = appinfo.get('name') or 'stoq'

        self.execute("SET application_name = '%s - %s - %s'" %
                     ((appname.lower(), get_hostname(), os.getpid())))
示例#46
0
 def _set_method_slave(self):
     """Sets the payment method slave"""
     method = self._ms.get_selected_method()
     if not method:
         return
     domain_mapper = get_utility(IDomainSlaveMapper)
     slave_class = domain_mapper.get_slave_class(method)
     if slave_class:
         self.wizard.payment_group = self.model
         self.slave = slave_class(self.wizard, self,
                                  self.store, self.order, method,
                                  outstanding_value=self.outstanding_value,
                                  first_duedate=self._first_duedate,
                                  installments_number=self._installments_number)
         self.attach_slave('method_slave_holder', self.slave)
示例#47
0
    def get_available_applications(self):
        user = api.get_current_user(self.store)

        permissions = user.profile.get_permissions()
        descriptions = get_utility(IApplicationDescriptions).get_descriptions()

        available_applications = []

        # sorting by app_full_name
        for name, full, icon, descr in locale_sorted(
                descriptions, key=operator.itemgetter(1)):
            if permissions.get(name):
                available_applications.append(
                    Application(name, full, icon, descr))
        return available_applications
示例#48
0
    def get_available_applications(self):
        user = api.get_current_user(self.store)

        permissions = user.profile.get_permissions()
        descriptions = get_utility(IApplicationDescriptions).get_descriptions()

        available_applications = []

        # sorting by app_full_name
        for name, full, icon, descr in locale_sorted(
                descriptions, key=operator.itemgetter(1)):
            # FIXME: The delivery app is still experimental. Remove this
            # once it is considered stable enough for our users
            if name == 'delivery' and not api.is_developer_mode():
                continue
            if permissions.get(name):
                available_applications.append(
                    Application(name, full, icon, descr))
        return available_applications
示例#49
0
    def setup_slaves(self):
        settings = {}
        for setting in self.model.profile_settings:
            settings[setting.app_dir_name] = setting

        apps = get_utility(IApplicationDescriptions)
        for name, full_name, icon_name, description in apps.get_descriptions():
            # Virtual apps should not be selected here
            if name in ProfileSettings.virtual_apps:
                continue

            # Create the user interface for each application which is
            # a HBox, a CheckButton and an Image
            box = gtk.HBox()
            box.show()

            button = ProxyCheckButton()
            button.set_label(full_name)
            button.data_type = bool
            button.model_attribute = 'has_permission'
            button.show()
            box.pack_start(button, padding=6)

            image = gtk.image_new_from_stock(icon_name, gtk.ICON_SIZE_MENU)
            box.pack_start(image, False, False)
            image.show()

            self.applications_vbox.pack_start(box, False)

            model = settings.get(name)
            if model is None:
                model = ProfileSettings(store=self.store,
                                        has_permission=False,
                                        app_dir_name=name,
                                        user_profile=self.model)

            setattr(self, name, button)
            self.add_proxy(model, [name])

        # Scroll to the bottom of the scrolled window
        vadj = self.scrolled_window.get_vadjustment()
        vadj.set_value(vadj.upper)
示例#50
0
 def feedback(self, screen, email, feedback):
     app_info = get_utility(IAppInfo, None)
     if app_info:
         app_version = app_info.get('version')
     else:
         app_version = 'Unknown'
     default_store = get_default_store()
     params = {
         'cnpj': self._get_cnpj(),
         'demo': sysparam(default_store).DEMO_MODE,
         'dist': ' '.join(platform.dist()),
         'email': email,
         'feedback': feedback,
         'plugins':
         ', '.join(InstalledPlugin.get_plugin_names(default_store)),
         'product_key': get_product_key(),
         'screen': screen,
         'time': datetime.datetime.today().isoformat(),
         'uname': ' '.join(platform.uname()),
         'version': app_version,
     }
     return self._do_request('GET', 'feedback.json', **params)
示例#51
0
    def get_available_applications(self):
        user = api.get_current_user(self.store)

        permissions = {}
        for settings in user.profile.profile_settings:
            permissions[settings.app_dir_name] = settings.has_permission

        descriptions = get_utility(IApplicationDescriptions).get_descriptions()

        available_applications = []

        # sorting by app_full_name
        for name, full, icon, descr in locale_sorted(
                descriptions, key=operator.itemgetter(1)):
            # FIXME:
            # if name in self._hidden_apps:
            #    continue
            # and name not in self._blocked_apps:
            if permissions.get(name):
                available_applications.append(
                    Application(name, full, icon, descr))
        return available_applications
示例#52
0
文件: test_main.py 项目: tmaxter/stoq
    def setUp(self):
        self._mocks = []

        self._iappinfo = get_utility(IAppInfo)
        # Shell will provide this utility
        remove_utility(IAppInfo)

        # If the locale is changed here, gui tests will break
        mocked = mock.patch.dict(get_settings()._root, clear=True)
        self._mocks.append(mocked)

        # Do not show the splash screen during the tests
        mocked = mock.patch('stoqlib.gui.splash.show_splash', new=lambda: None)
        self._mocks.append(mocked)

        # If a dependency is missing, avoid showing an error message
        # or else jenkins will hang
        mocked = mock.patch('stoq.lib.dependencies.DependencyChecker._error',
                            new=lambda *args: None)
        self._mocks.append(mocked)

        for mocked in self._mocks:
            mocked.start()
示例#53
0
文件: settings.py 项目: tmaxter/stoq
    def migrate(self):
        if self._migrated:
            return
        log.info("Migrating settings from Stoq.conf")

        # Migrate from old configuration settings
        try:
            config = get_utility(IStoqConfig)
        except NotImplementedError:
            # For unittests, migrating jenkins from old to new settings
            return

        self.set('hide-demo-warning',
                 config.get('UI', 'hide_demo_warning') == 'True')

        width = int(config.get('Launcher', 'window_width') or -1)
        height = int(config.get('Launcher', 'window_height') or -1)
        x = int(config.get('Launcher', 'window_x') or -1)
        y = int(config.get('Launcher', 'window_y') or -1)
        self.set('launcher-geometry',
                 dict(width=width, height=height, x=x, y=y))

        self.set('last-version-check',
                 config.get('General', 'last-version-check'))

        self.set('latest-version',
                 config.get('General', 'latest-version'))

        self.set('show-welcome-dialog',
                 config.get('General', 'show_welcome_dialog') != 'False')

        d = {}
        for k, v in config.items('Shortcuts'):
            d[k] = v
        self.set('shortcuts', d)
        self._migrated = True
示例#54
0
文件: api.py 项目: sarkis89/stoq
 def config(self):
     return get_utility(IStoqConfig)
示例#55
0
 def on_SignOut__activate(self, action):
     from stoqlib.lib.interfaces import ICookieFile
     get_utility(ICookieFile).clear()
     self._shutdown_application(restart=True)