Exemple #1
0
 def execute_actions(self, cursor, user, promotion_rule, order_id, context):
     """
     Executes the actions associated with this rule
     @param cursor: Database Cursor
     @param user: ID of User
     @param promotion_rule: Browse Record
     @param order_id: ID of sale order
     @param context: Context(no direct use).
     """
     action_obj = self.pool.get('promos.rules.actions')
     if DEBUG:
         netsvc.Logger().notifyChannel(
             "Promotions", netsvc.LOG_INFO,
             "Applying promo %s to %s" % (promotion_rule.id, order_id))
     order = self.pool.get('sale.order').browse(cursor, user, order_id,
                                                context)
     for action in promotion_rule.actions:
         try:
             action_obj.execute(cursor,
                                user,
                                action.id,
                                order,
                                context=None)
         except Exception, error:
             raise error
Exemple #2
0
    def _repair_action(self, cr, uid, data, context):
        """
        Action that repairs the invoice numbers 
        """
        logger = netsvc.Logger()

        logger.notifyChannel("l10n_es_account_invoice_sequence_fix", netsvc.LOG_DEBUG, "Searching for invoices.")

        invoice_facade = pooler.get_pool(cr.dbname).get('account.invoice')
        invoice_ids = invoice_facade.search(cr, uid, [('move_id','<>','')], limit=0, order='id', context=context)

        if len(invoice_ids) == 0:
            raise wizard.except_wizard(_('No Data Available'), _('No records found for your selection!'))

        logger.notifyChannel("l10n_es_account_invoice_sequence_fix", netsvc.LOG_DEBUG, "Repairing %d invoices." % len(invoice_ids))

        for invoice in invoice_facade.browse(cr, uid, invoice_ids):
            move_id = invoice.move_id or False
            if move_id:
                cr.execute('UPDATE account_invoice SET invoice_number=%s WHERE id=%s', (move_id.id, invoice.id))

        logger.notifyChannel("l10n_es_account_invoice_sequence_fix", netsvc.LOG_DEBUG, "%d invoices repaired." % len(invoice_ids))

        vals = {
        }
        return vals
class trial_cost(osv.TransientModel):
    logger = netsvc.Logger()
    _name = "trial.cost"
    _columns = {
        'date_start': fields.date('Start Date', required=True),
        'period_length': fields.integer('Period length (days)', required=True),
        'user_res_id': fields.many2one('res.users', 'Salesman'),
        'partner_res_id': fields.many2one('res.partner', 'Partner'),
        'cat_res_id': fields.many2one('product.category', 'Category'),
        'u_check': fields.boolean('Check salesman?'),
        'p_check': fields.boolean('Check partner?'),
        'c_check': fields.boolean('Check category?'),
    }

    _defaults = {
        'period_length': lambda *a: 30,
    }

    def action_print(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}

        data = {}
        data['ids'] = context.get('active_ids', [])
        data['model'] = context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(cr, uid, ids[0])
        form = data['form']
        if not form['u_check'] and not form['p_check'] and not form['c_check']:
            raise osv.except_osv(_('User Error'),
                                 _('You must check one box !'))
        res = {}
        period_length = data['form']['period_length']
        if period_length <= 0:
            raise osv.except_osv(
                _('UserError'),
                _('You must enter a period length that cannot be 0 or below !')
            )
        start = datetime.date.fromtimestamp(
            time.mktime(time.strptime(data['form']['date_start'], "%Y-%m-%d")))
        start = DateTime(int(start.year), int(start.month), int(start.day))

        for i in range(4)[::-1]:
            stop = start - RelativeDateTime(days=period_length)
            res[str(i)] = {
                'name':
                str((4 - (i + 1)) * period_length) + '-' + str(
                    (4 - i) * period_length),
                'stop':
                start.strftime('%Y-%m-%d'),
                'start':
                stop.strftime('%Y-%m-%d'),
            }
            start = stop - RelativeDateTime(days=1)

        data['form'].update(res)
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'profit.trial.cost',
            'datas': data
        }
