Пример #1
0
 def test_get_default(self):
     location = CityLocation.get_default(self.store)
     self.failUnless(isinstance(location, CityLocation))
     self.assertEquals(location.city, sysparam.get_string('CITY_SUGGESTED'))
     self.assertEquals(location.state,
                       sysparam.get_string('STATE_SUGGESTED'))
     self.assertEquals(location.country,
                       sysparam.get_string('COUNTRY_SUGGESTED'))
Пример #2
0
 def test_get_default(self):
     location = CityLocation.get_default(self.store)
     self.failUnless(isinstance(location, CityLocation))
     self.assertEquals(location.city,
                       sysparam.get_string('CITY_SUGGESTED'))
     self.assertEquals(location.state,
                       sysparam.get_string('STATE_SUGGESTED'))
     self.assertEquals(location.country,
                       sysparam.get_string('COUNTRY_SUGGESTED'))
Пример #3
0
    def get_default(cls, store):
        """Get the default city location according to the database parameters.
        The is usually the same city as main branch.

        :returns: the default city location
        """
        city = sysparam.get_string('CITY_SUGGESTED')
        state = sysparam.get_string('STATE_SUGGESTED')
        country = sysparam.get_string('COUNTRY_SUGGESTED')

        return cls.get_or_create(store, city, state, country)
Пример #4
0
    def get_default(cls, store):
        """Get the default city location according to the database parameters.
        The is usually the same city as main branch.

        :returns: the default city location
        """
        city = sysparam.get_string('CITY_SUGGESTED')
        state = sysparam.get_string('STATE_SUGGESTED')
        country = sysparam.get_string('COUNTRY_SUGGESTED')

        return cls.get_or_create(store, city, state, country)
Пример #5
0
    def version(self, store, app_version):
        """Fetches the latest version
        :param store: a store
        :param app_version: application version
        :returns: a deferred with the version_string as a parameter
        """
        try:
            bdist_type = library.bdist_type
        except Exception:
            bdist_type = None

        if os.path.exists(os.path.join('etc', 'init.d', 'stoq-bootstrap')):
            source = 'livecd'
        elif bdist_type in ['egg', 'wheel']:
            source = 'pypi'
        elif is_developer_mode():
            source = 'devel'
        else:
            source = 'ppa'

        params = {
            'hash': sysparam.get_string('USER_HASH'),
            'demo': sysparam.get_bool('DEMO_MODE'),
            'dist': platform.dist(),
            'cnpj': get_main_cnpj(store),
            'plugins': InstalledPlugin.get_plugin_names(store),
            'product_key': get_product_key(),
            'time': datetime.datetime.today().isoformat(),
            'uname': platform.uname(),
            'version': app_version,
            'source': source,
        }
        params.update(self._get_company_details(store))
        params.update(self._get_usage_stats(store))
        return self._do_request('GET', 'version.json', **params)
Пример #6
0
    def instrucoes(self):
        instructions = []
        payment = self.payment
        # FIXME: Penalty and interest are also defined on the payment method. We
        # should use that information instead. We could also add a discount
        # information on the payment method.
        penalty = currency(self.penalty_percentage / 100 * payment.value)
        interest = currency(self.interest_percentage / 100 * payment.value)
        discount = currency(self.discount_percentage / 100 * payment.value)
        data = sysparam.get_string('BILL_INSTRUCTIONS')
        for line in data.split('\n')[:4]:
            line = line.replace('$DATE', payment.due_date.strftime('%d/%m/%Y'))
            line = line.replace('$PENALTY',
                                converter.as_string(currency, penalty))
            line = line.replace('$INTEREST',
                                converter.as_string(currency, interest))
            line = line.replace('$DISCOUNT',
                                converter.as_string(currency, discount))
            line = line.replace('$INVOICE_NUMBER', str(self.numero_documento))
            instructions.append(line)

        # FIXME: Only add this if not a stoq.link subscriber
        #instructions.append('')
        #instructions.append('\n' + _('Stoq Retail Management') + ' - www.stoq.com.br')
        return instructions
Пример #7
0
 def bug_report(self, report, **kwargs):
     params = {
         'product_key': get_product_key(),
         'report': report,
     }
     endpoint = 'api/stoq/v1/bugreport/%s' % (sysparam.get_string('USER_HASH'), )
     return self._do_request('POST', endpoint, json=params, **kwargs)
Пример #8
0
 def bug_report(self, report, **kwargs):
     params = {
         'product_key': get_product_key(),
         'report': report,
     }
     endpoint = 'api/stoq/v1/bugreport/%s' % (sysparam.get_string('USER_HASH'), )
     return self._do_request('POST', endpoint, json=params, **kwargs)
