def _get_default_image(self): image_path = modules.get_resource_path('mail', 'static/src/img', 'groupdefault.png') with tools.file_open(image_path, 'rb') as fd: return base64.b64encode(fd.read())
def binary_content(cls, xmlid=None, model='ir.attachment', id=None, field='datas', unique=False, filename=None, filename_field='datas_fname', download=False, mimetype=None, default_mimetype='application/octet-stream', env=None): """ Get file, attachment or downloadable content If the ``xmlid`` and ``id`` parameter is omitted, fetches the default value for the binary field (via ``default_get``), otherwise fetches the field for that precise record. :param str xmlid: xmlid of the record :param str model: name of the model to fetch the binary from :param int id: id of the record from which to fetch the binary :param str field: binary field :param bool unique: add a max-age for the cache control :param str filename: choose a filename :param str filename_field: if not create an filename with model-id-field :param bool download: apply headers to download the file :param str mimetype: mintype of the field (for headers) :param str default_mimetype: default mintype if no mintype found :param Environment env: by default use request.env :returns: (status, headers, content) """ env = env or request.env # get object and content obj = None if xmlid: obj = env.ref(xmlid, False) elif id and model in env.registry: obj = env[model].browse(int(id)) # obj exists if not obj or not obj.exists() or field not in obj: return 404, [], None # check read access try: last_update = obj['__last_update'] except AccessError: return 403, [], None status, headers, content = None, [], None # attachment by url check module_resource_path = None if model == 'ir.attachment' and obj.type == 'url' and obj.url: url_match = re.match("^/(\w+)/(.+)$", obj.url) if url_match: module = url_match.group(1) module_path = get_module_path(module) module_resource_path = get_resource_path( module, url_match.group(2)) if module_path and module_resource_path: module_path = os.path.join( os.path.normpath(module_path), '') # join ensures the path ends with '/' module_resource_path = os.path.normpath( module_resource_path) if module_resource_path.startswith(module_path): with open(module_resource_path, 'rb') as f: content = base64.b64encode(f.read()) last_update = str( os.path.getmtime(module_resource_path)) if not module_resource_path: module_resource_path = obj.url if not content: status = 301 content = module_resource_path else: content = obj[field] or '' # filename if not filename: if filename_field in obj: filename = obj[filename_field] elif module_resource_path: filename = os.path.basename(module_resource_path) else: filename = "%s-%s-%s" % (obj._name, obj.id, field) # mimetype mimetype = 'mimetype' in obj and obj.mimetype or False if not mimetype: if filename: mimetype = mimetypes.guess_type(filename)[0] if not mimetype and getattr(env[model]._fields[field], 'attachment', False): # for binary fields, fetch the ir_attachement for mimetype check attach_mimetype = env['ir.attachment'].search_read( domain=[('res_model', '=', model), ('res_id', '=', id), ('res_field', '=', field)], fields=['mimetype'], limit=1) mimetype = attach_mimetype and attach_mimetype[0]['mimetype'] if not mimetype: mimetype = guess_mimetype(base64.b64decode(content), default=default_mimetype) headers += [('Content-Type', mimetype), ('X-Content-Type-Options', 'nosniff')] # cache etag = hasattr( request, 'httprequest') and request.httprequest.headers.get('If-None-Match') retag = '"%s"' % hashlib.md5(content).hexdigest() status = status or (304 if etag == retag else 200) headers.append(('ETag', retag)) headers.append( ('Cache-Control', 'max-age=%s' % (STATIC_CACHE if unique else 0))) # content-disposition default name if download: headers.append( ('Content-Disposition', IrHttp.content_disposition(filename))) # force download on safari headers.append(('Pragma', 'no-cache')) headers.append(('Expires', '0')) # Get Full File Length file_len = len(base64.b64decode(content)) response_length = file_len # Just for byte-range requests if request.httprequest.environ.get('HTTP_RANGE', False): try: first, last = parse_byte_range( request.httprequest.environ.get('HTTP_RANGE')) except ValueError as e: return 400, [], None # Fix last for "x-" like ranges if last is None or last >= file_len: last = file_len - 1 if first >= file_len: return 416, [], None status = 206 # Offset ranges needs offset content if first != 0: if last != file_len - 1: couple_bytes = base64.b64decode(content)[first:last] else: couple_bytes = base64.b64decode(content)[first:] content = base64.b64encode(couple_bytes) response_length = last - first + 1 headers.append( ('Content-Range', 'bytes %s-%s/%s' % (first, last, file_len))) headers.append(('Accept-Ranges', 'bytes')) headers.append(('Content-Length', str(response_length))) return status, headers, content
def get_path(filename): res = get_resource_path('l10n_ch_import_winbiz', 'tests', filename) return res
def get_original_document_path(self, data, objs): return get_resource_path('report_fillpdf', 'static/src/pdf', 'partner_pdf.pdf')
def test_ailos_return(self): mocked_response = [ { "codigo_registro": "03", "codigo_ocorrencia": "06", "data_ocorrencia": None, "agencia_com_dv": None, "agencia_sem_dv": "1234", "cedente_com_dv": "000003719", "convenio": None, "nosso_numero": "00000000000" + self.invoice_ailos_1_own_numbers[0], "tipo_cobranca": None, "tipo_cobranca_anterior": None, "natureza_recebimento": None, "carteira_variacao": None, "desconto": "0000000000000", "iof": None, "carteira": None, "comando": None, "data_liquidacao": None, "data_vencimento": "06072021", "valor_titulo": "0000000030000", "banco_recebedor": "136", "agencia_recebedora_com_dv": "12343", "especie_documento": None, "data_credito": "06072021", "valor_tarifa": "0000180", "outras_despesas": None, "juros_desconto": None, "iof_desconto": None, "valor_abatimento": "0000000000000", "desconto_concedito": None, "valor_recebido": "0000000030000", "juros_mora": "0000000000000", "outros_recebimento": None, "abatimento_nao_aproveitado": None, "valor_lancamento": None, "indicativo_lancamento": None, "indicador_valor": None, "valor_ajuste": None, "sequencial": "00000", "arquivo": None, "motivo_ocorrencia": [], "documento_numero": None, }, { "codigo_registro": "03", "codigo_ocorrencia": "06", "data_ocorrencia": None, "agencia_com_dv": None, "agencia_sem_dv": "1234", "cedente_com_dv": "000003719", "convenio": None, "nosso_numero": "00000000000" + self.invoice_ailos_1_own_numbers[1], "tipo_cobranca": None, "tipo_cobranca_anterior": None, "natureza_recebimento": None, "carteira_variacao": None, "desconto": "0000000000000", "iof": None, "carteira": None, "comando": None, "data_liquidacao": None, "data_vencimento": "06072021", "valor_titulo": "0000000070000", "banco_recebedor": "136", "agencia_recebedora_com_dv": "12343", "especie_documento": None, "data_credito": "06072021", "valor_tarifa": "0000180", "outras_despesas": None, "juros_desconto": None, "iof_desconto": None, "valor_abatimento": "0000000000000", "desconto_concedito": None, "valor_recebido": "0000000070000", "juros_mora": "0000000000000", "outros_recebimento": None, "abatimento_nao_aproveitado": None, "valor_lancamento": None, "indicativo_lancamento": None, "indicador_valor": None, "valor_ajuste": None, "sequencial": "00000", "arquivo": None, "motivo_ocorrencia": [], "documento_numero": None, }, { "codigo_registro": "9", "codigo_ocorrencia": "00", "data_ocorrencia": None, "agencia_com_dv": None, "agencia_sem_dv": "0000", "cedente_com_dv": "000000000", "convenio": None, "nosso_numero": "00 00000", "tipo_cobranca": None, "tipo_cobranca_anterior": None, "natureza_recebimento": None, "carteira_variacao": None, "desconto": "0000000", "iof": None, "carteira": None, "comando": None, "data_liquidacao": None, "data_vencimento": "00000000", "valor_titulo": "0000000000000", "banco_recebedor": "00", "agencia_recebedora_com_dv": "", "especie_documento": None, "data_credito": "00000000", "valor_tarifa": "", "outras_despesas": None, "juros_desconto": None, "iof_desconto": None, "valor_abatimento": "0000000000000", "desconto_concedito": None, "valor_recebido": "", "juros_mora": "", "outros_recebimento": None, "abatimento_nao_aproveitado": None, "valor_lancamento": None, "indicativo_lancamento": None, "indicador_valor": None, "valor_ajuste": None, "sequencial": "000016", "arquivo": None, "motivo_ocorrencia": [], "documento_numero": None, }, ] # Verifica se a fatura está aberta, antes de fazer o retorno. self.assertEqual(self.invoice_ailos_1.state, "open") self.journal = self.env.ref( "l10n_br_account_payment_order.ailos_journal") with mock.patch( _provider_class + "._get_brcobranca_retorno", return_value=mocked_response, ): file_name = get_resource_path( "l10n_br_account_payment_brcobranca", "tests", "data", "CNAB240AILOS.RET", ) # Se for um codigo cnab de liquidação retorna as account.move criadas moves = self._import_file(file_name) self.assertEqual("Retorno CNAB - Banco COOP CENTRAL AILOS - Conta 373", moves.name) # I check that the invoice state is "Paid" self.assertEqual(self.invoice_ailos_1.state, "paid")
def test_valor_maior_4(self): mocked_response = [ { "codigo_registro": "1", "codigo_ocorrencia": "06", "data_ocorrencia": None, "agencia_com_dv": None, "agencia_sem_dv": "1234", "cedente_com_dv": "000003719", "convenio": None, # "nosso_numero": "00000000000000110", "nosso_numero": self.invoice_unicred_2_own_numbers[0], "tipo_cobranca": None, "tipo_cobranca_anterior": None, "natureza_recebimento": None, "carteira_variacao": None, "desconto": "0000000000000", "iof": None, "carteira": None, "comando": None, "data_liquidacao": None, "data_vencimento": "060720", "valor_titulo": "0000000030000", "banco_recebedor": "136", "agencia_recebedora_com_dv": "12343", "especie_documento": None, "data_credito": "060720", "valor_tarifa": "0000180", "outras_despesas": None, "juros_desconto": None, "iof_desconto": None, "valor_abatimento": "0000000000000", "desconto_concedito": None, "valor_recebido": "0000000031000", "juros_mora": "0000000001000", "outros_recebimento": None, "abatimento_nao_aproveitado": None, "valor_lancamento": None, "indicativo_lancamento": None, "indicador_valor": None, "valor_ajuste": None, "sequencial": "00000", "arquivo": None, "motivo_ocorrencia": [], "documento_numero": None, }, { "codigo_registro": "1", "codigo_ocorrencia": "06", "data_ocorrencia": None, "agencia_com_dv": None, "agencia_sem_dv": "1234", "cedente_com_dv": "000003719", "convenio": None, # "nosso_numero": "00000000000000129", "nosso_numero": self.invoice_unicred_2_own_numbers[1], "tipo_cobranca": None, "tipo_cobranca_anterior": None, "natureza_recebimento": None, "carteira_variacao": None, "desconto": "0000000000000", "iof": None, "carteira": None, "comando": None, "data_liquidacao": None, "data_vencimento": "060720", "valor_titulo": "0000000070000", "banco_recebedor": "136", "agencia_recebedora_com_dv": "12343", "especie_documento": None, "data_credito": "060720", "valor_tarifa": "0000180", "outras_despesas": None, "juros_desconto": None, "iof_desconto": None, "valor_abatimento": "0000000000000", "desconto_concedito": None, "valor_recebido": "0000000071000", "juros_mora": "0000000001000", "outros_recebimento": None, "abatimento_nao_aproveitado": None, "valor_lancamento": None, "indicativo_lancamento": None, "indicador_valor": None, "valor_ajuste": None, "sequencial": "00000", "arquivo": None, "motivo_ocorrencia": [], "documento_numero": None, }, { "codigo_registro": "9", "codigo_ocorrencia": "00", "data_ocorrencia": None, "agencia_com_dv": None, "agencia_sem_dv": "0000", "cedente_com_dv": "000000000", "convenio": None, "nosso_numero": "00 00000", "tipo_cobranca": None, "tipo_cobranca_anterior": None, "natureza_recebimento": None, "carteira_variacao": None, "desconto": "0000000", "iof": None, "carteira": None, "comando": None, "data_liquidacao": None, "data_vencimento": "000000", "valor_titulo": "0000000000000", "banco_recebedor": "00", "agencia_recebedora_com_dv": "", "especie_documento": None, "data_credito": "000000", "valor_tarifa": "", "outras_despesas": None, "juros_desconto": None, "iof_desconto": None, "valor_abatimento": "0000000000000", "desconto_concedito": None, "valor_recebido": "", "juros_mora": "", "outros_recebimento": None, "abatimento_nao_aproveitado": None, "valor_lancamento": None, "indicativo_lancamento": None, "indicador_valor": None, "valor_ajuste": None, "sequencial": "000016", "arquivo": None, "motivo_ocorrencia": [], "documento_numero": None, }, ] with mock.patch( _provider_class + "._get_brcobranca_retorno", return_value=mocked_response, ): file_name = get_resource_path( "l10n_br_account_payment_brcobranca", "tests", "data", "CNAB400UNICRED_valor_maior_4.RET", ) # Se for um codigo cnab de liquidação retorna as account.move criadas moves = self._import_file(file_name) self.assertEqual("Retorno CNAB - Banco UNICRED - Conta 371", moves.name) # I check that the invoice state is "Paid" self.assertEqual(self.invoice_unicred_2.state, "paid")
def setUpClass(cls): super().setUpClass() cls.company_a = cls.env.ref("base.main_company") tools.convert_file( cls.cr, "account", get_resource_path("account", "test", "account_minimal_test.xml"), {}, "init", False, "test", ) cls.account_move_obj = cls.env["account.move"] cls.account_move_line_obj = cls.env["account.move.line"] cls.cnab_log_obj = cls.env["l10n_br_cnab.return.log"] cls.account_id = cls.env.ref("account.a_recv") cls.bank_account = cls.env.ref("account.bnk") cls.import_wizard_obj = cls.env["credit.statement.import"] # Get Invoice for test cls.invoice_unicred_1 = cls.env.ref( "l10n_br_account_payment_order." "demo_invoice_payment_order_unicred_cnab400") cls.invoice_unicred_2 = cls.env.ref( "l10n_br_account_payment_brcobranca." "demo_invoice_brcobranca_unicred_cnab400") cls.invoice_ailos_1 = cls.env.ref( "l10n_br_account_payment_order." "demo_invoice_payment_order_ailos_cnab240") cls.journal = cls.env.ref( "l10n_br_account_payment_order.unicred_journal") # I validate invoice by creating on cls.invoice_unicred_1.action_invoice_open() cls.invoice_unicred_2.action_invoice_open() cls.invoice_ailos_1.action_invoice_open() # Para evitar erros nos testes de variação da Sequencia do # Nosso Numero/own_number quando se roda mais de uma vez ou # devido a diferença entre os comandos feitos pelo Travis cls.invoice_unicred_1_own_numbers = [] for line in cls.invoice_unicred_1.financial_move_line_ids: # No arquivo de retorno vem o NOSSO NUMERO + Digito Verificador cls.invoice_unicred_1_own_numbers.append(line.own_number + "0") cls.invoice_unicred_2_own_numbers = [] for line in cls.invoice_unicred_2.financial_move_line_ids: # No arquivo de retorno vem o NOSSO NUMERO + Digito Verificador cls.invoice_unicred_2_own_numbers.append(line.own_number + "0") cls.invoice_ailos_1_own_numbers = [] for line in cls.invoice_ailos_1.financial_move_line_ids: cls.invoice_ailos_1_own_numbers.append(line.own_number) payment_order = cls.env["account.payment.order"].search([ ("payment_mode_id", "=", cls.invoice_unicred_1.payment_mode_id.id) ]) # Open payment order payment_order.draft2open() # Verifica se deve testar com o mock if os.environ.get("CI"): # Generate file_name = get_resource_path( "l10n_br_account_payment_brcobranca", "tests", "data", "teste_remessa-unicred_400-1.REM", ) with open(file_name, "rb") as f: mocked_response = f.read() with mock.patch( _provider_class_pay_order + "._get_brcobranca_remessa", return_value=mocked_response, ): payment_order.open2generated() else: payment_order.open2generated() # Confirm Upload payment_order.generated2uploaded()