Exemple #4
0
        def write_field(field_def):
            if not isinstance(field_def, tuple):
                logger = netsvc.Logger()
                msg = "Error on Object %s: field_def: %s [type: %s]" % (
                    obj_name.encode('utf8'), field_def.encode('utf8'),
                    type(field_def))
                logger.notifyChannel("base_module_doc_rst", netsvc.LOG_ERROR,
                                     msg)
                return ""

            field_name = field_def[0]
            field_dict = field_def[1]
            field_required = field_dict.get('required', '') and ', required'
            field_readonly = field_dict.get('readonly', '') and ', readonly'
            field_help_s = field_dict.get('help', '')
            if field_help_s:
                field_help_s = "*%s*" % (field_help_s)
                field_help = '\n'.join([
                    '    %s' % line.strip()
                    for line in field_help_s.split('\n')
                ])
            else:
                field_help = ''

            sl = [
                "",
                ":%s: %s, %s%s%s" %
                (field_name, field_dict.get('string', 'Unknown'),
                 field_dict['type'], field_required, field_readonly),
                "",
                field_help,
            ]
            return '\n'.join(sl)
Exemple #5
0
 def amount_to_text(self, nbr, lang='pe', currency=False):
     if not self._translate_funcs.has_key(lang):
         netsvc.Logger().notifyChannel("amount_to_text",netsvc.LOG_INFO, "WARNING: no translation function found for lang: '%s'" % (lang,))
         lang = 'en'
     if currency:
         exec("res = %s(abs(nbr), currency)"%(self._translate_funcs[lang]))
     else:
         exec("res = %s(abs(nbr))"%(self._translate_funcs[lang]))
     return res
Exemple #6
0
 def _fields_find(self, cr, uid, obj):
     modobj = self.pool.get(obj)
     if modobj:
         res = modobj.fields_get(cr, uid).items()
         return res
     else:
         logger = netsvc.Logger()
         msg = "Object %s not found" % (obj)
         logger.notifyChannel("base_module_doc_rst", netsvc.LOG_ERROR, msg)
         return ""
Exemple #7
0
 def amount_to_text_en(self, number, currency):
     netsvc.Logger().notifyChannel("amount_to_text_en",netsvc.LOG_INFO, "number_in: %s, currency: %s"%(number, currency))
     number = '%.2f' % number
     units_name = currency
     list = str(number).split('.')
     start_word = self.english_number(int(list[0]))
     end_word = self.english_number(int(list[1]))
     cents_number = int(list[1])
     cents_name = (cents_number > 1) and 'Cents' or 'Cent'
     final_result = start_word +' '+units_name+' and ' + end_word +' '+cents_name
     return final_result
Exemple #8
0
    def get_updated_currency(self, currency_array, main_currency,
                             max_delta_days):
        """implementation of abstract method of Curreny_getter_interface"""
        url = 'http://www.nbp.pl/kursy/xml/LastA.xml'  # LastA.xml is always the most recent one
        #we do not want to update the main currency
        if main_currency in currency_array:
            currency_array.remove(main_currency)
        # Move to new XML lib cf Launchpad bug #645263
        from lxml import etree
        logger = netsvc.Logger()
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "NBP.pl currency rate service : connecting...")
        rawfile = self.get_url(url)
        dom = etree.fromstring(
            rawfile)  # If rawfile is not XML, it crashes here
        ns = {}  # Cool, there are no namespaces !
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "NBP.pl sent a valid XML file")
        #node = xpath.Evaluate("/tabela_kursow", dom) # BEGIN Polish - rates table name
        #if isinstance(node, list) :
        #    node = node[0]
        #self.log_info = node.getElementsByTagName('numer_tabeli')[0].childNodes[0].data
        #self.log_info = self.log_info + " " + node.getElementsByTagName('data_publikacji')[0].childNodes[0].data    # END Polish - rates table name

        rate_date = dom.xpath('/tabela_kursow/data_publikacji/text()',
                              namespaces=ns)[0]
        rate_date_datetime = datetime.strptime(rate_date, '%Y-%m-%d')
        self.check_rate_date(rate_date_datetime, max_delta_days)
        #we dynamically update supported currencies
        self.supported_currency_array = dom.xpath(
            '/tabela_kursow/pozycja/kod_waluty/text()', namespaces=ns)
        self.supported_currency_array.append('PLN')
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Supported currencies = " + str(self.supported_currency_array))
        self.validate_cur(main_currency)
        if main_currency != 'PLN':
            main_curr_data = self.rate_retrieve(dom, ns, main_currency)
            # 1 MAIN_CURRENCY = main_rate PLN
            main_rate = main_curr_data['rate_currency'] / main_curr_data[
                'rate_ref']
        for curr in currency_array:
            self.validate_cur(curr)
            if curr == 'PLN':
                rate = main_rate
            else:
                curr_data = self.rate_retrieve(dom, ns, curr)
                # 1 MAIN_CURRENCY = rate CURR
                if main_currency == 'PLN':
                    rate = curr_data['rate_ref'] / curr_data['rate_currency']
                else:
                    rate = main_rate * curr_data['rate_ref'] / curr_data[
                        'rate_currency']
            self.updated_currency[curr] = rate
            # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
        return self.updated_currency, self.log_info