Пример #9
0
    def save(self):
        temp_csv = tempfile.NamedTemporaryFile(suffix='.csv', delete=False, mode='w')
        writer = csv.writer(temp_csv, delimiter=',',
                            doublequote=True,
                            quoting=csv.QUOTE_ALL)
        writer.writerows(self.rows)
        temp_csv.close()

        template_file = sysparam.get_string('LABEL_TEMPLATE_PATH')
        if not os.path.exists(template_file):
            raise ValueError(_('Template file for printing labels was not found.'))

        args = ['-f', str(self.skip + 1), '-o', self.filename, '-i',
                temp_csv.name, template_file]

        # FIXME: This is just a quick workaround. There must be a better way to
        # do this.
        # glables3 changed the script name. If the default (glables2) is not
        # available, try the one from glables3
        try:
            p = Process(['glabels-batch'] + args)
        except OSError:
            p = Process(['glabels-3-batch'] + args)
        # FIXME: We should use while so the print dialog can be canceled (see
        # threadutils)
        p.wait()
Пример #10
0
    def _get_parameter_value(self, obj):
        """Given a ParameterData object, returns a string representation of
        its current value.
        """
        detail = sysparam.get_detail_by_name(obj.field_name)
        if detail.type == unicode:
            data = sysparam.get_string(obj.field_name)
        elif detail.type == bool:
            data = sysparam.get_bool(obj.field_name)
        elif detail.type == int:
            data = sysparam.get_int(obj.field_name)
        elif detail.type == decimal.Decimal:
            data = sysparam.get_decimal(obj.field_name)
        elif isinstance(detail.type, basestring):
            data = sysparam.get_object(self.store, obj.field_name)
        else:
            raise NotImplementedError(detail.type)

        if isinstance(data, Domain):
            if not (IDescribable in providedBy(data)):
                raise TypeError(u"Parameter `%s' must implement IDescribable "
                                "interface." % obj.field_name)
            return data.get_description()
        elif detail.options:
            return detail.options[int(obj.field_value)]
        elif isinstance(data, bool):
            return [_(u"No"), _(u"Yes")][data]
        elif obj.field_name == u'COUNTRY_SUGGESTED':
            return dgettext("iso_3166", data)
        elif isinstance(data, unicode):
            # FIXME: workaround to handle locale specific data
            return _(data)
        return unicode(data)
Пример #11
0
    def link_update(self, store):
        # Setup a callback (just in case we need it)
        def callback(response=False):
            """Send data to Stoq Server if the client is using Stoq Link"""
            if not response:
                # On falsy responses we will ignore the next send data
                WebService.send_link_data = False
                return
            # On non falsy responses we will send the next data right away
            WebService.send_link_data = True
            params = {
                'hash': key,
                'data': collect_link_statistics(store)
            }
            return self._do_request('POST', 'api/lite/data', **params)

        key = sysparam.get_string('USER_HASH')
        if WebService.send_link_data is False:
            # Don't even try to send data if the user is not using Stoq Link
            return None
        elif WebService.send_link_data:
            # If the instance is using stoq link lite, we may send data
            return callback(True)

        # If we dont know if the instance is using Stoq Link, we should ask
        # our server, and then send data in case it is using it.
        params = {
            'hash': key,
            'callback': callback,
        }
        return self._do_request('GET', 'api/lite/using', **params)
Пример #12
0
    def _get_instrucoes(self, payment):
        instructions = []

        sale = payment.group.sale
        if sale:
            invoice_number = sale.invoice_number
        else:
            invoice_number = payment.identifier

        penalty = currency(
            (sysparam.get_decimal('BILL_PENALTY') / 100) * payment.value)
        interest = currency(
            (sysparam.get_decimal('BILL_INTEREST') / 100) * payment.value)
        discount = currency(
            (sysparam.get_decimal('BILL_DISCOUNT') / 100) * payment.value)
        data = sysparam.get_string('BILL_INSTRUCTIONS')
        for line in data.split('\n')[:4]:
            line = line.replace('$DATE', payment.due_date.strftime('%d/%m/%Y'))
            line = line.replace('$PENALTY',
                                converter.as_string(currency, penalty))
            line = line.replace('$INTEREST',
                                converter.as_string(currency, interest))
            line = line.replace('$DISCOUNT',
                                converter.as_string(currency, discount))
            line = line.replace('$INVOICE_NUMBER', str(invoice_number))
            instructions.append(line)

        instructions.append('')
        instructions.append('\n' + _('Stoq Retail Management') + ' - www.stoq.com.br')
        return instructions
Пример #13
0
    def _get_parameter_value(self, obj):
        """Given a ParameterData object, returns a string representation of
        its current value.
        """
        detail = sysparam.get_detail_by_name(obj.field_name)
        if detail.type == unicode:
            data = sysparam.get_string(obj.field_name)
        elif detail.type == bool:
            data = sysparam.get_bool(obj.field_name)
        elif detail.type == int:
            data = sysparam.get_int(obj.field_name)
        elif detail.type == decimal.Decimal:
            data = sysparam.get_decimal(obj.field_name)
        elif isinstance(detail.type, basestring):
            data = sysparam.get_object(self.store, obj.field_name)
        else:
            raise NotImplementedError(detail.type)

        if isinstance(data, Domain):
            if not (IDescribable in providedBy(data)):
                raise TypeError(u"Parameter `%s' must implement IDescribable "
                                "interface." % obj.field_name)
            return data.get_description()
        elif detail.options:
            return detail.options[int(obj.field_value)]
        elif isinstance(data, bool):
            return [_(u"No"), _(u"Yes")][data]
        elif obj.field_name == u'COUNTRY_SUGGESTED':
            return dgettext("iso_3166", data)
        elif isinstance(data, unicode):
            # FIXME: workaround to handle locale specific data
            return _(data)
        return unicode(data)
