0
votes

Why I am getting this error?

Traceback(most recent call last):
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
650, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
310, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File
"/home/prachh/odoo-new/11/odoo/odoo/tools/pycompat.py", line
87, in reraise
raise value
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
692, in dispatch
result = self._call_function(**self.params)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
342, in _call_function
return checked_call(self.db, *args, **kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/service/model.py", line
97, in wrapper
return f(dbname, *args, **kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
335, in checked_call
result = self.endpoint(*a, **kw)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
936, in call
return self.method(*args, **kw)
File
"/home/prachh/odoo-new/11/odoo/odoo/http.py", line
515, in response_wrap
response = f(*args, **kw)
File
"/home/prachh/odoo-new/11/odoo/addons/web/controllers/main.py", line
934, in call_button
action = self._call_kw(model, method, args, {})
File
"/home/prachh/odoo-new/11/odoo/addons/web/controllers/main.py", line
922, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/api.py", line
689, in call_kw
return call_kw_multi(method, model, args, kwargs)
File
"/home/prachh/odoo-new/11/odoo/odoo/api.py", line
680, in call_kw_multi
result = method(recs, *args, **kwargs)
File
"/home/prachh/odoo-new/11/enterprise/account_bank_statement_import_csv/wizard/account_bank_statement_import_csv.py", line
19, in import_file
return super(AccountBankStatementImport, self).import_file()
File
"/home/prachh/odoo-new/11/apps/account_bank_statement_import_bankgiro/models/inherited_account_bank_statement_import.py", line
18, in import_file
else:
File
"/home/prachh/odoo-new/11/apps/account_bank_statement_import_bankgiro/models/inherited_account_bank_statement_import.py", line
26, in _parse_file_txt
File
"/home/prachh/odoo-new/11/apps/account_bank_statement_import_bankgiro/models/inherited_account_bank_statement_import.py", line
107, in records
'antal_extra_referansposter': line[18:26], 'antal_insattningsposter': line[26:34]}, KeyError: b'01' 
I put his .decode("utf-8") Is it right? check this code if this is wrong so where i need put this?
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
import base64


class AccountBankStatementImportBankgiro(models.TransientModel):
    _inherit = 'account.bank.statement.import'

    @staticmethod
    def _check_bg(data_file):
        return data_file.strip().startswith(b'01BGMAX')

    @api.multi
    def import_file(self):
        if not self._check_bg(base64.standard_b64decode(self.data_file)):
            return super(AccountBankStatementImportBankgiro, self).import_file()
        else:
            return self._parse_file_txt(base64.standard_b64decode(self.data_file))

    def _parse_file_txt(self, data_file):
        st_ids = []
        journal_id = self._context.get('journal_id')

        for line in data_file.splitlines():

            vals = self.records(line)

            if vals['post'] == 'startpost':
                date = vals['skrivdag_tidsstampel'][:8]
                id = self.env['account.bank.statement'].create({
                    'name': ("%s-%s") % (vals['layoutnamn'], vals['skrivdag_tidsstampel']),
                    'journal_id': journal_id,
                    'date': date,
                })
                st_ids.append(id.id)

            if vals['post'] == 'oppningspost':
                bgnummer = ("%s-%s") % (vals['mottagarbankgironummer'][2:6], vals['mottagarbankgironummer'][6:])

            if vals['post'] == 'organisationsnummerpost':
                result = self.env['res.partner'].search([('ref', '=', vals['organisationsnummer'][2:])], limit=1)

                if result and lid:
                    st_line = self.env['account.bank.statement.line'].search([('id', '=', lid.id)])
                    st_line.write({
                        'partner_id': result[0]['id']
                    })

            if vals['post'] == 'betalningspost':
                referens = vals['referens'] if vals['referens'] != "" else "."
                amount = float(vals['betalningsbelopp']) / 100

                lid = self.env['account.bank.statement.line'].create({
                    'statement_id': id.id,
                    'name': referens.decode('iso-8859-1'),
                    'journal_id': journal_id,
                    'amount': amount,
                    'date': date,
                })

            if vals['post'] == 'insattningspost':
                referens = ("Bg %s %s") % (bgnummer, vals['insattningslopnummer'])
                amount = -float(vals['insattningsbelopp']) / 100

                lid = self.env['account.bank.statement.line'].create({
                    'statement_id': id.id,
                    'name': referens,
                    'journal_id': journal_id,
                    'amount': amount,
                    'date': date
                })

        if st_ids:
            action = self.env.ref('account.action_bank_reconcile_bank_statements')

            return {
                'name': action.name,
                'tag': action.tag,
                'context': {
                    'statement_ids': st_ids,
                },
                'type': 'ir.actions.client',
            }

    @staticmethod
    def records(line):
        return {
            '01': {'post': 'startpost', 'layoutnamn': line[2:22].strip(), 'skrivdag_tidsstampel': line[24:44],
                   'testmarkering': line[44]},
            '05': {'post': 'oppningspost', 'mottagarbankgironummer': line[2:12], 'valuta': line[22:25]},
            '20': {'post': 'betalningspost', 'avsandarbankgironummer': line[2:12], 'referens': line[12:37].strip(),
                   'betalningsbelopp': line[37:55], 'referenskod': line[55]},
            '21': {'post': 'avdragspost', 'avsandarbankgironummer': line[2:12], 'referens': line[12:37],
                   'betalningsbelopp': line[37:55], 'referenskod': line[55]},
            '22': {'post': 'extra referensnummerpost'},
            '23': {'post': 'extra referensnummerpost negativ'},
            '25': {'post': 'informationspost', 'informationstext': line[2:52]},
            '26': {'post': 'namnpost', 'betalarens_namn': line[2:37].strip()},
            '27': {'post': 'adresspost1', 'betalarens_adress': line[2:37].strip(),
                   'betalarens_postnummer': line[37:46].strip()},
            '28': {'post': 'adresspost2', 'betalarens_ortsadress': line[2:37].strip()},
            '29': {'post': 'organisationsnummerpost', 'organisationsnummer': line[2:14]},
            '15': {'post': 'insattningspost', 'mottagarbankgironummer': line[2:37], 'betalningsdag': line[37:45],
                   'insattningslopnummer': line[45:50], 'insattningsbelopp': line[50:68], 'antal_betalningar': line[71:79]},
            '70': {'post': 'slutpost', 'antal_betalposter': line[2:10], 'antal_avdragsposter': line[10:18],
                   'antal_extra_referansposter': line[18:26], 'antal_insattningsposter': line[26:34]},
        }[line[:2].decode('utf-8')]


2
Your problem is that b'01' key is not present in the dict (records return value).Kenly
where can i change give me idea?Pragya Chhabra
Try to convert bytes to string .decode("utf-8") .Kenly
I put his .decode("utf-8") Is it right? check this code if this is wrong so where i need put this?Pragya Chhabra
@WaKo I didn't understand.What is the problem please help mePragya Chhabra

2 Answers

1
votes

Sounds like data_file is a bytes object, not a str. In which case .startsiwith requires a bytes argument (written as b'text'), not a unicode string (written as 'text'). In this case you want

 return data_file.strip().startswith(b'01BGMAX')

Proof

b'hello world '.strip().startswith('hello')

# ---------------------------------------------------------------------------
# TypeError                                 Traceback (most recent call last)
# <ipython-input-38-cc253315406b> in <module>()
# ----> 1 b'hello world '.strip().startswith('hello')
# 
# TypeError: startswith first arg must be bytes or a tuple of bytes, not str


b'hello world '.strip().startswith(b'hello')
# True
-1
votes

Byte literals start with 'b'. It creates a instance of bytes type instead of string type. You are getting an error as you have directly passed a string. Try

return data_file.strip().startswith(b'01BGMAX')

This will tell python that it is a sequence of bytes and not Unicode characters