Exemple #9
0
class account_journal_bs_config(osv.Model):
    _name = 'account.journal.bs.config'
    _order = 'sequence asc'
    logger = netsvc.Logger()

    _columns = {
        'sequence':
        fields.integer('Label'),
        'bsl_id':
        fields.many2one('account.journal', 'Journal', required=False),
        'partner_id':
        fields.many2one('res.partner', 'Partner', required=False),
        'account_id':
        fields.many2one('account.account', 'Account', required=False),
        'expresion':
        fields.char('Text To be Compared',
                    size=128,
                    required=True,
                    readonly=False),
        'name':
        fields.char('Cancept Label', size=128, required=True, readonly=False),
    }
    _defaults = {
        'sequence': 10,
    }

    def _check_expresion(self, cr, user, ids, context=None):
        """
        A user defined constraints listed in {_constraints}
        @param cr: cursor to database
        @param user: id of current user
        @param ids: list of record ids on which constraints executes

        @return: return True if all constraints satisfied, False otherwise
        """
        try:
            exp_ = self.browse(cr, user, ids, context=context)[0].expresion
            exp = eval(exp_)
            self.logger.notifyChannel('Chain. ' + str(exp), netsvc.LOG_DEBUG,
                                      'Succefully Validated')
            if type(exp) is list:
                return True
            else:
                self.logger.notifyChannel('Chain. ' + str(exp_),
                                          netsvc.LOG_ERROR,
                                          'Fail With You must use a list')
                return False
        except Exception, var:
            self.logger.notifyChannel('Chain. ' + str(exp_), netsvc.LOG_ERROR,
                                      'Fail With %s' % var)
            return False
Exemple #10
0
    def get_updated_currency(self, currency_array, main_currency,
                             max_delta_days):
        """implementation of abstract method of Curreny_getter_interface"""
        url = 'http://www.afd.admin.ch/publicdb/newdb/mwst_kurse/wechselkurse.php'
        #we do not want to update the main currency
        if main_currency in currency_array:
            currency_array.remove(main_currency)
        # Move to new XML lib cf Launchpad bug #645263
        from lxml import etree
        logger = netsvc.Logger()
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Admin.ch currency rate service : connecting...")
        rawfile = self.get_url(url)
        dom = etree.fromstring(rawfile)
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Admin.ch sent a valid XML file")
        adminch_ns = {
            'def': 'http://www.afd.admin.ch/publicdb/newdb/mwst_kurse'
        }
        rate_date = dom.xpath('/def:wechselkurse/def:datum/text()',
                              namespaces=adminch_ns)[0]
        rate_date_datetime = datetime.strptime(rate_date, '%Y-%m-%d')
        self.check_rate_date(rate_date_datetime, max_delta_days)
        #we dynamically update supported currencies
        self.supported_currency_array = dom.xpath(
            "/def:wechselkurse/def:devise/@code", namespaces=adminch_ns)
        self.supported_currency_array = [
            x.upper() for x in self.supported_currency_array
        ]
        self.supported_currency_array.append('CHF')

        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Supported currencies = " + str(self.supported_currency_array))
        self.validate_cur(main_currency)
        if main_currency != 'CHF':
            main_curr_data = self.rate_retrieve(dom, adminch_ns, main_currency)
            # 1 MAIN_CURRENCY = main_rate CHF
            main_rate = main_curr_data['rate_currency'] / main_curr_data[
                'rate_ref']
        for curr in currency_array:
            self.validate_cur(curr)
            if curr == 'CHF':
                rate = main_rate
            else:
                curr_data = self.rate_retrieve(dom, adminch_ns, curr)
                # 1 MAIN_CURRENCY = rate CURR
                if main_currency == 'CHF':
                    rate = curr_data['rate_ref'] / curr_data['rate_currency']
                else:
                    rate = main_rate * curr_data['rate_ref'] / curr_data[
                        'rate_currency']
            self.updated_currency[curr] = rate
            # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
        return self.updated_currency, self.log_info