Пример #14
0
    def save(self):
        temp_csv = tempfile.NamedTemporaryFile(suffix='.csv', delete=False, mode='w')
        writer = csv.writer(temp_csv, delimiter=',',
                            doublequote=True,
                            quoting=csv.QUOTE_ALL)
        writer.writerows(self.rows)
        temp_csv.close()

        template_file = sysparam.get_string('LABEL_TEMPLATE_PATH')
        if not os.path.exists(template_file):
            raise ValueError(_('Template file for printing labels was not found.'))

        args = ['-f', str(self.skip + 1), '-o', self.filename, '-i',
                temp_csv.name, template_file]

        # FIXME: This is just a quick workaround. There must be a better way to
        # do this.
        # glables3 changed the script name. If the default (glables2) is not
        # available, try the one from glables3
        try:
            p = Process(['glabels-batch'] + args)
        except OSError:
            p = Process(['glabels-3-batch'] + args)
        # FIXME: We should use while so the print dialog can be canceled (see
        # threadutils)
        p.wait()
Пример #15
0
    def _get_instrucoes(self, payment):
        instructions = []

        sale = payment.group.sale
        if sale:
            invoice_number = sale.invoice.invoice_number
        else:
            invoice_number = payment.identifier

        penalty = currency(
            (sysparam.get_decimal('BILL_PENALTY') / 100) * payment.value)
        interest = currency(
            (sysparam.get_decimal('BILL_INTEREST') / 100) * payment.value)
        discount = currency(
            (sysparam.get_decimal('BILL_DISCOUNT') / 100) * payment.value)
        data = sysparam.get_string('BILL_INSTRUCTIONS')
        for line in data.split('\n')[:4]:
            line = line.replace('$DATE', payment.due_date.strftime('%d/%m/%Y'))
            line = line.replace('$PENALTY',
                                converter.as_string(currency, penalty))
            line = line.replace('$INTEREST',
                                converter.as_string(currency, interest))
            line = line.replace('$DISCOUNT',
                                converter.as_string(currency, discount))
            line = line.replace('$INVOICE_NUMBER', str(invoice_number))
            instructions.append(line)

        instructions.append('')
        instructions.append('\n' + _('Stoq Retail Management') +
                            ' - www.stoq.com.br')
        return instructions
Пример #16
0
    def _get_instrucoes(self, payment):
        instructions = []
        data = sysparam.get_string('BILL_INSTRUCTIONS')
        for line in data.split('\n')[:3]:
            line = line.replace('$DATE', payment.due_date.strftime('%d/%m/%Y'))
            instructions.append(line)

        instructions.append('\n' + _('Stoq Retail Management') + ' - www.stoq.com.br')
        return instructions
Пример #17
0
 def tef_request(self, name, email, phone):
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'name': name,
         'email': email,
         'phone': phone,
         'product_key': get_product_key(),
     }
     return self._do_request('GET', 'tefrequest.json', **params)
Пример #18
0
 def tef_request(self, name, email, phone):
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'name': name,
         'email': email,
         'phone': phone,
         'product_key': get_product_key(),
     }
     return self._do_request('GET', 'tefrequest.json', **params)
Пример #19
0
    def download_plugin(self, plugin_name, md5sum=None, **kwargs):
        params = {
            'hash': sysparam.get_string('USER_HASH'),
            'md5': md5sum or '',
            'version': self._get_version(),
        }

        endpoint = 'api/stoq-link/egg/%s' % (plugin_name, )
        return self._do_request('GET', endpoint, params=params, **kwargs)
Пример #20
0
 def link_registration(self, name, email, phone):
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'name': name,
         'email': email,
         'phone': phone,
         'product_key': get_product_key(),
     }
     return self._do_request('POST', 'api/auth/register', **params)
Пример #21
0
 def link_registration(self, name, email, phone, **kwargs):
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'name': name,
         'email': email,
         'phone': phone,
         'product_key': get_product_key(),
     }
     return self._do_request('POST', 'api/stoq-link/user', data=params, **kwargs)
Пример #22
0
    def download_plugin(self, plugin_name, md5sum=None, **kwargs):
        params = {
            'hash': sysparam.get_string('USER_HASH'),
            'md5': md5sum or '',
            'version': self._get_version(),
        }

        endpoint = 'api/stoq-link/egg/%s' % (plugin_name, )
        return self._do_request('GET', endpoint, params=params, **kwargs)
Пример #23
0
 def download_plugin(self, plugin_name, md5sum=None, callback=None):
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'plugin': plugin_name,
         'md5': md5sum or '',
         'version': self._get_version(),
     }
     return self._do_download_request(
         'api/eggs', callback=callback, **params)
Пример #24
0
    def _get_instrucoes(self, payment):
        instructions = []
        data = sysparam.get_string("BILL_INSTRUCTIONS")
        for line in data.split("\n")[:3]:
            line = line.replace("$DATE", payment.due_date.strftime("%d/%m/%Y"))
            instructions.append(line)

        instructions.append("\n" + _("Stoq Retail Management") + " - www.stoq.com.br")
        return instructions
Пример #25
0
 def link_registration(self, name, email, phone, **kwargs):
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'name': name,
         'email': email,
         'phone': phone,
         'product_key': get_product_key(),
     }
     return self._do_request('POST', 'api/stoq-link/user', data=params, **kwargs)
Пример #26
0
    def _get_instrucoes(self, payment):
        instructions = []
        data = sysparam.get_string('BILL_INSTRUCTIONS')
        for line in data.split('\n')[:3]:
            line = line.replace('$DATE', payment.due_date.strftime('%d/%m/%Y'))
            instructions.append(line)

        instructions.append('\n' + _('Stoq Retail Management') +
                            ' - www.stoq.com.br')
        return instructions
Пример #27
0
def print_labels(label_data, store, purchase=None):
    path = sysparam.get_string('LABEL_TEMPLATE_PATH')
    if path and os.path.exists(path):
        if purchase:
            print_report(LabelReport, purchase.get_data_for_labels(),
                         label_data.skip, store=store)
        else:
            print_report(LabelReport, [label_data], label_data.skip, store=store)
    else:
        warning(_("It was not possible to print the labels. The "
                  "template file was not found."))
Пример #28
0
    def _create_model(self, store):
        user = api.get_current_user(store)
        salesperson = user.person.salesperson

        return Sale(coupon_id=None,
                    status=Sale.STATUS_QUOTE,
                    salesperson=salesperson,
                    branch=api.get_current_branch(store),
                    group=PaymentGroup(store=store),
                    cfop_id=sysparam.get_object_id('DEFAULT_SALES_CFOP'),
                    operation_nature=sysparam.get_string('DEFAULT_OPERATION_NATURE'),
                    store=store)
Пример #29
0
    def bug_report(self, report):
        params = {
            'hash': sysparam.get_string('USER_HASH'),
            'product_key': get_product_key(),
            'report': json.dumps(report)
        }
        if os.environ.get('STOQ_DISABLE_CRASHREPORT'):
            d = Deferred()
            sys.stderr.write(report)
            d.callback({'report-url': '<not submitted>', 'report': '<none>'})
            return d

        return self._do_request('POST', 'v2/bugreport.json', **params)
Пример #30
0
    def _create_model(self, store):
        user = api.get_current_user(store)
        salesperson = user.person.sales_person

        return Sale(
            coupon_id=None,
            status=Sale.STATUS_QUOTE,
            salesperson=salesperson,
            branch=api.get_current_branch(store),
            group=PaymentGroup(store=store),
            cfop_id=sysparam.get_object_id('DEFAULT_SALES_CFOP'),
            operation_nature=sysparam.get_string('DEFAULT_OPERATION_NATURE'),
            store=store)
Пример #31
0
 def __init__(self, temp, models, skip=0, store=None):
     self.store = store
     self.models = models
     self.skip = skip
     self.temp = temp
     self.rows = []
     columns = sysparam.get_string('LABEL_COLUMNS')
     columns = columns.split(',')
     for model in models:
         for i in range(int(model.quantity)):
             if not isinstance(model, Sellable):
                 model = model.sellable
             self.rows.append(_parse_row(model, columns))
Пример #32
0
 def __init__(self, temp, models, skip=0, store=None):
     self.store = store
     self.models = models
     self.skip = skip
     self.temp = temp
     self.rows = []
     columns = sysparam.get_string('LABEL_COLUMNS')
     columns = columns.split(',')
     for model in models:
         for i in range(int(model.quantity)):
             if not isinstance(model, Sellable):
                 model = model.sellable
             self.rows.append(_parse_row(model, columns))
Пример #33
0
    def bug_report(self, report):
        params = {
            'hash': sysparam.get_string('USER_HASH'),
            'product_key': get_product_key(),
            'report': json.dumps(report)
        }
        if os.environ.get('STOQ_DISABLE_CRASHREPORT'):
            d = Deferred()
            sys.stderr.write(report)
            d.callback({'report-url': '<not submitted>',
                        'report': '<none>'})
            return d

        return self._do_request('POST', 'v2/bugreport.json', **params)
Пример #34
0
def get_l10n_module(country=None):
    if not country:
        from stoqlib.lib.parameters import sysparam
        country = sysparam.get_string('COUNTRY_SUGGESTED')

    short = iso639_list.get(country.lower(), None)
    if short is None:
        return generic

    path = 'stoqlib.l10n.%s.%s' % (short, short)
    try:
        module = namedAny(path)
    except (ImportError, AttributeError):
        return generic

    return module