Exemple #11
0
    def get_updated_currency(self, currency_array, main_currency,
                             max_delta_days):
        """implementation of abstract method of Curreny_getter_interface"""
        url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
        # Important : as explained on the ECB web site, the currencies are
        # at the beginning of the afternoon ; so, until 3 p.m. Paris time
        # the currency rates are the ones of trading day N-1
        # see http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html

        #we do not want to update the main currency
        if main_currency in currency_array:
            currency_array.remove(main_currency)
        # Move to new XML lib cf Launchpad bug #645263
        from lxml import etree
        logger = netsvc.Logger()
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "ECB currency rate service : connecting...")
        rawfile = self.get_url(url)
        dom = etree.fromstring(rawfile)
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "ECB sent a valid XML file")
        ecb_ns = {
            'gesmes': 'http://www.gesmes.org/xml/2002-08-01',
            'def': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'
        }
        rate_date = dom.xpath('/gesmes:Envelope/def:Cube/def:Cube/@time',
                              namespaces=ecb_ns)[0]
        rate_date_datetime = datetime.strptime(rate_date, '%Y-%m-%d')
        self.check_rate_date(rate_date_datetime, max_delta_days)
        #we dynamically update supported currencies
        self.supported_currency_array = dom.xpath(
            "/gesmes:Envelope/def:Cube/def:Cube/def:Cube/@currency",
            namespaces=ecb_ns)
        self.supported_currency_array.append('EUR')
        # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Supported currencies = " + str(self.supported_currency_array))
        self.validate_cur(main_currency)
        if main_currency != 'EUR':
            main_curr_data = self.rate_retrieve(dom, ecb_ns, main_currency)
        for curr in currency_array:
            self.validate_cur(curr)
            if curr == 'EUR':
                rate = 1 / main_curr_data['rate_currency']
            else:
                curr_data = self.rate_retrieve(dom, ecb_ns, curr)
                if main_currency == 'EUR':
                    rate = curr_data['rate_currency']
                else:
                    rate = curr_data['rate_currency'] / main_curr_data[
                        'rate_currency']
            self.updated_currency[curr] = rate
            # logger.notifyChannel("rate_update", netsvc.LOG_DEBUG, "Rate retrieved : 1 " + main_currency + ' = ' + str(rate) + ' ' + curr)
        return self.updated_currency, self.log_info
Exemple #12
0
 def _is_connection_status_good(link):
     server = "openerp.com"
     status_good = False
     try:
         conn = httplib.HTTPConnection(server)
         conn.request("HEAD", link)
         res = conn.getresponse()
         if res.status in (200, ):
             status_good = True
     except (Exception, ), e:
         logger = netsvc.Logger()
         msg = """
         error connecting to server '%s' with link '%s'.
         Error message: %s
         """ % (server, link, str(e))
         logger.notifyChannel("base_module_doc_rst", netsvc.LOG_ERROR,
                              msg)
         status_good = False
Exemple #13
0
 def evaluate(self, cursor, user, promotion_rule, order, context=None):
     """
     Evaluates if a promotion is valid
     @param cursor: Database Cursor
     @param user: ID of User
     @param promotion_rule: Browse Record
     @param order: Browse Record
     @param context: Context(no direct use).
     """
     if not context:
         context = {}
     expression_obj = self.pool.get('promos.rules.conditions.exps')
     try:
         self.check_primary_conditions(cursor, user, promotion_rule, order,
                                       context)
     except Exception, e:
         if DEBUG:
             netsvc.Logger().notifyChannel("Promotions", netsvc.LOG_INFO,
                                           ustr(e))
         return False
Exemple #14
0
import report
from openerp.report import report_sxw
from report.report_sxw import *
from report.report_sxw import rml_parse
from lxml import etree
import subprocess
import os
import cStringIO
import base64
import time

import openerp.netsvc as netsvc
import openerp.tools as tools
import openerp.netsvc as netsvc

logger = netsvc.Logger()


def checkBins(*bin):
    bins = list(bin)

    searchPaths = os.environ["PATH"].split(":")
    for path in searchPaths:
        for bin in bins:
            if os.path.exists(os.path.join(path, bin)):
                bins.remove(bin)
        if bins == []:
            return
    raise IOError("required binaries not %s found" % ", ".join(bins))

Exemple #15
0
class picking_valued(osv.TransientModel):
    logger = netsvc.Logger()
    _name = "picking.valued"
    _columns = {
        'type':
        fields.selection([
            ('entrega', 'Nota de Entrega (Con Precios)'),
            ('despacho', 'Nota de Entrega (Sin Precios)'),
        ],
                         'Type',
                         required=True,
                         select=True),
        'sure':
        fields.boolean('Are you sure?'),
        'sure2':
        fields.boolean('Are you sure?'),
        'sure3':
        fields.boolean('Are you sure?'),
        'sure4':
        fields.boolean('Are you sure?'),
        'note':
        fields.char('Note', size=256, required=False, readonly=False),
        'note2':
        fields.char('Note', size=256, required=False, readonly=False),
        'reason':
        fields.selection([('rep', 'Reparación'),
                          ('tdep', 'Traslado a depósito'),
                          ('talmo', 'Traslado almacenes o bodegas de otros'),
                          ('talmp', 'Traslado almacenes o bodegas propios'),
                          ('tdis', 'Traslado para su distribución'),
                          ('otr', 'Otros')],
                         'Reason',
                         select=True),
        'nro':
        fields.char('Number', 32, readonly=True),
    }

    _defaults = {'type': 'entrega'}

    def default_get(self, cr, uid, fields, context=None):
        """
         To get default values for the object.
         @param self: The object pointer.
         @param cr: A database cursor
         @param uid: ID of the user currently logged in
         @param fields: List of fields for which we want default values
         @param context: A standard dictionary
         @return: A dictionary with default values for all field in ``fields``
        """
        if context is None:
            context = {}
        res = super(picking_valued, self).default_get(cr,
                                                      uid,
                                                      fields,
                                                      context=context)
        record_id = context and context.get('active_id', False) or False
        pick_obj = self.pool.get('picking.valued')
        pick = pick_obj.browse(cr, uid, record_id, context=context)
        if pick:
            for field in ('type', 'note', 'nro'):
                if context.get(field, False):
                    res[field] = context[field]
                    if field == 'note':
                        res['note2'] = context[field]
        return res

    def action_start(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        data_pool = self.pool.get('ir.model.data')
        obj = self.browse(cr, uid, ids[0])
        if obj.sure == False:
            raise osv.except_osv(_('Alert !'), _('Check the box!!!'))
        context.update({'type': obj.type})

        action = {}
        action_model, action_id = data_pool.get_object_reference(
            cr, uid, 'l10n_ve_stock', "action_pick_trans")
        if action_model:
            action_pool = self.pool.get(action_model)
            action = action_pool.read(cr, uid, action_id, context=context)
            action.update({'context': context})

        return action

    def action_trans(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        data_pool = self.pool.get('ir.model.data')
        obj = self.browse(cr, uid, ids[0])
        if obj.sure2 == False:
            raise osv.except_osv(_('Alert !'), _('Check the box!!!'))

        context.update({'note': obj.note})
        if not context['note']:
            return self.action_number(cr, uid, ids, context=context)

        action = {}
        action_model, action_id = data_pool.get_object_reference(
            cr, uid, 'l10n_ve_stock', "action_pick_note")
        if obj.type == 'despacho':
            action_model, action_id = data_pool.get_object_reference(
                cr, uid, 'l10n_ve_stock', "action_pick_reason")
        if action_model:
            action_pool = self.pool.get(action_model)
            action = action_pool.read(cr, uid, action_id, context=context)
            action.update({'context': context})

        return action

    def make_nro(self, cr, uid, ids, context=None):
        cr.execute(
            'SELECT id, number '
            'FROM stock_picking '
            'WHERE id IN  %s', (tuple(ids), ))

        for (id, number) in cr.fetchall():
            if not number:
                number = self.pool.get('ir.sequence').get(
                    cr, uid, 'stock.valued')
            cr.execute('UPDATE stock_picking SET number=%s '
                       'WHERE id=%s', (number, id))

        return number

    def action_number(self, cr, uid, ids, context=None):
        if context is None:
            context = {}

        data_pool = self.pool.get('ir.model.data')
        obj = self.browse(cr, uid, ids[0])
        comment = obj.note2 or obj.note
        razon = getattr(obj, 'reason')
        motiv = {
            'rep': 'Reparación',
            'tdep': 'Traslado a depósito',
            'talmo': 'Traslado almacenes o bodegas de otros',
            'talmp': 'Traslado almacenes o bodegas propios',
            'tdis': 'Traslado para su distribución',
            'otr': 'Otros'
        }

        record_id = context and context.get('active_id', False) or False
        pick_obj = self.pool.get('stock.picking')
        number = self.make_nro(cr, uid, [record_id], context)
        if razon:
            comment += '\n' + motiv[razon]
        pick_obj.write(cr, uid, [record_id], {'note': comment})

        context.update({'nro': number})
        action = {}
        action_model, action_id = data_pool.get_object_reference(
            cr, uid, 'l10n_ve_stock', "action_pick_end")
        if action_model:
            action_pool = self.pool.get(action_model)
            action = action_pool.read(cr, uid, action_id, context=context)
            action.update({'context': context})

        return action
Exemple #16
0
    def _generate(self, cr, uid, context):
        module_model = self.pool.get('ir.module.module')
        module_ids = context['active_ids']

        module_index = []

        # create a temporary gzipped tarfile:
        tgz_tmp_filename = tempfile.mktemp('_rst_module_doc.tgz')
        try:
            tarf = tarfile.open(tgz_tmp_filename, 'w:gz')

            modules = module_model.browse(cr, uid, module_ids)
            for module in modules:
                index_dict = {
                    'name': module.name,
                    'shortdesc': module.shortdesc,
                }
                module_index.append(index_dict)

                objects = self._get_objects(cr, uid, module)
                module.test_views = self._get_views(cr,
                                                    uid,
                                                    module.id,
                                                    context=context)
                rstdoc = RstDoc(module, objects)

                # Append Relationship Graph on rst
                graph_mod = False
                module_name = False
                if module.file_graph:
                    graph_mod = base64.decodestring(module.file_graph)
                else:
                    module_data = module_model.get_relation_graph(
                        cr, uid, module.name, context=context)
                    if module_data['module_file']:
                        graph_mod = base64.decodestring(
                            module_data['module_file'])
                if graph_mod:
                    module_name = module.name
                    try:
                        tmp_file_graph = tempfile.NamedTemporaryFile()
                        tmp_file_graph.write(graph_mod)
                        tmp_file_graph.file.flush()
                        tarf.add(tmp_file_graph.name,
                                 arcname=module.name + '_module.png')
                    finally:
                        tmp_file_graph.close()

                out = rstdoc.write(module_name)
                try:
                    tmp_file = tempfile.NamedTemporaryFile()
                    tmp_file.write(out.encode('utf8'))
                    tmp_file.file.flush()  # write content to file
                    tarf.add(tmp_file.name, arcname=module.name + '.rst')
                finally:
                    tmp_file.close()

            # write index file:
            tmp_file = tempfile.NamedTemporaryFile()
            out = self._create_index(module_index)
            tmp_file.write(out.encode('utf8'))
            tmp_file.file.flush()
            tarf.add(tmp_file.name, arcname='index.rst')
        finally:
            tarf.close()

        f = open(tgz_tmp_filename, 'rb')
        out = f.read()
        f.close()

        if os.path.exists(tgz_tmp_filename):
            try:
                os.unlink(tgz_tmp_filename)
            except Exception, e:
                logger = netsvc.Logger()
                msg = "Temporary file %s could not be deleted. (%s)" % (
                    tgz_tmp_filename, e)
                logger.notifyChannel("warning", netsvc.LOG_WARNING, msg)
    def find_cost(self, cr, uid, config_id, address, model_obj, context=None):
        """
        Function to calculate shipping cost
        """
        cost = 0
        table_pool = self.pool.get('shipping.rate')
        config_pool = self.pool.get('shipping.rate.config')
        logger = netsvc.Logger()
        config_obj = config_pool.browse(cr, uid, config_id, context=context)
        rate_card_id = config_obj.rate_card_id.id
        if config_obj.calc_method == 'country_weight':
            country_id = address.country_id.id
            weight_net = model_obj.total_weight_net
            table_ids = table_pool.search(cr,
                                          uid,
                                          [('card_id', '=', rate_card_id),
                                           ('country_id', '=', country_id),
                                           ('from_weight', '<=', weight_net),
                                           ('to_weight', '>', weight_net)],
                                          context=context)
            if table_ids:
                table_obj = table_pool.browse(cr,
                                              uid,
                                              table_ids[0],
                                              context=context)
                if table_obj.charge == 0.0 and table_obj.over_cost:
                    cost = model_obj.total_weight_net * table_obj.over_cost
                else:
                    cost = table_obj.charge

            else:
                search_list = [('card_id', '=', rate_card_id),
                               ('country_id', '=', country_id),
                               ('over_cost', '>', 0)]
                table_ids = table_pool.search(cr,
                                              uid,
                                              search_list,
                                              context=context)
                if table_ids:
                    table_objs = table_pool.browse(cr,
                                                   uid,
                                                   table_ids,
                                                   context=context)
                    table_obj = table_objs[0]
                    for table in table_objs:
                        if table_obj.from_weight < table.from_weight:
                            table_obj = table
                    weight = model_obj.total_weight_net
                    if table_obj.charge > 0:
                        cost = table_obj.charge
                        weight -= table_obj.from_weight
                        if weight > 0:
                            cost += weight * table_obj.over_cost
                    else:
                        cost = weight * table_obj.over_cost
                else:
                    logger.notifyChannel(
                        _("Calculate Shipping"), netsvc.LOG_WARNING,
                        _("Unable to find rate table with Shipping Table = %s and \
                                            Country = %s and Over Cost > 0." %
                          (config_obj.rate_card_id.name,
                           address.country_id.name)))

        elif config_obj.calc_method == 'state_zone_weight':
            zone_pool = self.pool.get('zone.map')
            state_id = address.state_id.id
            zone_ids = zone_pool.search(
                cr,
                uid, [('rate_config_id', '=', config_obj.id),
                      ('state_id', '=', state_id)],
                context=context)
            if zone_ids:
                zone = zone_pool.read(cr,
                                      uid,
                                      zone_ids, ['zone'],
                                      context=context)[0]['zone']
                table_ids = table_pool.search(cr,
                                              uid,
                                              [('card_id', '=', rate_card_id),
                                               ('zone', '=', zone)],
                                              context=context)
                if table_ids:
                    table_obj = table_pool.browse(cr,
                                                  uid,
                                                  table_ids,
                                                  context=context)[0]
                    weight = model_obj.total_weight_net
                    if table_obj.charge > 0:
                        cost = table_obj.charge
                        weight -= table_obj.to_weight
                        if weight > 0:
                            cost += weight * table_obj.over_cost
                    else:
                        cost = weight * table_obj.over_cost
                else:
                    logger.notifyChannel(
                        _("Calculate Shipping"), netsvc.LOG_WARNING,
                        _("Unable to find rate table with Shipping Table = %s and \
                                            Zone = %s." %
                          (config_obj.shipmethodname, zone)))
            else:
                logger.notifyChannel(
                    _("Calculate Shipping"), netsvc.LOG_WARNING,
                    _("Unable to find Zone Mapping Table with Shipping Rate \
                                        Configuration = %s and State = %s." %
                      (config_obj.shipmethodname, address.state_id.name)))
        elif config_obj.calc_method == 'manual':
            cost = 0.0
        return cost
Exemple #18
0
    def create_source_pdf(self, cr, uid, ids, data, report_xml, context=None):
        flag = False
        if not context:
            context = {}
        pool = pooler.get_pool(cr.dbname)
        attach = report_xml.attachment
        #~
        #~ Check in the new model if this report allow to reprint,
        #~ Allowtoreprint should mandate over attach,
        if attach:
            objs = self.getObjects(cr, uid, ids, context)
            results = []
            for obj in objs:
                aname = eval(attach, {'object': obj, 'time': time})
                result = False
                if report_xml.attachment_use and aname and context.get(
                        'attachment_use', True):
                    aids = pool.get('ir.attachment').search(
                        cr, uid, [('datas_fname', '=', aname + '.pdf'),
                                  ('res_model', '=', self.table),
                                  ('res_id', '=', obj.id)])
                    if aids:
                        brow_rec = pool.get('ir.attachment').browse(
                            cr, uid, aids[0])
                        if not brow_rec.datas:
                            continue
                        d = base64.decodestring(brow_rec.datas)
                        results.append((d, 'pdf'))
                        continue
                result = self.create_single_pdf(cr, uid, [obj.id], data,
                                                report_xml, context)
                if not result:
                    return False
                try:
                    if aname:
                        flag = True  # ya que entra solo la primera vez sin attachment
                        name = aname + '.' + result[1]
                        pool.get('ir.attachment').create(
                            cr,
                            uid, {
                                'name': aname,
                                'datas': base64.encodestring(result[0]),
                                'datas_fname': name,
                                'res_model': self.table,
                                'res_id': obj.id,
                            },
                            context=context)
                        cr.commit()

                except Exception, e:
                    import traceback
                    import sys
                    tb_s = reduce(
                        lambda x, y: x + y,
                        traceback.format_exception(sys.exc_type, sys.exc_value,
                                                   sys.exc_traceback))
                    netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR,
                                                  str(e))
                results.append(result)
            if results:
                if results[0][1] == 'pdf':
                    if not context.get('allow', False):
                        return self.create_single_pdf(cr, uid, ids, data,
                                                      report_xml, context)
                    else:
                        from pyPdf import PdfFileWriter, PdfFileReader
                        output = PdfFileWriter()
                        for r in results:
                            reader = PdfFileReader(cStringIO.StringIO(r[0]))
                            for page in range(reader.getNumPages()):
                                output.addPage(reader.getPage(page))
                        s = cStringIO.StringIO()
                        output.write(s)
                        return s.getvalue(), results[0][1]
Exemple #19
0
#
##############################################################################

try:
    #Backward compatible
    from sets import Set as set
except:
    pass

from openerp.osv import osv, fields
from tools.misc import ustr
from openerp import netsvc
from tools.translate import _

#LOGGER = netsvc.Logger()
LOGGER = netsvc.Logger()
DEBUG = True
PRODUCT_UOM_ID = 1

ATTRIBUTES = [
    ('amount_untaxed', _('Untaxed Total')),
    ('amount_tax', 'Tax Amount'),
    ('amount_total', 'Total Amount'),
    ('product', 'Product Code in order'),
    ('prod_qty', 'Product Quantity combination'),
    ('prod_unit_price', 'Product UnitPrice combination'),
    ('prod_sub_total', 'Product SubTotal combination'),
    #    ('prod_net_price', 'Product NetPrice combination'),
    ('prod_discount', 'Product Discount combination'),
    ('prod_weight', 'Product Weight combination'),
    ('comp_sub_total', 'Compute sub total of products'),
Exemple #20
0
 def text_plain(text):
     netsvc.Logger().notifyChannel('report_aeroo', netsvc.LOG_INFO, msg)
     return text
Exemple #21
0
        try:
            from report_aeroo_ooo.report import OpenOffice_service
        except Exception, e:
            OpenOffice_service = False

        if OpenOffice_service:
            cr.execute("SELECT id, state FROM ir_module_module WHERE name='report_aeroo_ooo'")
            helper_module = cr.dictfetchone()
            helper_installed = helper_module and helper_module['state'] == 'installed'

        if OpenOffice_service and helper_installed:
            try:
                cr.execute("SELECT host, port FROM oo_config")
                host, port = cr.fetchone()
                OpenOffice_service(cr, host, port)
                netsvc.Logger().notifyChannel('report_aeroo', netsvc.LOG_INFO,
                    "OpenOffice.org connection successfully established")
            except Exception, e:
                netsvc.Logger().notifyChannel('report_aeroo', netsvc.LOG_WARNING, str(e))
        ##############################################

        cr.execute(
            "SELECT * FROM ir_act_report_xml WHERE report_type = 'aeroo' and active = true ORDER BY id")  # change for OpenERP 6.0
        records = cr.dictfetchall()
        for record in records:
            parser = rml_parse
            if record['parser_state'] == 'loc' and record['parser_loc']:
                parser = self.load_from_file(record['parser_loc'], cr.dbname, record['id']) or parser
            elif record['parser_state'] == 'def' and record['parser_def']:
                parser = self.load_from_source("from report import report_sxw\n" + record['parser_def']) or parser
            self.register_report(cr, record['report_name'], record['model'], record['report_rml'], parser)