Пример #35
0
def print_labels(label_data, store, purchase=None, receiving=None):
    path = sysparam.get_string('LABEL_TEMPLATE_PATH')
    if path and os.path.exists(path):
        if purchase:
            print_report(LabelReport, purchase.get_data_for_labels(),
                         label_data.skip, store=store)
        elif receiving:
            data = []
            for purchase in receiving.purchase_orders:
                data.extend(purchase.get_data_for_labels())
            print_report(LabelReport, data, label_data.skip, store=store)
        else:
            print_report(LabelReport, [label_data], label_data.skip, store=store)
    else:
        warning(_("It was not possible to print the labels. The "
                  "template file was not found."))
Пример #36
0
def get_l10n_module(country=None):
    if not country:
        from stoqlib.lib.parameters import sysparam
        country = sysparam.get_string('COUNTRY_SUGGESTED')

    short = iso639_list.get(country.lower(), None)
    if short is None:
        return generic

    path = 'stoqlib.l10n.%s.%s' % (short, short)
    try:
        module = import_from_string(path)
    except (ImportError, AttributeError):
        return generic

    return module
Пример #37
0
 def feedback(self, screen, email, feedback):
     default_store = get_default_store()
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'cnpj': get_main_cnpj(default_store),
         'demo': sysparam.get_bool('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': self._get_version(),
     }
     return self._do_request('GET', 'feedback.json', **params)
Пример #38
0
 def feedback(self, screen, email, feedback):
     default_store = get_default_store()
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'cnpj': get_main_cnpj(default_store),
         'demo': sysparam.get_bool('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': self._get_version(),
     }
     return self._do_request('GET', 'feedback.json', **params)
Пример #39
0
 def version(self, store, app_version):
     """Fetches the latest version
     :param store: a store
     :param app_version: application version
     :returns: a deferred with the version_string as a parameter
     """
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'demo': sysparam.get_bool('DEMO_MODE'),
         'dist': platform.dist(),
         'cnpj': get_main_cnpj(store),
         'plugins': InstalledPlugin.get_plugin_names(store),
         'product_key': get_product_key(),
         'time': datetime.datetime.today().isoformat(),
         'uname': platform.uname(),
         'version': app_version,
     }
     return self._do_request('GET', 'version.json', **params)
Пример #40
0
 def version(self, store, app_version):
     """Fetches the latest version
     :param store: a store
     :param app_version: application version
     :returns: a deferred with the version_string as a parameter
     """
     params = {
         'hash': sysparam.get_string('USER_HASH'),
         'demo': sysparam.get_bool('DEMO_MODE'),
         'dist': platform.dist(),
         'cnpj': get_main_cnpj(store),
         'plugins': InstalledPlugin.get_plugin_names(store),
         'product_key': get_product_key(),
         'time': datetime.datetime.today().isoformat(),
         'uname': platform.uname(),
         'version': app_version,
     }
     return self._do_request('GET', 'version.json', **params)
Пример #41
0
    def feedback(self, screen, email, feedback, **kwargs):
        default_store = get_default_store()
        params = {
            'cnpj': get_main_cnpj(default_store),
            'demo': sysparam.get_bool('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': self._get_version(),
        }

        endpoint = 'api/stoq/v1/feedback/%s' % (sysparam.get_string('USER_HASH'), )
        return self._do_request('POST', endpoint, json=params, **kwargs)
Пример #42
0
    def feedback(self, screen, email, feedback, **kwargs):
        default_store = get_default_store()
        params = {
            'cnpj': get_main_cnpj(default_store),
            'demo': sysparam.get_bool('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': self._get_version(),
        }

        endpoint = 'api/stoq/v1/feedback/%s' % (sysparam.get_string('USER_HASH'), )
        return self._do_request('POST', endpoint, json=params, **kwargs)
Пример #43
0
 def sysparam(self, **kwargs):
     """
     Updates a set of system parameters within a context.
     The values will be reverted when leaving the scope.
     kwargs contains a dictionary of parameter name->value
     """
     from stoqlib.lib.parameters import sysparam
     old_values = {}
     for param, value in kwargs.items():
         if isinstance(value, bool):
             old_values[param] = sysparam.get_bool(param)
             sysparam.set_bool(self.store, param, value)
         elif isinstance(value, int):
             old_values[param] = sysparam.get_int(param)
             sysparam.set_int(self.store, param, value)
         elif isinstance(value, Domain) or value is None:
             old_values[param] = sysparam.get_object(self.store, param)
             sysparam.set_object(self.store, param, value)
         elif isinstance(value, str):
             old_values[param] = sysparam.get_string(param)
             sysparam.set_string(self.store, param, value)
         elif isinstance(value, Decimal):
             old_values[param] = sysparam.get_decimal(param)
             sysparam.set_decimal(self.store, param, value)
         else:
             raise NotImplementedError(type(value))
     try:
         yield
     finally:
         for param, value in old_values.items():
             if isinstance(value, bool):
                 sysparam.set_bool(self.store, param, value)
             elif isinstance(value, int):
                 sysparam.set_int(self.store, param, value)
             elif isinstance(value, Domain) or value is None:
                 sysparam.set_object(self.store, param, value)
             elif isinstance(value, str):
                 sysparam.set_string(self.store, param, value)
             elif isinstance(value, Decimal):
                 sysparam.set_decimal(self.store, param, value)
             else:
                 raise NotImplementedError(type(value))
Пример #44
0
 def sysparam(self, **kwargs):
     """
     Updates a set of system parameters within a context.
     The values will be reverted when leaving the scope.
     kwargs contains a dictionary of parameter name->value
     """
     from stoqlib.lib.parameters import sysparam
     old_values = {}
     for param, value in kwargs.items():
         if isinstance(value, bool):
             old_values[param] = sysparam.get_bool(param)
             sysparam.set_bool(self.store, param, value)
         elif isinstance(value, int):
             old_values[param] = sysparam.get_int(param)
             sysparam.set_int(self.store, param, value)
         elif isinstance(value, Domain) or value is None:
             old_values[param] = sysparam.get_object(self.store, param)
             sysparam.set_object(self.store, param, value)
         elif isinstance(value, str):
             old_values[param] = sysparam.get_string(param)
             sysparam.set_string(self.store, param, value)
         elif isinstance(value, Decimal):
             old_values[param] = sysparam.get_decimal(param)
             sysparam.set_decimal(self.store, param, value)
         else:
             raise NotImplementedError(type(value))
     try:
         yield
     finally:
         for param, value in old_values.items():
             if isinstance(value, bool):
                 sysparam.set_bool(self.store, param, value)
             elif isinstance(value, int):
                 sysparam.set_int(self.store, param, value)
             elif isinstance(value, Domain) or value is None:
                 sysparam.set_object(self.store, param, value)
             elif isinstance(value, str):
                 sysparam.set_string(self.store, param, value)
             elif isinstance(value, Decimal):
                 sysparam.set_decimal(self.store, param, value)
             else:
                 raise NotImplementedError(type(value))
Пример #45
0
 def __init__(self, temp, models, skip=0, store=None):
     self.store = store
     self.models = models
     self.skip = skip
     self.temp = temp
     self.rows = []
     columns = sysparam.get_string('LABEL_COLUMNS')
     columns = columns.split(',')
     for model in models:
         for i in range(int(model.quantity)):
             if columns:
                 from stoqlib.domain.sellable import Sellable
                 if not isinstance(model, Sellable):
                     model = model.sellable
                 self.rows.append(_parse_row(model, columns))
             else:
                 # XXX: glabels is not working with unicode caracters
                 desc = strip_accents(model.description)
                 self.rows.append(
                     [model.code, model.barcode, desc, model.price])
Пример #46
0
    def version(self, store, app_version, **kwargs):
        """Fetches the latest version

        :param store: a store
        :param app_version: application version
        """
        import stoq
        try:
            bdist_type = library.bdist_type
        except Exception:
            bdist_type = None

        # We should use absolute paths when looking for /etc
        if os.path.exists(
                os.path.join(os.sep, 'etc', 'init.d', 'stoq-bootstrap')):
            source = 'livecd'
        elif stoq.trial_mode:
            source = 'trial'
        elif bdist_type in ['egg', 'wheel']:
            source = 'pypi'
        elif is_developer_mode():
            source = 'devel'
        else:
            source = 'ppa'

        params = {
            'demo': sysparam.get_bool('DEMO_MODE'),
            'dist': ' '.join(platform.dist()),
            'cnpj': get_main_cnpj(store),
            'plugins': ' '.join(InstalledPlugin.get_plugin_names(store)),
            'product_key': get_product_key(),
            'uname': ' '.join(platform.uname()),
            'version': app_version,
            'source': source,
        }
        params.update(self._get_company_details(store))
        params.update(self._get_usage_stats(store))

        endpoint = 'api/stoq/v1/version/%s' % (
            sysparam.get_string('USER_HASH'), )
        return self._do_request('POST', endpoint, json=params, **kwargs)
Пример #47
0
    def download_plugin(self, plugin_name, md5sum=None, callback=None):
        params = {
            'hash': sysparam.get_string('USER_HASH'),
            'plugin': plugin_name,
            'md5': md5sum or '',
            'version': self._get_version(),
        }

        def errback(code, error):
            if code == '204':
                log.info("No update needed. The plugin is already up to date.")
            else:
                return_messages = {
                    '400': "Plugin not available for this stoq version",
                    '404': "Plugin does not exist",
                    '405': "This instance has not acquired the specified plugin",
                }
                log.warning(return_messages.get(code, str(error)))

        return self._do_download_request(
            'api/eggs', callback=callback, errback=errback, **params)
Пример #48
0
    def version(self, store, app_version, **kwargs):
        """Fetches the latest version

        :param store: a store
        :param app_version: application version
        """
        import stoq
        try:
            bdist_type = library.bdist_type
        except Exception:
            bdist_type = None

        # We should use absolute paths when looking for /etc
        if os.path.exists(os.path.join(os.sep, 'etc', 'init.d', 'stoq-bootstrap')):
            source = 'livecd'
        elif stoq.trial_mode:
            source = 'trial'
        elif bdist_type in ['egg', 'wheel']:
            source = 'pypi'
        elif is_developer_mode():
            source = 'devel'
        else:
            source = 'ppa'

        params = {
            'demo': sysparam.get_bool('DEMO_MODE'),
            'dist': ' '.join(platform.dist()),
            'cnpj': get_main_cnpj(store),
            'plugins': ' '.join(InstalledPlugin.get_plugin_names(store)),
            'product_key': get_product_key(),
            'uname': ' '.join(platform.uname()),
            'version': app_version,
            'source': source,
        }
        params.update(self._get_company_details(store))
        params.update(self._get_usage_stats(store))

        endpoint = 'api/stoq/v1/version/%s' % (sysparam.get_string('USER_HASH'), )
        return self._do_request('POST', endpoint, json=params, **kwargs)
Пример #49
0
    def instrucoes(self):
        instructions = []
        payment = self.payment
        # FIXME: Penalty and interest are also defined on the payment method. We
        # should use that information instead. We could also add a discount
        # information on the payment method.
        penalty = currency(self.penalty_percentage / 100 * payment.value)
        interest = currency(self.interest_percentage / 100 * payment.value)
        discount = currency(self.discount_percentage / 100 * payment.value)
        data = sysparam.get_string('BILL_INSTRUCTIONS')
        for line in data.split('\n')[:4]:
            line = line.replace('$DATE', payment.due_date.strftime('%d/%m/%Y'))
            line = line.replace('$PENALTY', converter.as_string(currency, penalty))
            line = line.replace('$INTEREST', converter.as_string(currency, interest))
            line = line.replace('$DISCOUNT', converter.as_string(currency, discount))
            line = line.replace('$INVOICE_NUMBER', str(self.numero_documento))
            instructions.append(line)

        # FIXME: Only add this if not a stoq.link subscriber
        #instructions.append('')
        #instructions.append('\n' + _('Stoq Retail Management') + ' - www.stoq.com.br')
        return instructions
Пример #50
0
    def download_plugin(self, plugin_name, md5sum=None, callback=None):
        params = {
            'hash': sysparam.get_string('USER_HASH'),
            'plugin': plugin_name,
            'md5': md5sum or '',
            'version': self._get_version(),
        }

        def errback(code, error):
            if code == '204':
                log.info("No update needed. The plugin is already up to date.")
            else:
                return_messages = {
                    '400': "Plugin not available for this stoq version",
                    '404': "Plugin does not exist",
                    '405':
                    "This instance has not acquired the specified plugin",
                }
                log.warning(return_messages.get(code, str(error)))

        return self._do_download_request('api/eggs',
                                         callback=callback,
                                         errback=errback,
                                         **params)
Пример #51
0
 def status(self, **kwargs):
     endpoint = 'api/stoq/v1/status/%s' % (sysparam.get_string('USER_HASH'), )
     return self._do_request('GET', endpoint, **kwargs)
Пример #52
0
 def status(self, **kwargs):
     endpoint = 'api/stoq/v1/status/%s' % (sysparam.get_string('USER_HASH'), )
     return self._do_request('GET', endpoint, **kwargs)
Пример #53
0
    def _close_till(self, till, previous_day):
        log.info('ECFCouponPrinter.close_till(%r, %r)' % (till, previous_day))

        # XXX: this is so ugly, but the printer stops responding
        # if its printing something. We should wait a little bit...
        # This only happens if closing the till from the current day.
        if not previous_day:
            time.sleep(4)

        # Callsite catches DeviceError
        self._validate_printer()

        printer = self._printer.get_printer()

        if (sysparam.get_bool('ENABLE_DOCUMENT_ON_INVOICE') and not
            (printer.user_number and printer.register_date and
             printer.register_cro)):
            response = warning(
                short=_(u"You need to set some details about your ECF "
                        "if you want to save the paulista invoice file. "
                        "Go to the admin application and fill the "
                        "required information for the ECF."),
                buttons=((_(u"Cancel Close Till"), gtk.RESPONSE_CANCEL), ))
            return False

        retval = True
        while True:
            try:
                self._printer.close_till(previous_day=previous_day)
            except CouponOpenError:
                self._printer.cancel()
                retval = False
            except DriverError:
                response = warning(
                    short=_(u"It's not possible to emit a reduce Z for the "
                            "configured printer.\nWould you like to ignore "
                            "this error and continue?"),
                    buttons=((_(u"Cancel"), gtk.RESPONSE_CANCEL),
                             (_(u"Ignore"), gtk.RESPONSE_YES),
                             (_(u"Try Again"), gtk.RESPONSE_NONE)))
                if response == gtk.RESPONSE_NONE:
                    continue
                elif response == gtk.RESPONSE_CANCEL:
                    retval = False

            break

        if self._needs_cat52(printer):
            day = datetime.date.today()
            if previous_day:
                # XXX: Make sure this is tested
                day = till.opening_date

            dir = sysparam.get_string('CAT52_DEST_DIR')
            dir = os.path.expanduser(dir)
            if not os.path.exists(dir):
                os.mkdir(dir)

            generator = StoqlibCATGenerator(self.default_store, day, printer)
            generator.write(dir)

        self._reset_last_doc()

        return retval
Пример #54
0
 def local_pagamento(self):
     return sysparam.get_string('BILL_PAYMENT_PLACE')
Пример #55
0
 def _get_instructions(self):
     instructions = sysparam.get_string('BOOKLET_INSTRUCTIONS')
     return instructions.split('\n')
Пример #56
0
 def _get_instructions(self):
     instructions = sysparam.get_string('BOOKLET_INSTRUCTIONS')
     return instructions.split('\n')
Пример #57
0
def collect_report():
    report_ = {}

    # Date and uptime
    report_['date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    report_['tz'] = time.tzname
    report_['uptime'] = get_uptime()
    report_['locale'] = get_system_locale()

    # Python and System
    import platform
    report_['architecture'] = ' '.join(platform.architecture())
    report_['distribution'] = ' '.join(platform.dist())
    report_['python_version'] = _fix_version(sys.version_info)
    report_['uname'] = ' '.join(platform.uname())
    report_['system'] = platform.system()

    # Stoq application
    info = get_utility(IAppInfo, None)
    if info and info.get('name'):
        report_['app_name'] = info.get('name')
        report_['app_version'] = _fix_version(info.get('ver'))

    # External dependencies
    import gi
    report_['gtk_version'] = _fix_version(gi.version_info)

    import kiwi
    report_['kiwi_version'] = _fix_version(
        kiwi.__version__.version + (_get_revision(kiwi), ))

    import psycopg2
    try:
        parts = psycopg2.__version__.split(' ')
        extra = ' '.join(parts[1:])
        report_['psycopg_version'] = _fix_version(
            list(map(int, parts[0].split('.'))) + [extra])
    except Exception:
        report_['psycopg_version'] = _fix_version(psycopg2.__version__)

    import reportlab
    report_['reportlab_version'] = _fix_version(reportlab.Version)

    import stoqdrivers
    report_['stoqdrivers_version'] = _fix_version(
        stoqdrivers.__version__ + (_get_revision(stoqdrivers), ))

    report_['product_key'] = get_product_key()

    try:
        from stoqlib.lib.kiwilibrary import library
        report_['bdist_type'] = library.bdist_type
    except Exception:
        pass

    # PostgreSQL database server
    try:
        from stoqlib.database.settings import get_database_version
        default_store = get_default_store()
        report_['postgresql_version'] = _fix_version(
            get_database_version(default_store))
        report_['demo'] = sysparam.get_bool('DEMO_MODE')
        report_['hash'] = sysparam.get_string('USER_HASH')
        report_['cnpj'] = get_main_cnpj(default_store)
        report_['plugins'] = ', '.join(
            InstalledPlugin.get_plugin_names(default_store))
    except Exception:
        pass

    # Tracebacks
    report_['tracebacks'] = {}
    for i, trace in enumerate(_tracebacks):
        t = ''.join(traceback.format_exception(*trace))
        # Eliminate duplicates:
        md5sum = hashlib.md5(t).hexdigest()
        report_['tracebacks'][md5sum] = t

    if info and info.get('log'):
        report_['log'] = open(info.get('log')).read()
        report_['log_name'] = info.get('log')

    return report_
Пример #58
0
    def _close_till(self, till, previous_day):
        log.info('ECFCouponPrinter.close_till(%r, %r)' % (till, previous_day))

        # XXX: this is so ugly, but the printer stops responding
        # if its printing something. We should wait a little bit...
        # This only happens if closing the till from the current day.
        if not previous_day:
            time.sleep(4)

        # Callsite catches DeviceError
        self._validate_printer()

        printer = self._printer.get_printer()

        if (sysparam.get_bool('ENABLE_DOCUMENT_ON_INVOICE') and not
            (printer.user_number and printer.register_date and
             printer.register_cro)):
            response = warning(
                short=_(u"You need to set some details about your ECF "
                        "if you want to save the paulista invoice file. "
                        "Go to the admin application and fill the "
                        "required information for the ECF."),
                buttons=((_(u"Cancel Close Till"), Gtk.ResponseType.CANCEL), ))
            return False

        retval = True
        while True:
            try:
                self._printer.close_till(previous_day=previous_day)
            except CouponOpenError:
                self._printer.cancel()
                retval = False
            except DriverError:
                response = warning(
                    short=_(u"It's not possible to emit a reduce Z for the "
                            "configured printer.\nWould you like to ignore "
                            "this error and continue?"),
                    buttons=((_(u"Cancel"), Gtk.ResponseType.CANCEL),
                             (_(u"Ignore"), Gtk.ResponseType.YES),
                             (_(u"Try Again"), Gtk.ResponseType.NONE)))
                if response == Gtk.ResponseType.NONE:
                    continue
                elif response == Gtk.ResponseType.CANCEL:
                    retval = False

            break

        if self._needs_cat52(printer):
            day = datetime.date.today()
            if previous_day:
                # XXX: Make sure this is tested
                day = till.opening_date

            dir = sysparam.get_string('CAT52_DEST_DIR')
            dir = os.path.expanduser(dir)
            if not os.path.exists(dir):
                os.mkdir(dir)

            generator = StoqlibCATGenerator(self.default_store, day, printer)
            generator.write(dir)

        self._reset_last_doc()

        return retval