diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 00000000..84a2768d --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,160 @@ + true, + 'array_syntax' => ['syntax' => 'short'], + 'binary_operator_spaces' => [ + 'default' => 'single_space', + 'operators' => ['=>' => 'align_single_space_minimal'], + ], + 'blank_line_after_namespace' => true, + 'blank_line_after_opening_tag' => true, + 'blank_line_before_statement' => [ + 'statements' => ['return'], + ], + 'single_space_around_construct' => true, + 'cast_spaces' => true, + 'class_attributes_separation' => [ + 'elements' => [ + 'const' => 'none', + 'method' => 'one', + 'property' => 'one', + 'trait_import' => 'none', + ], + ], + 'class_definition' => [ + 'multi_line_extends_each_single_line' => true, + 'single_item_single_line' => true, + 'single_line' => true, + ], + 'concat_space' => [ + 'spacing' => 'one', + ], + 'constant_case' => ['case' => 'lower'], + 'declare_equal_normalize' => true, + 'elseif' => true, + 'encoding' => true, + 'full_opening_tag' => true, + 'fully_qualified_strict_types' => true, // added by Shift + 'function_declaration' => true, + 'type_declaration_spaces' => true, + 'general_phpdoc_tag_rename' => true, + 'heredoc_to_nowdoc' => true, + 'include' => true, + 'increment_style' => ['style' => 'post'], + 'indentation_type' => true, + 'linebreak_after_opening_tag' => true, + 'line_ending' => true, + 'lowercase_cast' => true, + 'lowercase_keywords' => true, + 'lowercase_static_reference' => true, // added from Symfony + 'magic_method_casing' => true, // added from Symfony + 'magic_constant_casing' => true, + 'method_argument_space' => [ + 'on_multiline' => 'ignore', + ], + 'multiline_whitespace_before_semicolons' => [ + 'strategy' => 'no_multi_line', + ], + 'native_function_casing' => true, +// 'no_alias_functions' => true, + 'no_extra_blank_lines' => [ + 'tokens' => [ + 'extra', + 'throw', + 'use', + ], + ], + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_closing_tag' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_mixed_echo_print' => [ + 'use' => 'echo', + ], + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_short_bool_cast' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_after_function_name' => true, + 'no_spaces_around_offset' => [ + 'positions' => ['inside', 'outside'], + ], + 'spaces_inside_parentheses' => true, + 'no_trailing_comma_in_singleline' => true, + 'no_trailing_whitespace' => true, + 'no_trailing_whitespace_in_comment' => true, + 'no_unneeded_control_parentheses' => [ + 'statements' => ['break', 'clone', 'continue', 'echo_print', 'return', 'switch_case', 'yield'], + ], +// 'no_unreachable_default_argument_value' => true, + 'no_useless_return' => true, + 'no_unused_imports' => true, + 'no_whitespace_before_comma_in_array' => true, + 'no_whitespace_in_blank_line' => true, + 'normalize_index_brace' => true, + 'not_operator_with_successor_space' => true, + 'object_operator_without_whitespace' => true, + 'ordered_imports' => ['sort_algorithm' => 'length', 'imports_order' => ['class', 'function', 'const']], +// 'psr_autoloading' => true, + 'phpdoc_indent' => true, + 'phpdoc_inline_tag_normalizer' => true, + 'phpdoc_no_access' => true, + 'phpdoc_no_package' => true, + 'phpdoc_no_useless_inheritdoc' => true, + 'phpdoc_scalar' => true, + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_summary' => false, + 'phpdoc_to_comment' => false, // override to preserve user preference + 'phpdoc_tag_type' => true, + 'phpdoc_trim' => true, + 'phpdoc_types' => true, + 'phpdoc_var_without_name' => true, +// 'self_accessor' => true, + 'short_scalar_cast' => true, + 'simplified_null_return' => false, // disabled as "risky" + 'single_blank_line_at_eof' => true, + 'blank_lines_before_namespace' => true, + 'single_class_element_per_statement' => [ + 'elements' => ['const', 'property'], + ], + 'single_import_per_statement' => true, + 'single_line_after_imports' => true, + 'single_line_comment_style' => [ + 'comment_types' => ['hash'], + ], + 'single_quote' => true, + 'space_after_semicolon' => true, + 'standardize_not_equals' => true, + 'switch_case_semicolon_to_colon' => true, + 'switch_case_space' => true, + 'ternary_operator_spaces' => true, + 'trailing_comma_in_multiline' => ['elements' => ['arrays']], + 'trim_array_spaces' => true, + 'unary_operator_spaces' => true, + 'visibility_required' => [ + 'elements' => ['method', 'property'], + ], + 'whitespace_after_comma_in_array' => true, +]; + +$finder = Finder::create() + ->in([ + __DIR__.'/src', + __DIR__.'/exemplos', + ]) + ->name('*.php') + ->notName('*.blade.php') + ->notName('*.js') + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +return (new Config()) + ->setFinder($finder) + ->setRules($rules) + ->setRiskyAllowed(false) + ->setUsingCache(false); \ No newline at end of file diff --git a/README.md b/README.md index 240525e9..7c11a3e6 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Ou, coloque em seu arquivo composer.json: ## Doações -**Estamos em busca de *doadores* e *patrocinadores* para ajudar a financiar parte do desenvolvimento deste pacote** +**Estamos em busca de *doadores* e *patrocinadores* para ajudar a financiar parte do desenvolvimento deste pacote** Este é um projeto totalmente *OpenSource*, para usa-lo, copia-lo e modifica-lo você não paga absolutamente nada. Porém para continuarmos a mante-lo de forma adequada é necessária alguma contribuição seja feita, seja auxiliando na codificação, na documentação, na realização de testes e identificação de falhas e BUGs. diff --git a/composer.json b/composer.json index 32a0cf2f..a4cf425f 100644 --- a/composer.json +++ b/composer.json @@ -14,19 +14,22 @@ } ], "require": { - "php": ">5.5.0", - "ext-intl": "*", - "ext-mbstring": "*", - "laravel/framework": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", + "php": ">5.5.0", + "ext-intl": "*", + "ext-mbstring": "*", + "laravel/framework": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", "neitanod/forceutf8": "^2.0", - "setasign/fpdf": "^1.8", - "ext-curl": "*", - "ext-json": "*", - "ext-openssl": "*" + "setasign/fpdf": "^1.8", + "ext-curl": "*", + "ext-json": "*", + "ext-openssl": "*", + "eduardokum/laravel-mail-auto-embed": "dev-master", + "chillerlan/php-qrcode": "^3.0|^4.0|^5.0" }, "require-dev": { "phpunit/phpunit": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", - "orchestra/testbench": "^3.0|^4.0|^5.0|^6.0|^7.0|^8.0|^9.0" + "orchestra/testbench": "^4.0|^5.0|^6.0|^7.0|^8.0|^9.0", + "friendsofphp/php-cs-fixer": "*" }, "autoload": { "psr-4": { @@ -40,5 +43,9 @@ }, "config": { "allow-plugins": true + }, + "scripts": { + "php-cs-fixer-check": "vendor/bin/php-cs-fixer fix --diff --verbose --dry-run", + "php-cs-fixer": "vendor/bin/php-cs-fixer fix --verbose" } -} \ No newline at end of file +} diff --git a/exemplos/arquivos/.gitignore b/exemplos/arquivos/.gitignore index 3f23f2eb..a2439574 100644 --- a/exemplos/arquivos/.gitignore +++ b/exemplos/arquivos/.gitignore @@ -1 +1,4 @@ -!*.ret \ No newline at end of file +* +!.gitignore +!*.ret +!template.blade.php \ No newline at end of file diff --git a/exemplos/arquivos/btg.ret b/exemplos/arquivos/btg.ret new file mode 100644 index 00000000..ee0e101b --- /dev/null +++ b/exemplos/arquivos/btg.ret @@ -0,0 +1,9 @@ +20800000 230306294000145006375766049310430530000100000001100983 EMPRESA CEDENTE BANCO BTG PACTUAL 21506202113034700001410301600 +20800001T01 020 2030306294000145006375766049310430530000100000001100983 EMPRESA CEDENTE 15062021 +2080001300001T 020000100000001100783 000000000000000002681196/1-1 150620210000000000800002080000100000695800000001285 09052843212000818 EMPRESA SACADO EXEMPLO 00000000000000000000000 0000000000 +2080001300002U 020000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000 15062021 000015062021000000000000000 000 +2080001300003T 060000100000001100783 000000000000000002681196/1-1 150620210000000000800002080000100000695800000001285 09052843212000818 EMPRESA SACADO EXEMPLO 00000000000000000000000 0000000000 +2080001300004U 060000000000000000000000000000000000000000800000000000000000000000000000800000000000000800000000000000000000000000000000 1506202115062021000015062021000000000080000 000 +20800015 000001000001000000000080000 000000000000000000000 00000000000000000000000000000000000000000000 00000000 +20899999 000001000001000000 + \ No newline at end of file diff --git a/exemplos/arquivos/santander_pix.ret b/exemplos/arquivos/santander_pix.ret new file mode 100644 index 00000000..00ef7a3d --- /dev/null +++ b/exemplos/arquivos/santander_pix.ret @@ -0,0 +1,4 @@ +02RETORNO0000000000000000011110000000009999999000000000000000000000000000000033000000000000000201016000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +10000000000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000002201016 10000000000000000000020101600000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000099000000000000002 +25 39a1178e-db6b-4407-bc7b-b674390acf5f id-da-transcao-pix 000003 +9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 \ No newline at end of file diff --git a/exemplos/arquivos/template.blade.php b/exemplos/arquivos/template.blade.php new file mode 100644 index 00000000..1517c254 --- /dev/null +++ b/exemplos/arquivos/template.blade.php @@ -0,0 +1,10 @@ + + + + + + + +

{{ $empresa }}

+

Olá cliente {{ $boleto['pagador']['nome'] }}

+ diff --git a/exemplos/autoload.php b/exemplos/autoload.php index 20d3a2c8..6da716ad 100644 --- a/exemplos/autoload.php +++ b/exemplos/autoload.php @@ -1,8 +1,9 @@ - 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '756.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 1, - 'agencia' => 1111, - 'convenio' => 123123, - 'conta' => 22222, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '756.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 1, + 'agencia' => 1111, + 'convenio' => 123123, + 'conta' => 22222, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/bancoob_remessa.php b/exemplos/bancoob_remessa.php index 5d9b0d42..6bbc5c1e 100644 --- a/exemplos/bancoob_remessa.php +++ b/exemplos/bancoob_remessa.php @@ -1,59 +1,52 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '756.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 1, - 'agencia' => 1111, - 'conta' => 22222, - 'convenio' => 123123, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '756.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 1, + 'agencia' => 1111, + 'conta' => 22222, + 'convenio' => 123123, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Bancoob( - [ - 'agencia' => 1111, - 'conta' => 22222, - 'carteira' => 1, - 'convenio' => 123123, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Bancoob([ + 'agencia' => 1111, + 'conta' => 22222, + 'carteira' => 1, + 'convenio' => 123123, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'bancoob.txt'); diff --git a/exemplos/bancoob_retorno.php b/exemplos/bancoob_retorno.php index 96bb0261..0f02d817 100644 --- a/exemplos/bancoob_retorno.php +++ b/exemplos/bancoob_retorno.php @@ -1,7 +1,8 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/banrisul_boleto.php b/exemplos/banrisul_boleto.php index b6736e72..731c31ea 100644 --- a/exemplos/banrisul_boleto.php +++ b/exemplos/banrisul_boleto.php @@ -1,48 +1,43 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Banrisul( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 1, - 'agencia' => 1111, - 'conta' => 22222, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Banrisul([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '041.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 1, + 'agencia' => 1111, + 'conta' => 22222, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/banrisul_remessa.php b/exemplos/banrisul_remessa.php index e26a8143..96cb6e24 100644 --- a/exemplos/banrisul_remessa.php +++ b/exemplos/banrisul_remessa.php @@ -1,59 +1,52 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Banrisul( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'diasBaixaAutomatica' => 2, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 1, - 'agencia' => 1111, - 'conta' => 22222, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Banrisul([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '041.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'diasBaixaAutomatica' => 2, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 1, + 'agencia' => 1111, + 'conta' => 22222, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Banrisul( - [ - 'agencia' => 1111, - 'conta' => 22222, - 'carteira' => 1, - 'codigoCliente' => 11112222222, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Banrisul([ + 'agencia' => 1111, + 'conta' => 22222, + 'carteira' => 1, + 'codigoCliente' => 11112222222, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'banrisul.txt'); diff --git a/exemplos/banrisul_retorno.php b/exemplos/banrisul_retorno.php index 8e353549..665db1df 100644 --- a/exemplos/banrisul_retorno.php +++ b/exemplos/banrisul_retorno.php @@ -1,7 +1,8 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/bb_boleto.php b/exemplos/bb_boleto.php index bf64ef60..5729a83d 100644 --- a/exemplos/bb_boleto.php +++ b/exemplos/bb_boleto.php @@ -1,48 +1,43 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 1111, - 'convenio' => 1234567, - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 11, + 'convenio' => 1234567, +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/bb_remessa.php b/exemplos/bb_remessa.php index 7ec108a4..3501488f 100644 --- a/exemplos/bb_remessa.php +++ b/exemplos/bb_remessa.php @@ -1,57 +1,50 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 11, - 'convenio' => 1234567, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 11, + 'convenio' => 1234567, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Bb( - [ - 'agencia' => 1111, - 'carteira' => 11, - 'conta' => 999999999, - 'convenio' => 1234567, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Bb([ + 'agencia' => 1111, + 'carteira' => 11, + 'conta' => 999999999, + 'convenio' => 1234567, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'bb.txt'); diff --git a/exemplos/bb_remessa_extendida.php b/exemplos/bb_remessa_extendida.php index 8627fc2b..13f6effc 100644 --- a/exemplos/bb_remessa_extendida.php +++ b/exemplos/bb_remessa_extendida.php @@ -1,58 +1,51 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 11, - 'convenio' => 1234567, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - 'chaveNfe' => '12345678901234567890123456789012345678901234' - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 11, + 'convenio' => 1234567, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'chaveNfe' => '12345678901234567890123456789012345678901234', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Bb( - [ - 'agencia' => 1111, - 'carteira' => 11, - 'conta' => 999999999, - 'convenio' => 1234567, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Bb([ + 'agencia' => 1111, + 'carteira' => 11, + 'conta' => 999999999, + 'convenio' => 1234567, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'bb_ext.txt'); diff --git a/exemplos/bb_retorno.php b/exemplos/bb_retorno.php index 25f10f38..a625bec3 100644 --- a/exemplos/bb_retorno.php +++ b/exemplos/bb_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/bnb_boleto.php b/exemplos/bnb_boleto.php index f19f525d..09c49fd7 100644 --- a/exemplos/bnb_boleto.php +++ b/exemplos/bnb_boleto.php @@ -1,49 +1,44 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bnb( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '004.png', - 'dataVencimento' => \Carbon\Carbon::createFromDate(2017, 04, 03), - 'valor' => 2338.28, - 'multa' => false, - 'juros' => false, - 'numero' => '0990887', - 'numeroDocumento' => '3456/1', - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '21', - 'agencia' => '0123', - 'conta' => '0000123', - 'contaDv' => '1', - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bnb([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '004.png', + 'dataVencimento' => Carbon\Carbon::createFromDate(2017, 04, 03), + 'valor' => 2338.28, + 'multa' => false, + 'juros' => false, + 'numero' => '0990887', + 'numeroDocumento' => '3456/1', + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '21', + 'agencia' => '0123', + 'conta' => '0000123', + 'contaDv' => '1', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/bnb_remessa.php b/exemplos/bnb_remessa.php index 7ece1b99..e1dd5b27 100644 --- a/exemplos/bnb_remessa.php +++ b/exemplos/bnb_remessa.php @@ -1,59 +1,52 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bnb( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '004.png', - 'dataVencimento' => \Carbon\Carbon::createFromDate(2017, 04, 03), - 'valor' => 2338.28, - 'multa' => 2.0, - 'juros' => false, - 'numero' => '0990887', - 'numeroDocumento' => '3456/1', - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '21', - 'agencia' => '0232', - 'conta' => '0000559', - 'contaDv' => '1', - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bnb([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '004.png', + 'dataVencimento' => Carbon\Carbon::createFromDate(2017, 04, 03), + 'valor' => 2338.28, + 'multa' => 2.0, + 'juros' => false, + 'numero' => '0990887', + 'numeroDocumento' => '3456/1', + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '21', + 'agencia' => '0232', + 'conta' => '0000559', + 'contaDv' => '1', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Bnb( - [ - 'agencia' => '0232', - 'conta' => '0000559', - 'contaDv' => '1', - 'carteira' => '21', - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Bnb([ + 'agencia' => '0232', + 'conta' => '0000559', + 'contaDv' => '1', + 'carteira' => '21', + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'bnb.txt'); diff --git a/exemplos/bnb_retorno.php b/exemplos/bnb_retorno.php index 2ccb4290..dea23404 100644 --- a/exemplos/bnb_retorno.php +++ b/exemplos/bnb_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/boleto_mail.php b/exemplos/boleto_mail.php new file mode 100644 index 00000000..98c29aec --- /dev/null +++ b/exemplos/boleto_mail.php @@ -0,0 +1,93 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '756.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 1, + 'agencia' => 1111, + 'convenio' => 123123, + 'conta' => 22222, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); + +$configsCasoNaoTenhaUmMailerConfiguradoNoSeuLaravel = [ + 'scheme' => 'smtp', + 'port' => 'porta', + 'host' => 'smtp.host.com', + 'username' => 'usuario', + 'password' => 'senha', + 'from' => ['address' => 'empresa@empresa.com', 'name' => 'Empresa'], +]; + +$mail = new VinicciusGuedes\LaravelCnab\Boleto\Mail($configsCasoNaoTenhaUmMailerConfiguradoNoSeuLaravel); + +$data = [ + 'empresa' => 'Nome da empresa', + 'logo' => 'full/path/logo.png', +]; + +// Array do boleto será automaticamente passado para view no formato de array, com a variável chamada $boleto +$mail->send( + ['arquivos/template.blade.php', $data], + 'assunto', + $boleto, + 'email@cliente.com' +); + +$mail->send( + ["

{{ \$empresa }}

Olá cliente {{ \$boleto['pagador']['nome'] }}

", $data], + 'assunto', + $boleto, + 'email@cliente.com' +); + +$mail->send( + 'Email simples sem template', + 'assunto', + $boleto, + 'email@cliente.com' +); + +$mail->setTo('email@cliente.com')->setBoleto($boleto)->send('Email simples sem template', 'assunto'); + +$aLoteBoletos = [ + 'cliente@cliente1.com.br' => $boleto, + 'cliente@cliente2.com.br' => $boleto, + 'cliente@cliente3.com.br' => $boleto, +]; + +$mail->sendLote( + 'Email simples sem template', + 'assunto', + $aLoteBoletos +); diff --git a/exemplos/boleto_protection.php b/exemplos/boleto_protection.php new file mode 100644 index 00000000..a016f39e --- /dev/null +++ b/exemplos/boleto_protection.php @@ -0,0 +1,46 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '756.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 1, + 'agencia' => 1111, + 'convenio' => 123123, + 'conta' => 22222, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +$pdf->SetProtection('123123'); +$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'bancoob.pdf'); diff --git a/exemplos/boletos.php b/exemplos/boletos.php index ed6d2964..06668a38 100644 --- a/exemplos/boletos.php +++ b/exemplos/boletos.php @@ -1,4 +1,5 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', 'documento' => '99.999.999/9999-99', - ] -); +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', 'documento' => '999.999.999-99', - ] -); +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '09', - 'agencia' => 1111, - 'conta' => 9999999, +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '09', + 'agencia' => 1111, + 'conta' => 9999999, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM' - ] -); + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/bradesco_remessa.php b/exemplos/bradesco_remessa.php index 0ed1de06..ec949647 100644 --- a/exemplos/bradesco_remessa.php +++ b/exemplos/bradesco_remessa.php @@ -1,61 +1,54 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'diasBaixaAutomatica' => 2, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '09', - 'agencia' => 1111, - 'conta' => 9999999, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'diasBaixaAutomatica' => 2, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '09', + 'agencia' => 1111, + 'conta' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Bradesco( - [ - 'idRemessa' => 1, - 'agencia' => 1111, - 'carteira' => '09', - 'conta' => 99999999, - 'contaDv' => 9, - 'codigoCliente' => '12345678901234567890', - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Bradesco([ + 'idRemessa' => 1, + 'agencia' => 1111, + 'carteira' => '09', + 'conta' => 99999999, + 'contaDv' => 9, + 'codigoCliente' => '12345678901234567890', + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'bradesco.txt'); diff --git a/exemplos/bradesco_remessa_extendida.php b/exemplos/bradesco_remessa_extendida.php index dde22d85..1b9fc8be 100644 --- a/exemplos/bradesco_remessa_extendida.php +++ b/exemplos/bradesco_remessa_extendida.php @@ -1,62 +1,55 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'diasBaixaAutomatica' => 2, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '09', - 'agencia' => 1111, - 'conta' => 9999999, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - 'chaveNfe' => '12345678901234567890123456789012345678901234' - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'diasBaixaAutomatica' => 2, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '09', + 'agencia' => 1111, + 'conta' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'chaveNfe' => '12345678901234567890123456789012345678901234', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Bradesco( - [ - 'idRemessa' => 1, - 'agencia' => 1111, - 'carteira' => '09', - 'conta' => 99999999, - 'contaDv' => 9, - 'codigoCliente' => '12345678901234567890', - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Bradesco([ + 'idRemessa' => 1, + 'agencia' => 1111, + 'carteira' => '09', + 'conta' => 99999999, + 'contaDv' => 9, + 'codigoCliente' => '12345678901234567890', + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'bradesco_ext.txt'); diff --git a/exemplos/bradesco_retorno.php b/exemplos/bradesco_retorno.php index 7dfa382e..24d3563d 100644 --- a/exemplos/bradesco_retorno.php +++ b/exemplos/bradesco_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/btg_boleto.php b/exemplos/btg_boleto.php new file mode 100644 index 00000000..05ca1128 --- /dev/null +++ b/exemplos/btg_boleto.php @@ -0,0 +1,45 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Btg([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '208.png', + 'dataVencimento' => new Carbon\Carbon('2021-12-11'), + 'valor' => 200, + 'multa' => false, + 'juros' => false, + 'numero' => 6380, + 'numeroDocumento' => 6380, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '1', + 'agencia' => '0050', + 'conta' => '000000000', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pix_qrcode' => '00020104141234567890123426660014BR.GOV.BCB.PIX014466756C616E6F32303139406578616D706C652E636F6D27300012BR.COM.OUTRO011001234567895204000053039865406123.455802BR5915NOMEDORECEBEDOR6008BRASILIA61087007490062530515RP12345678-201950300017BR.GOV.BCB.BRCODE01051.0.080450014BR.GOV.BCB.PIX0123PADRAO.URL.PIX/0123ABCD81390012BR.COM.OUTRO01190123.ABCD.3456.WXYZ6304EB76', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'btg.pdf'); diff --git a/exemplos/btg_remessa.php b/exemplos/btg_remessa.php new file mode 100644 index 00000000..28bd785d --- /dev/null +++ b/exemplos/btg_remessa.php @@ -0,0 +1,54 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Btg([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '208.png', + 'dataVencimento' => new Carbon\Carbon('2021-12-11'), + 'valor' => 200, + 'multa' => 10, + 'juros' => 10, + 'desconto' => 10, + 'numero' => 6380, + 'numeroDocumento' => 6380, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '1', + 'agencia' => '0050', + 'conta' => '000000000', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pix_qrcode' => '00020104141234567890123426660014BR.GOV.BCB.PIX014466756C616E6F32303139406578616D706C652E636F6D27300012BR.COM.OUTRO011001234567895204000053039865406123.455802BR5915NOMEDORECEBEDOR6008BRASILIA61087007490062530515RP12345678-201950300017BR.GOV.BCB.BRCODE01051.0.080450014BR.GOV.BCB.PIX0123PADRAO.URL.PIX/0123ABCD81390012BR.COM.OUTRO01190123.ABCD.3456.WXYZ6304EB76', +]); + +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab240\Cobranca\Banco\Btg([ + 'agencia' => '0050', + 'carteira' => '1', + 'conta' => '000000000', + 'codigoCliente' => '001100983001401000', + 'idremessa' => 1, + 'beneficiario' => $beneficiario, +]); +$remessa->addBoleto($boleto); + +echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'btg.txt'); diff --git a/exemplos/btg_retorno.php b/exemplos/btg_retorno.php new file mode 100644 index 00000000..c789a78c --- /dev/null +++ b/exemplos/btg_retorno.php @@ -0,0 +1,8 @@ +processar(); + +echo $retorno->getBancoNome(); +dd($retorno->getDetalhes()); diff --git a/exemplos/c6_boleto.php b/exemplos/c6_boleto.php new file mode 100644 index 00000000..890a1b48 --- /dev/null +++ b/exemplos/c6_boleto.php @@ -0,0 +1,45 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\C6([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '336.png', + 'dataVencimento' => new Carbon\Carbon('2020-03-27'), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 66, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '10', + 'agencia' => 1, + 'conta' => 242746330, + 'codigoCliente' => 1893, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'c6.pdf'); diff --git a/exemplos/c6_remessa.php b/exemplos/c6_remessa.php new file mode 100644 index 00000000..9d19fa38 --- /dev/null +++ b/exemplos/c6_remessa.php @@ -0,0 +1,54 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\C6([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '336.png', + 'dataVencimento' => new Carbon\Carbon('2020-03-27'), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 66, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '10', + 'agencia' => 1, + 'conta' => 123, + 'codigoCliente' => 1893, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); + +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\C6([ + 'idRemessa' => 1, + 'agencia' => 1111, + 'carteira' => '10', + 'conta' => 1234, + 'contaDv' => 5, + 'codigoCliente' => '1893', + 'beneficiario' => $beneficiario, +]); +$remessa->addBoleto($boleto); + +echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'c6.txt'); diff --git a/exemplos/cef_boleto.php b/exemplos/cef_boleto.php index 0df89c13..33387310 100644 --- a/exemplos/cef_boleto.php +++ b/exemplos/cef_boleto.php @@ -1,49 +1,44 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Caixa( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '104.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100.41, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'agencia' => 1111, - 'conta' => 123456, - 'carteira' => 'RG', - 'codigoCliente' => 999999, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Caixa([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '104.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100.41, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'agencia' => 1111, + 'conta' => 123456, + 'carteira' => 'RG', + 'codigoCliente' => 999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/cef_remessa.php b/exemplos/cef_remessa.php index a6d4f38f..044cc637 100644 --- a/exemplos/cef_remessa.php +++ b/exemplos/cef_remessa.php @@ -1,61 +1,54 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Caixa( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '104.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100.41, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'diasBaixaAutomatica' => 2, - 'beneficiario' => $beneficiario, - 'agencia' => 1111, - 'conta' => 123456, - 'carteira' => 'RG', - 'codigoCliente' => 999999, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Caixa([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '104.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100.41, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'diasBaixaAutomatica' => 2, + 'beneficiario' => $beneficiario, + 'agencia' => 1111, + 'conta' => 123456, + 'carteira' => 'RG', + 'codigoCliente' => 999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Caixa( - [ - 'agencia' => 1111, - 'idRemessa' => 1, - 'conta' => 123456, - 'carteira' => 'RG', - 'codigoCliente' => 999999, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Caixa([ + 'agencia' => 1111, + 'idRemessa' => 1, + 'conta' => 123456, + 'carteira' => 'RG', + 'codigoCliente' => 999999, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'cef.txt'); diff --git a/exemplos/cef_retorno.php b/exemplos/cef_retorno.php index e1ebbc2b..6e8f343b 100644 --- a/exemplos/cef_retorno.php +++ b/exemplos/cef_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/delbank_112_remessa.php b/exemplos/delbank_112_remessa.php index 7adc92f2..9883f2e3 100644 --- a/exemplos/delbank_112_remessa.php +++ b/exemplos/delbank_112_remessa.php @@ -2,61 +2,53 @@ require 'autoload.php'; -$beneficiario = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'FUNDO DELCRED MULTISSETORIAL', - 'endereco' => 'AV. RIO BRANCO, 186', - 'cep' => '49010-030', - 'uf' => 'SE', - 'cidade' => 'CENTRO', - 'documento' => '32.853.772/0001-62', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'FUNDO DELCRED MULTISSETORIAL', + 'endereco' => 'AV. RIO BRANCO, 186', + 'cep' => '49010-030', + 'uf' => 'SE', + 'cidade' => 'CENTRO', + 'documento' => '32.853.772/0001-62', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'PABLO KAWAN SANTOS TRINDADE', - 'endereco' => 'AV. RIO BRANCO, 186', - 'bairro' => 'CENTRO', - 'cep' => '49010-030', - 'uf' => 'SE', - 'cidade' => 'ARACAJU', - 'documento' => '000.000.000-00', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'PABLO KAWAN SANTOS TRINDADE', + 'endereco' => 'AV. RIO BRANCO, 186', + 'bairro' => 'CENTRO', + 'cep' => '49010-030', + 'uf' => 'SE', + 'cidade' => 'ARACAJU', + 'documento' => '000.000.000-00', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Delbank( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '435.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'dataDocumento' => new \Carbon\Carbon('2022-05-23'), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 0, - 'numero_controle' => 'SEUNUMERO', - 'diasBaixaAutomatica' => 5, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '112', - 'agencia' => 19, - 'conta' => 10138, - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3', 'instrucao 4', 'instrucao 5'], - 'especieDoc' => 'DM' - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Delbank([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '435.png', + 'dataVencimento' => new Carbon\Carbon(), + 'dataDocumento' => new Carbon\Carbon('2022-05-23'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 0, + 'numero_controle' => 'SEUNUMERO', + 'diasBaixaAutomatica' => 5, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '112', + 'agencia' => 19, + 'conta' => 10138, + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3', 'instrucao 4', 'instrucao 5'], + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Delbank( - [ - 'idRemessa' => 1, - 'agencia' => 19, - 'carteira' => '112', - 'conta' => 10138, - 'codigoCliente' => '10138DELCREDFUNDOLTD', - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Delbank([ + 'idRemessa' => 1, + 'agencia' => 19, + 'carteira' => '112', + 'conta' => 10138, + 'codigoCliente' => '10138DELCREDFUNDOLTD', + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); -echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'delbank.112.txt'); \ No newline at end of file +echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'delbank.112.txt'); diff --git a/exemplos/delbank_121_remessa.php b/exemplos/delbank_121_remessa.php index 0dcec995..af499d61 100644 --- a/exemplos/delbank_121_remessa.php +++ b/exemplos/delbank_121_remessa.php @@ -2,60 +2,52 @@ require 'autoload.php'; -$beneficiario = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'FUNDO DELCRED MULTISSETORIAL', - 'endereco' => 'AV. RIO BRANCO, 186', - 'cep' => '49010-030', - 'uf' => 'SE', - 'cidade' => 'CENTRO', - 'documento' => '32.853.772/0001-62', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'FUNDO DELCRED MULTISSETORIAL', + 'endereco' => 'AV. RIO BRANCO, 186', + 'cep' => '49010-030', + 'uf' => 'SE', + 'cidade' => 'CENTRO', + 'documento' => '32.853.772/0001-62', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'PABLO KAWAN SANTOS TRINDADE', - 'endereco' => 'AV. RIO BRANCO, 186', - 'bairro' => 'CENTRO', - 'cep' => '49010-030', - 'uf' => 'SE', - 'cidade' => 'ARACAJU', - 'documento' => '000.000.000-00', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'PABLO KAWAN SANTOS TRINDADE', + 'endereco' => 'AV. RIO BRANCO, 186', + 'bairro' => 'CENTRO', + 'cep' => '49010-030', + 'uf' => 'SE', + 'cidade' => 'ARACAJU', + 'documento' => '000.000.000-00', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Delbank( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '435.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'dataDocumento' => new \Carbon\Carbon('2022-05-23'), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numero_controle' => 'SEUNUMERO', - 'diasBaixaAutomatica' => 5, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '121', - 'agencia' => 19, - 'conta' => 10138, - 'especieDoc' => 'DM' - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Delbank([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '435.png', + 'dataVencimento' => new Carbon\Carbon(), + 'dataDocumento' => new Carbon\Carbon('2022-05-23'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numero_controle' => 'SEUNUMERO', + 'diasBaixaAutomatica' => 5, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '121', + 'agencia' => 19, + 'conta' => 10138, + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Delbank( - [ - 'idRemessa' => 1, - 'agencia' => 19, - 'carteira' => '121', - 'conta' => 10138, - 'codigoCliente' => '10138DELCREDFUNDOLTD', - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Delbank([ + 'idRemessa' => 1, + 'agencia' => 19, + 'carteira' => '121', + 'conta' => 10138, + 'codigoCliente' => '10138DELCREDFUNDOLTD', + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); -echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'delbank.121.txt'); \ No newline at end of file +echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'delbank.121.txt'); diff --git a/exemplos/delbank_retorno.php b/exemplos/delbank_retorno.php index fb4fc89a..335b2666 100644 --- a/exemplos/delbank_retorno.php +++ b/exemplos/delbank_retorno.php @@ -1,7 +1,8 @@ processar(); echo $retorno->getBancoNome(); -dd($retorno->getDetalhes()); \ No newline at end of file +dd($retorno->getDetalhes()); diff --git a/exemplos/fibra_boleto.php b/exemplos/fibra_boleto.php index b6f48ad1..f1ce1d22 100644 --- a/exemplos/fibra_boleto.php +++ b/exemplos/fibra_boleto.php @@ -1,55 +1,47 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Fibra( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '224.png', - 'dataVencimento' => new \Carbon\Carbon('2023-01-04'), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'range' => 0, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'modalidadeCarteira' => 'D', - 'carteira' => 112, - 'agencia' => '0001', - 'codigoCliente' => '12345', - 'conta' => '1234567', - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'N', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Fibra([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '224.png', + 'dataVencimento' => new Carbon\Carbon('2023-01-04'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'modalidadeCarteira' => 'D', + 'carteira' => 112, + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234567', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/fibra_remessa.php b/exemplos/fibra_remessa.php index 01ae14ba..ddf75ede 100644 --- a/exemplos/fibra_remessa.php +++ b/exemplos/fibra_remessa.php @@ -1,62 +1,55 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Fibra( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '224.png', - 'dataVencimento' => new \Carbon\Carbon('2023-01-04'), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'range' => 0, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'modalidadeCarteira' => 'D', - 'carteira' => 112, - 'agencia' => '0001', - 'codigoCliente' => '12345', - 'conta' => '1234567', - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'N', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Fibra([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '224.png', + 'dataVencimento' => new Carbon\Carbon('2023-01-04'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'modalidadeCarteira' => 'D', + 'carteira' => 112, + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234567', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Fibra( - [ - 'agencia' => '0001', - 'conta' => '1234567', - 'contaDv' => 9, - 'carteira' => 112, - 'beneficiario' => $beneficiario, - 'codigoCliente' => '12345', - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Fibra([ + 'agencia' => '0001', + 'conta' => '1234567', + 'contaDv' => 9, + 'carteira' => 112, + 'beneficiario' => $beneficiario, + 'codigoCliente' => '12345', +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'fibra.txt'); diff --git a/exemplos/fibra_retorno.php b/exemplos/fibra_retorno.php index c30f8a39..95e688d0 100644 --- a/exemplos/fibra_retorno.php +++ b/exemplos/fibra_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/hsbc_boleto.php b/exemplos/hsbc_boleto.php index 807ab8a5..6d155ec4 100644 --- a/exemplos/hsbc_boleto.php +++ b/exemplos/hsbc_boleto.php @@ -1,50 +1,45 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Hsbc( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '399.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 'CSB', - 'range' => 12345, - 'agencia' => 1111, - 'conta' => 999999, - 'contaDv' => 9, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Hsbc([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '399.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 'CSB', + 'range' => 12345, + 'agencia' => 1111, + 'conta' => 999999, + 'contaDv' => 9, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/hsbc_remessa.php b/exemplos/hsbc_remessa.php index 477357f0..32991831 100644 --- a/exemplos/hsbc_remessa.php +++ b/exemplos/hsbc_remessa.php @@ -1,60 +1,53 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Hsbc( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '399.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 'CSB', - 'range' => 12345, - 'agencia' => 1111, - 'conta' => 999999, - 'contaDv' => 9, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Hsbc([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '399.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 'CSB', + 'range' => 12345, + 'agencia' => 1111, + 'conta' => 999999, + 'contaDv' => 9, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Hsbc( - [ - 'agencia' => 1111, - 'carteira' => 'CSB', - 'conta' => 999999, - 'contaDv' => 9, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Hsbc([ + 'agencia' => 1111, + 'carteira' => 'CSB', + 'conta' => 999999, + 'contaDv' => 9, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'hsbc.txt'); diff --git a/exemplos/hsbc_retorno.php b/exemplos/hsbc_retorno.php index 875c0886..3cfc0e4f 100644 --- a/exemplos/hsbc_retorno.php +++ b/exemplos/hsbc_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/inter_boleto.php b/exemplos/inter_boleto.php index 270c9967..f64c75af 100644 --- a/exemplos/inter_boleto.php +++ b/exemplos/inter_boleto.php @@ -1,48 +1,43 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', 'documento' => '99.999.999/9999-99', - ] -); +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', 'documento' => '999.999.999-99', - ] -); +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '077.png', - 'dataVencimento' => (new \Carbon\Carbon())->addDays(), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'nossoNumero' => '12345678901', - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'conta' => '123456789', - 'operacao' => '1234567', - 'aceite' => 'S', - 'especieDoc' => 'DM' - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '077.png', + 'dataVencimento' => (new Carbon\Carbon())->addDays(), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'nossoNumero' => '000', + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'conta' => '123456789', + 'operacao' => '1234567', + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); -$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'inter.pdf'); \ No newline at end of file +$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'inter.pdf'); diff --git a/exemplos/inter_boleto_api.php b/exemplos/inter_boleto_api.php index 438a0590..832fafa6 100644 --- a/exemplos/inter_boleto_api.php +++ b/exemplos/inter_boleto_api.php @@ -1,46 +1,41 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '077.png', - 'dataVencimento' => (new \Carbon\Carbon())->addDays(), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'conta' => '123456789', - 'operacao' => '1234567', - 'aceite' => 'S', - 'especieDoc' => 'DM' - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '077.png', + 'dataVencimento' => (new Carbon\Carbon())->addDays(), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'conta' => '123456789', + 'operacao' => '1234567', + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $api = new VinicciusGuedes\LaravelCnab\Api\Banco\Inter([ 'conta' => '123456789', diff --git a/exemplos/inter_boleto_lista_api.php b/exemplos/inter_boleto_lista_api.php index e1702499..5bb34e44 100644 --- a/exemplos/inter_boleto_lista_api.php +++ b/exemplos/inter_boleto_lista_api.php @@ -1,19 +1,15 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); $api = new VinicciusGuedes\LaravelCnab\Api\Banco\Inter([ 'conta' => '123456789', @@ -27,4 +23,3 @@ //$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); //$pdf->addBoletos($retorno); //$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'inter_lista_v2.pdf'); - diff --git a/exemplos/inter_remessa.php b/exemplos/inter_remessa.php index 0dcf360d..aa8213b3 100644 --- a/exemplos/inter_remessa.php +++ b/exemplos/inter_remessa.php @@ -1,59 +1,49 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '077.png', - 'dataVencimento' => (new \Carbon\Carbon())->addDays(), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'conta' => '123456789', - 'operacao' => '1234567', - 'aceite' => 'S', - 'especieDoc' => 'DM' - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '077.png', + 'dataVencimento' => (new Carbon\Carbon())->addDays(), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'conta' => '123456789', + 'operacao' => '1234567', + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Inter( - [ - 'idRemessa' => 1, - 'agencia' => '0001', - 'conta' => '123456789', - 'carteira' => 112, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Inter([ + 'idRemessa' => 1, + 'agencia' => '0001', + 'conta' => '123456789', + 'carteira' => 112, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'inter.txt', true); diff --git a/exemplos/inter_retorno.php b/exemplos/inter_retorno.php index e58e0f5e..e9a9083a 100644 --- a/exemplos/inter_retorno.php +++ b/exemplos/inter_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/interv2_boleto_lista_api.php b/exemplos/interv2_boleto_lista_api.php index 94400ba1..497c4b05 100644 --- a/exemplos/interv2_boleto_lista_api.php +++ b/exemplos/interv2_boleto_lista_api.php @@ -1,25 +1,21 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); $api = new VinicciusGuedes\LaravelCnab\Api\Banco\Inter([ - 'versao' => 2, - 'beneficiario' => $beneficiario, - 'client_id' => 'id', - 'client_secret' => '', + 'versao' => 2, + 'beneficiario' => $beneficiario, + 'client_id' => 'id', + 'client_secret' => '', 'certificado' => realpath(__DIR__ . '/certs/') . DIRECTORY_SEPARATOR . 'cert.crt', 'certificadoChave' => realpath(__DIR__ . '/certs/') . DIRECTORY_SEPARATOR . 'key.key', ]); diff --git a/exemplos/itau_boleto.php b/exemplos/itau_boleto.php index dd251868..b8bdfd19 100644 --- a/exemplos/itau_boleto.php +++ b/exemplos/itau_boleto.php @@ -1,48 +1,43 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 112, - 'agencia' => 1111, - 'conta' => 99999, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 112, + 'agencia' => 1111, + 'conta' => 99999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/itau_remessa.php b/exemplos/itau_remessa.php index cfa8f1b3..70a720e6 100644 --- a/exemplos/itau_remessa.php +++ b/exemplos/itau_remessa.php @@ -1,59 +1,52 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'diasBaixaAutomatica' => 2, - 'carteira' => 112, - 'agencia' => 1111, - 'conta' => 99999, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'diasBaixaAutomatica' => 2, + 'carteira' => 112, + 'agencia' => 1111, + 'conta' => 99999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Itau( - [ - 'agencia' => 1111, - 'conta' => 99999, - 'contaDv' => 9, - 'carteira' => 112, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Itau([ + 'agencia' => 1111, + 'conta' => 99999, + 'contaDv' => 9, + 'carteira' => 112, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'itau.txt'); diff --git a/exemplos/itau_retorno.php b/exemplos/itau_retorno.php index 855da24a..8cfa3af9 100644 --- a/exemplos/itau_retorno.php +++ b/exemplos/itau_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/ourinvest_boleto.php b/exemplos/ourinvest_boleto.php new file mode 100644 index 00000000..4c3e051b --- /dev/null +++ b/exemplos/ourinvest_boleto.php @@ -0,0 +1,44 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Ourinvest([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '712.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 2, + 'numeroDocumento' => 2, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '19', + 'agencia' => 0001, + 'conta' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'ourinvest.pdf'); diff --git a/exemplos/ourinvest_remessa.php b/exemplos/ourinvest_remessa.php new file mode 100644 index 00000000..7f99d051 --- /dev/null +++ b/exemplos/ourinvest_remessa.php @@ -0,0 +1,54 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', + 'email' => 'email@dominio.com', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Ourinvest([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '712.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 2, + 'numeroDocumento' => 2, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '19', + 'agencia' => 0001, + 'conta' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'chaveNfe' => '12345678901234567890123456789012345678901234', +]); + +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Ourinvest([ + 'idRemessa' => 1, + 'agencia' => 1111, + 'carteira' => '19', + 'conta' => 1234567, + 'contaDv' => 9, + 'beneficiario' => $beneficiario, +]); +$remessa->addBoleto($boleto); + +$file = $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'ourinvest.txt'); diff --git a/exemplos/ourinvest_retorno.php b/exemplos/ourinvest_retorno.php new file mode 100644 index 00000000..0f3b234b --- /dev/null +++ b/exemplos/ourinvest_retorno.php @@ -0,0 +1,8 @@ +processar(); + +echo $retorno->getBancoNome(); +dd($retorno->getDetalhes()); diff --git a/exemplos/pine_boleto.php b/exemplos/pine_boleto.php index cf5a81b9..74481747 100644 --- a/exemplos/pine_boleto.php +++ b/exemplos/pine_boleto.php @@ -1,55 +1,46 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '643.png', - 'dataVencimento' => new \Carbon\Carbon('2023-03-09'), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'range' => 0, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '112', - 'agencia' => '0001', - 'codigoCliente' => '12345', - 'conta' => '1234', - 'modalidadeCarteira' => '1', - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'N', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '643.png', + 'dataVencimento' => new Carbon\Carbon('2023-03-09'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '112', + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234', + 'modalidadeCarteira' => '1', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/pine_remessa.php b/exemplos/pine_remessa.php index a7ea7b03..805bfb7c 100644 --- a/exemplos/pine_remessa.php +++ b/exemplos/pine_remessa.php @@ -1,62 +1,55 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '643.png', - 'dataVencimento' => new \Carbon\Carbon('2023-03-09'), - 'valor' => 10, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'range' => 0, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '112', - 'agencia' => '0001', - 'codigoCliente' => '12345', - 'conta' => '1234', - 'modalidadeCarteira' => '1', - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'N', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '643.png', + 'dataVencimento' => new Carbon\Carbon('2023-03-09'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '112', + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234', + 'modalidadeCarteira' => '1', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Pine( - [ - 'agencia' => '0001', - 'conta' => '1234', - 'contaDv' => 9, - 'carteira' => 112, - 'beneficiario' => $beneficiario, - 'codigoCliente' => '1234', - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Pine([ + 'agencia' => '0001', + 'conta' => '1234', + 'contaDv' => 9, + 'carteira' => 112, + 'beneficiario' => $beneficiario, + 'codigoCliente' => '1234', +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'pine.txt'); diff --git a/exemplos/pine_retorno.php b/exemplos/pine_retorno.php index 2e2de5f0..0c1f2dc3 100644 --- a/exemplos/pine_retorno.php +++ b/exemplos/pine_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/pix_boleto_qrcode_copia_cola.php b/exemplos/pix_boleto_qrcode_copia_cola.php new file mode 100644 index 00000000..7a786005 --- /dev/null +++ b/exemplos/pix_boleto_qrcode_copia_cola.php @@ -0,0 +1,45 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 112, + 'agencia' => 1111, + 'conta' => 99999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pix_qrcode' => '00020104141234567890123426660014BR.GOV.BCB.PIX014466756C616E6F32303139406578616D706C652E636F6D27300012BR.COM.OUTRO011001234567895204000053039865406123.455802BR5915NOMEDORECEBEDOR6008BRASILIA61087007490062530515RP12345678-201950300017BR.GOV.BCB.BRCODE01051.0.080450014BR.GOV.BCB.PIX0123PADRAO.URL.PIX/0123ABCD81390012BR.COM.OUTRO01190123.ABCD.3456.WXYZ6304EB76', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +echo $pdf->gerarBoleto(); diff --git a/exemplos/pix_boleto_qrcode_copia_cola_localizacao.php b/exemplos/pix_boleto_qrcode_copia_cola_localizacao.php new file mode 100644 index 00000000..53b79705 --- /dev/null +++ b/exemplos/pix_boleto_qrcode_copia_cola_localizacao.php @@ -0,0 +1,48 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 112, + 'agencia' => 1111, + 'conta' => 99999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pix_qrcode' => '00020104141234567890123426660014BR.GOV.BCB.PIX014466756C616E6F32303139406578616D706C652E636F6D27300012BR.COM.OUTRO011001234567895204000053039865406123.455802BR5915NOMEDORECEBEDOR6008BRASILIA61087007490062530515RP12345678-201950300017BR.GOV.BCB.BRCODE01051.0.080450014BR.GOV.BCB.PIX0123PADRAO.URL.PIX/0123ABCD81390012BR.COM.OUTRO01190123.ABCD.3456.WXYZ6304EB76', + 'qr_code_style' => VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau::QRCODE_ESTILO_PONTO, +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +$pdf->setLocalizacaoPix(VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf::PIX_INSTRUCAO); +//$pdf->setLocalizacaoPix(VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf::PIX_COD_BARRAS); +echo $pdf->gerarBoleto(); diff --git a/exemplos/pix_boleto_qrcode_img.php b/exemplos/pix_boleto_qrcode_img.php new file mode 100644 index 00000000..e1f7a75f --- /dev/null +++ b/exemplos/pix_boleto_qrcode_img.php @@ -0,0 +1,45 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 112, + 'agencia' => 1111, + 'conta' => 99999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pix_qrcode' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR0AAAEdAQMAAAALpCE4AAAABlBMVEX///8AAABVwtN+AAADYElEQVRoge2Zy7GrQAxERbFgSQiTiUmMKqhyYiYTQmDJgkKvu8XHdgR6tzwLrvGcu5BHn5bG7Ld+68+v1t13q+e1c+djs+aFr1drn9jxMS+EP492M3+BtIf1+NRuxTp/zrGbFXr6yq3VCOF1Xh98VIB8Tw8Nc+O+lWbHvk9L7Wu11P8BFL6jw4BT0cSGp5Qboj9ZX5pXOxaGhDfTYgUW119Olw1iBF9e9PH4CvNkUCzE7Y4wpk3YoXXVYt8rFyRLGAiTj0WJE6eEVcGwi8wImRWrlmFmDMCVEA2KYOuWAY/rWBJCNSOYWyhQMKe3xgkxEFSvskIsUNPSM13iWCo6/wRjtQ88L8QC1eGzciY+wVi+UiEUv36ChBBs4tnMsA7+dKR4x4N59PoJUkKmXMPUU5yuJGmzMoybtyqVEbJK5wCyOVypp47s+Wp5IYjdnU71OOw0FS2dzW1dQoiph3G7Kkkq9cg6Jk5qhbRQVKme+Yc9BurVIROwd0dwRkh5XpWVyd6ZQlFjw58yQyYHcqr0YdYBqVdCoWXLsWSGEKj0J2pG6QJkSkGj3U6XEAqJ6xQ0G2sTrLMQZv4mkDNC0Rf5ame3wZAopkx0OV1CCJbgRDi+ONIlPYtt0hnGWSFEcFjHFrqhddTr1GQjM1FiCIfh/nTpghgdCVLj96Z68kFs+0HCsIHWGSO41ilBQt5VKh2ELWN/p5ypPC8V7CIrTw2pJ22YZkIcMAYUwZcSywixTXKJF751riHSyBr79I/+LiM0LSG9ZrVJaKYRy2fPlxayISqrRqE0h5MBNR8aHSWGJHE3k+yN/+HZOJXYNadLCfXR8TNu9Vp4LN5IFeyZIc3kQqrH+MLVbewSZreETAdxAMACJeHIZtqVQjVEstOfUkLUBTBR37o8SxZzw85knxGKIxiLHdKL07n2GBjdbVJGaKBKr1lUSeJV2pejxvJWyvJBrYbPgxSvKWylgs9rgTEtFORxRXFo36U+a+znFUAqKG5x2RfF6CjkuzI++6cxLzTGDdeqay5aRzkW6vEWyBkhSS9kHc5w1VEfXd2H02WFNKyj7OWr9Feos7tNSgoxjLuFZ8N92URhdimxlJD8qY5pi6b/xxiaF/4vs7xQuE18q8lFXFtoYPQmHtJBv/Vbf3r9A2A129WHoHA0AAAAAElFTkSuQmCC', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +echo $pdf->gerarBoleto(); diff --git a/exemplos/pix_boleto_qrcode_img_base64.php b/exemplos/pix_boleto_qrcode_img_base64.php new file mode 100644 index 00000000..af6aae95 --- /dev/null +++ b/exemplos/pix_boleto_qrcode_img_base64.php @@ -0,0 +1,45 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 112, + 'agencia' => 1111, + 'conta' => 99999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pix_qrcode' => 'iVBORw0KGgoAAAANSUhEUgAAAR0AAAEdAQMAAAALpCE4AAAABlBMVEX///8AAABVwtN+AAADYElEQVRoge2Zy7GrQAxERbFgSQiTiUmMKqhyYiYTQmDJgkKvu8XHdgR6tzwLrvGcu5BHn5bG7Ld+68+v1t13q+e1c+djs+aFr1drn9jxMS+EP492M3+BtIf1+NRuxTp/zrGbFXr6yq3VCOF1Xh98VIB8Tw8Nc+O+lWbHvk9L7Wu11P8BFL6jw4BT0cSGp5Qboj9ZX5pXOxaGhDfTYgUW119Olw1iBF9e9PH4CvNkUCzE7Y4wpk3YoXXVYt8rFyRLGAiTj0WJE6eEVcGwi8wImRWrlmFmDMCVEA2KYOuWAY/rWBJCNSOYWyhQMKe3xgkxEFSvskIsUNPSM13iWCo6/wRjtQ88L8QC1eGzciY+wVi+UiEUv36ChBBs4tnMsA7+dKR4x4N59PoJUkKmXMPUU5yuJGmzMoybtyqVEbJK5wCyOVypp47s+Wp5IYjdnU71OOw0FS2dzW1dQoiph3G7Kkkq9cg6Jk5qhbRQVKme+Yc9BurVIROwd0dwRkh5XpWVyd6ZQlFjw58yQyYHcqr0YdYBqVdCoWXLsWSGEKj0J2pG6QJkSkGj3U6XEAqJ6xQ0G2sTrLMQZv4mkDNC0Rf5ame3wZAopkx0OV1CCJbgRDi+ONIlPYtt0hnGWSFEcFjHFrqhddTr1GQjM1FiCIfh/nTpghgdCVLj96Z68kFs+0HCsIHWGSO41ilBQt5VKh2ELWN/p5ypPC8V7CIrTw2pJ22YZkIcMAYUwZcSywixTXKJF751riHSyBr79I/+LiM0LSG9ZrVJaKYRy2fPlxayISqrRqE0h5MBNR8aHSWGJHE3k+yN/+HZOJXYNadLCfXR8TNu9Vp4LN5IFeyZIc3kQqrH+MLVbewSZreETAdxAMACJeHIZtqVQjVEstOfUkLUBTBR37o8SxZzw85knxGKIxiLHdKL07n2GBjdbVJGaKBKr1lUSeJV2pejxvJWyvJBrYbPgxSvKWylgs9rgTEtFORxRXFo36U+a+znFUAqKG5x2RfF6CjkuzI++6cxLzTGDdeqay5aRzkW6vEWyBkhSS9kHc5w1VEfXd2H02WFNKyj7OWr9Feos7tNSgoxjLuFZ8N92URhdimxlJD8qY5pi6b/xxiaF/4vs7xQuE18q8lFXFtoYPQmHtJBv/Vbf3r9A2A129WHoHA0AAAAAElFTkSuQmCC', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +echo $pdf->gerarBoleto(); diff --git a/exemplos/pix_boleto_qrcode_img_data.php b/exemplos/pix_boleto_qrcode_img_data.php new file mode 100644 index 00000000..e1f7a75f --- /dev/null +++ b/exemplos/pix_boleto_qrcode_img_data.php @@ -0,0 +1,45 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 112, + 'agencia' => 1111, + 'conta' => 99999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'pix_qrcode' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAR0AAAEdAQMAAAALpCE4AAAABlBMVEX///8AAABVwtN+AAADYElEQVRoge2Zy7GrQAxERbFgSQiTiUmMKqhyYiYTQmDJgkKvu8XHdgR6tzwLrvGcu5BHn5bG7Ld+68+v1t13q+e1c+djs+aFr1drn9jxMS+EP492M3+BtIf1+NRuxTp/zrGbFXr6yq3VCOF1Xh98VIB8Tw8Nc+O+lWbHvk9L7Wu11P8BFL6jw4BT0cSGp5Qboj9ZX5pXOxaGhDfTYgUW119Olw1iBF9e9PH4CvNkUCzE7Y4wpk3YoXXVYt8rFyRLGAiTj0WJE6eEVcGwi8wImRWrlmFmDMCVEA2KYOuWAY/rWBJCNSOYWyhQMKe3xgkxEFSvskIsUNPSM13iWCo6/wRjtQ88L8QC1eGzciY+wVi+UiEUv36ChBBs4tnMsA7+dKR4x4N59PoJUkKmXMPUU5yuJGmzMoybtyqVEbJK5wCyOVypp47s+Wp5IYjdnU71OOw0FS2dzW1dQoiph3G7Kkkq9cg6Jk5qhbRQVKme+Yc9BurVIROwd0dwRkh5XpWVyd6ZQlFjw58yQyYHcqr0YdYBqVdCoWXLsWSGEKj0J2pG6QJkSkGj3U6XEAqJ6xQ0G2sTrLMQZv4mkDNC0Rf5ame3wZAopkx0OV1CCJbgRDi+ONIlPYtt0hnGWSFEcFjHFrqhddTr1GQjM1FiCIfh/nTpghgdCVLj96Z68kFs+0HCsIHWGSO41ilBQt5VKh2ELWN/p5ypPC8V7CIrTw2pJ22YZkIcMAYUwZcSywixTXKJF751riHSyBr79I/+LiM0LSG9ZrVJaKYRy2fPlxayISqrRqE0h5MBNR8aHSWGJHE3k+yN/+HZOJXYNadLCfXR8TNu9Vp4LN5IFeyZIc3kQqrH+MLVbewSZreETAdxAMACJeHIZtqVQjVEstOfUkLUBTBR37o8SxZzw85knxGKIxiLHdKL07n2GBjdbVJGaKBKr1lUSeJV2pejxvJWyvJBrYbPgxSvKWylgs9rgTEtFORxRXFo36U+a+znFUAqKG5x2RfF6CjkuzI++6cxLzTGDdeqay5aRzkW6vEWyBkhSS9kHc5w1VEfXd2H02WFNKyj7OWr9Feos7tNSgoxjLuFZ8N92URhdimxlJD8qY5pi6b/xxiaF/4vs7xQuE18q8lFXFtoYPQmHtJBv/Vbf3r9A2A129WHoHA0AAAAAElFTkSuQmCC', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +echo $pdf->gerarBoleto(); diff --git a/exemplos/pix_retorno.php b/exemplos/pix_retorno.php new file mode 100644 index 00000000..cf0d01f3 --- /dev/null +++ b/exemplos/pix_retorno.php @@ -0,0 +1,13 @@ +processar(); + +echo $retorno->getBancoNome(); +dd([ + 'ID' => $retorno->getDetalhe(1)->getId(), + 'LOCATION' => $retorno->getDetalhe(1)->getLocation(), + 'COPIA_E_COLA_VEIO_NO_RETORNO' => $retorno->getDetalhe(1)->getPixQrCode(), + 'COPIA_E_COLA_GERADO_PELA_CLASSE' => $retorno->getDetalhe(1)->gerarPixCopiaECola('NOMEEMPRESA', 'SÃO PAULO', true), +]); diff --git a/exemplos/remessas.php b/exemplos/remessas.php index f8c1081f..86c3b25f 100644 --- a/exemplos/remessas.php +++ b/exemplos/remessas.php @@ -1,4 +1,5 @@ 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Rendimento([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '633.png', + 'dataVencimento' => new Carbon\Carbon('2023-01-20'), + 'valor' => 12750, + 'multa' => false, + 'juros' => false, + 'numero' => 96928179, + 'numeroDocumento' => 96928179, + 'range' => 0, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '121', + 'agencia' => '0001', + 'codigoCliente' => '5447390', + 'conta' => '1234', + 'modalidadeCarteira' => '6', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', +]); + +$pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); +$pdf->addBoleto($boleto); +$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'rendimento.pdf'); diff --git a/exemplos/rendimento_remessa.php b/exemplos/rendimento_remessa.php new file mode 100644 index 00000000..99f3a63c --- /dev/null +++ b/exemplos/rendimento_remessa.php @@ -0,0 +1,54 @@ + 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); + +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); + +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Rendimento([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '633.png', + 'dataVencimento' => new Carbon\Carbon('2023-01-20'), + 'valor' => 12750, + 'multa' => false, + 'juros' => false, + 'numero' => 96928179, + 'numeroDocumento' => 96928179, + 'range' => 0, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '121', + 'agencia' => '0001', + 'codigoCliente' => '5447390', + 'conta' => '1234', + 'modalidadeCarteira' => '6', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', +]); + +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Rendimento([ + 'agencia' => '0001', + 'conta' => '1234', + 'carteira' => 121, + 'beneficiario' => $beneficiario, + 'codigoCliente' => '5447390', +]); +$remessa->addBoleto($boleto); + +echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'rendimento.txt'); diff --git a/exemplos/rendimento_retorno.php b/exemplos/rendimento_retorno.php new file mode 100644 index 00000000..9a9ed16f --- /dev/null +++ b/exemplos/rendimento_retorno.php @@ -0,0 +1,8 @@ +processar(); + +echo $retorno->getBancoNome(); +dd($retorno->getDetalhes()); diff --git a/exemplos/retornos.php b/exemplos/retornos.php index 8285282a..c5998a2c 100644 --- a/exemplos/retornos.php +++ b/exemplos/retornos.php @@ -1,4 +1,5 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Santander( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => 101, - 'agencia' => 1111, - 'conta' => 99999999, - 'codigoCliente' => 1234567, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Santander([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => 101, + 'agencia' => 1111, + 'conta' => 99999999, + 'codigoCliente' => 1234567, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); -$pdf->gerarBoleto($pdf::OUTPUT_SAVE, - __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'santander.pdf'); +$pdf->gerarBoleto($pdf::OUTPUT_SAVE, __DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'santander.pdf'); diff --git a/exemplos/santander_remessa.php b/exemplos/santander_remessa.php index 3e920d58..721ee20c 100644 --- a/exemplos/santander_remessa.php +++ b/exemplos/santander_remessa.php @@ -1,59 +1,52 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Santander( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'diasBaixaAutomatica' => 15, - 'carteira' => 101, - 'agencia' => 1111, - 'conta' => 99999999, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Santander([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'conta' => 99999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Santander( - [ - 'agencia' => 1111, - 'carteira' => 101, - 'conta' => 99999999, - 'codigoCliente' => 12345678, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Santander([ + 'agencia' => 1111, + 'carteira' => 101, + 'conta' => 99999999, + 'codigoCliente' => 12345678, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'santander.txt'); diff --git a/exemplos/santander_retorno.php b/exemplos/santander_retorno.php index 5ea9d294..0b0461e7 100644 --- a/exemplos/santander_retorno.php +++ b/exemplos/santander_retorno.php @@ -1,6 +1,7 @@ processar(); echo $retorno->getBancoNome(); diff --git a/exemplos/sicredi_boleto.php b/exemplos/sicredi_boleto.php index 1fda8996..ef26946e 100644 --- a/exemplos/sicredi_boleto.php +++ b/exemplos/sicredi_boleto.php @@ -1,50 +1,45 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Sicredi( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '748.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '1', - 'byte' => 2, - 'agencia' => 1111, - 'posto' => 11, - 'conta' => 11111, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Sicredi([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '748.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '1', + 'byte' => 2, + 'agencia' => 1111, + 'posto' => 11, + 'conta' => 11111, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); $pdf = new VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf(); $pdf->addBoleto($boleto); diff --git a/exemplos/sicredi_remessa.php b/exemplos/sicredi_remessa.php index 2de6af87..5791e2bb 100644 --- a/exemplos/sicredi_remessa.php +++ b/exemplos/sicredi_remessa.php @@ -1,61 +1,54 @@ 'ACME', - 'endereco' => 'Rua um, 123', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '99.999.999/9999-99', - ] -); +$beneficiario = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'ACME', + 'endereco' => 'Rua um, 123', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '99.999.999/9999-99', +]); -$pagador = new \VinicciusGuedes\LaravelCnab\Pessoa( - [ - 'nome' => 'Cliente', - 'endereco' => 'Rua um, 123', - 'bairro' => 'Bairro', - 'cep' => '99999-999', - 'uf' => 'UF', - 'cidade' => 'CIDADE', - 'documento' => '999.999.999-99', - ] -); +$pagador = new VinicciusGuedes\LaravelCnab\Pessoa([ + 'nome' => 'Cliente', + 'endereco' => 'Rua um, 123', + 'bairro' => 'Bairro', + 'cep' => '99999-999', + 'uf' => 'UF', + 'cidade' => 'CIDADE', + 'documento' => '999.999.999-99', +]); -$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Sicredi( - [ - 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '748.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, - 'numero' => 1, - 'numeroDocumento' => 1, - 'pagador' => $pagador, - 'beneficiario' => $beneficiario, - 'carteira' => '1', - 'byte' => 2, - 'agencia' => 1111, - 'posto' => 11, - 'conta' => 11111, - 'codigoCliente' => 12345, - 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], - 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', - 'especieDoc' => 'DM', - ] -); +$boleto = new VinicciusGuedes\LaravelCnab\Boleto\Banco\Sicredi([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '748.png', + 'dataVencimento' => new Carbon\Carbon(), + 'valor' => 100, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => $pagador, + 'beneficiario' => $beneficiario, + 'carteira' => '1', + 'byte' => 2, + 'agencia' => 1111, + 'posto' => 11, + 'conta' => 11111, + 'codigoCliente' => 12345, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', +]); -$remessa = new \VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Banco\Sicredi( - [ - 'agencia' => 2606, - 'carteira' => '1', - 'conta' => 12510, - 'codigoCliente'=> 12345, - 'idremessa' => 1, - 'beneficiario' => $beneficiario, - ] -); +$remessa = new VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco\Sicredi([ + 'agencia' => 2606, + 'carteira' => '1', + 'conta' => 12510, + 'codigoCliente' => 12345, + 'idremessa' => 1, + 'beneficiario' => $beneficiario, +]); $remessa->addBoleto($boleto); echo $remessa->save(__DIR__ . DIRECTORY_SEPARATOR . 'arquivos' . DIRECTORY_SEPARATOR . 'sicredi.txt'); diff --git a/exemplos/sicredi_retorno.php b/exemplos/sicredi_retorno.php index 6ebf02cf..b2ae81e5 100644 --- a/exemplos/sicredi_retorno.php +++ b/exemplos/sicredi_retorno.php @@ -1,7 +1,8 @@ processar(); echo $retorno->getBancoNome(); diff --git a/logos/085.png b/logos/085.png new file mode 100644 index 00000000..59c2b64c Binary files /dev/null and b/logos/085.png differ diff --git a/logos/133.png b/logos/133.png new file mode 100644 index 00000000..bbd230a9 Binary files /dev/null and b/logos/133.png differ diff --git a/logos/208.png b/logos/208.png new file mode 100644 index 00000000..14d4a5e6 Binary files /dev/null and b/logos/208.png differ diff --git a/logos/336.png b/logos/336.png new file mode 100644 index 00000000..a308d9bc Binary files /dev/null and b/logos/336.png differ diff --git a/logos/633.png b/logos/633.png new file mode 100644 index 00000000..605978a1 Binary files /dev/null and b/logos/633.png differ diff --git a/logos/712.png b/logos/712.png new file mode 100644 index 00000000..c48b9cdb Binary files /dev/null and b/logos/712.png differ diff --git "a/manuais/AILOS/Informa\303\247\303\265es importantes para homologa\303\247\303\243o CNAB 240.pdf" "b/manuais/AILOS/Informa\303\247\303\265es importantes para homologa\303\247\303\243o CNAB 240.pdf" new file mode 100644 index 00000000..8bc79a9f Binary files /dev/null and "b/manuais/AILOS/Informa\303\247\303\265es importantes para homologa\303\247\303\243o CNAB 240.pdf" differ diff --git a/manuais/AILOS/Linha Digitavel do boleto.jpg b/manuais/AILOS/Linha Digitavel do boleto.jpg new file mode 100644 index 00000000..5ae3f76a Binary files /dev/null and b/manuais/AILOS/Linha Digitavel do boleto.jpg differ diff --git a/manuais/AILOS/Logo_SistemaAilos_Colorido.bmp b/manuais/AILOS/Logo_SistemaAilos_Colorido.bmp new file mode 100644 index 00000000..a938e513 Binary files /dev/null and b/manuais/AILOS/Logo_SistemaAilos_Colorido.bmp differ diff --git "a/manuais/AILOS/Manual T\303\251cnico de Cobran\303\247a Banc\303\241ria \342\200\223 240 Posi\303\247\303\265es.pdf" "b/manuais/AILOS/Manual T\303\251cnico de Cobran\303\247a Banc\303\241ria \342\200\223 240 Posi\303\247\303\265es.pdf" new file mode 100644 index 00000000..2b0e6c2f Binary files /dev/null and "b/manuais/AILOS/Manual T\303\251cnico de Cobran\303\247a Banc\303\241ria \342\200\223 240 Posi\303\247\303\265es.pdf" differ diff --git a/manuais/AILOS/boleto teste.pdf b/manuais/AILOS/boleto teste.pdf new file mode 100644 index 00000000..00813edc Binary files /dev/null and b/manuais/AILOS/boleto teste.pdf differ diff --git a/manuais/BRADESCO/mpo_arquivos_layout_400P.pdf b/manuais/BRADESCO/mpo_arquivos_layout_400P.pdf new file mode 100644 index 00000000..fcd3ee50 Binary files /dev/null and b/manuais/BRADESCO/mpo_arquivos_layout_400P.pdf differ diff --git a/manuais/BTG/Calculadora Codigo de Barras.xlsx b/manuais/BTG/Calculadora Codigo de Barras.xlsx new file mode 100644 index 00000000..ff6df279 Binary files /dev/null and b/manuais/BTG/Calculadora Codigo de Barras.xlsx differ diff --git a/manuais/BTG/Layout_FEBRABAN_CNAB240_ V_10_06.pdf b/manuais/BTG/Layout_FEBRABAN_CNAB240_ V_10_06.pdf new file mode 100644 index 00000000..b616e810 Binary files /dev/null and b/manuais/BTG/Layout_FEBRABAN_CNAB240_ V_10_06.pdf differ diff --git a/manuais/BTG/Manual de Implantacao.pdf b/manuais/BTG/Manual de Implantacao.pdf new file mode 100644 index 00000000..adcf1d59 Binary files /dev/null and b/manuais/BTG/Manual de Implantacao.pdf differ diff --git a/manuais/BTG/Mascara boleto BTG PACTUAL.pdf b/manuais/BTG/Mascara boleto BTG PACTUAL.pdf new file mode 100644 index 00000000..47e286bb Binary files /dev/null and b/manuais/BTG/Mascara boleto BTG PACTUAL.pdf differ diff --git a/manuais/BTG/Tradutor CNAB.xlsx b/manuais/BTG/Tradutor CNAB.xlsx new file mode 100644 index 00000000..dacb3293 Binary files /dev/null and b/manuais/BTG/Tradutor CNAB.xlsx differ diff --git a/manuais/BTG/Tradutor Linha Digitavel BTG.xlsx b/manuais/BTG/Tradutor Linha Digitavel BTG.xlsx new file mode 100644 index 00000000..941b45e7 Binary files /dev/null and b/manuais/BTG/Tradutor Linha Digitavel BTG.xlsx differ diff --git a/manuais/CRESOL/especificacoes_tecnicas.pdf b/manuais/CRESOL/especificacoes_tecnicas.pdf new file mode 100644 index 00000000..e68ddb67 Binary files /dev/null and b/manuais/CRESOL/especificacoes_tecnicas.pdf differ diff --git a/manuais/CRESOL/integrada_remessa_cnab400_cresol 133.pdf b/manuais/CRESOL/integrada_remessa_cnab400_cresol 133.pdf new file mode 100644 index 00000000..124cdb97 Binary files /dev/null and b/manuais/CRESOL/integrada_remessa_cnab400_cresol 133.pdf differ diff --git a/manuais/CRESOL/integrada_retorno_cnab400_cresol 133.pdf b/manuais/CRESOL/integrada_retorno_cnab400_cresol 133.pdf new file mode 100644 index 00000000..6353a1d8 Binary files /dev/null and b/manuais/CRESOL/integrada_retorno_cnab400_cresol 133.pdf differ diff --git a/manuais/ITAU/COBRANCA-.400.BYTES.CNAB.-.JUL2021_v3.pdf b/manuais/ITAU/COBRANCA-.400.BYTES.CNAB.-.JUL2021_v3.pdf new file mode 100644 index 00000000..3424a33e Binary files /dev/null and b/manuais/ITAU/COBRANCA-.400.BYTES.CNAB.-.JUL2021_v3.pdf differ diff --git a/manuais/RENDIMENTO/BLOQUETE_PELO_CLIENTE.pdf b/manuais/RENDIMENTO/BLOQUETE_PELO_CLIENTE.pdf new file mode 100644 index 00000000..74ac9bc9 Binary files /dev/null and b/manuais/RENDIMENTO/BLOQUETE_PELO_CLIENTE.pdf differ diff --git a/manuais/RENDIMENTO/LAYOUT AUTK_novoCNAB400.pdf b/manuais/RENDIMENTO/LAYOUT AUTK_novoCNAB400.pdf new file mode 100644 index 00000000..49611ead Binary files /dev/null and b/manuais/RENDIMENTO/LAYOUT AUTK_novoCNAB400.pdf differ diff --git a/phpunit_gt_81.xml b/phpunit_gt_81.xml new file mode 100644 index 00000000..58ab2328 --- /dev/null +++ b/phpunit_gt_81.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + ./tests + + + + + + + + + + + ./src + + + ./src/Boleto/Render/view + + + diff --git a/src/Api/AbstractAPI.php b/src/Api/AbstractAPI.php index 27461673..20e3151d 100644 --- a/src/Api/AbstractAPI.php +++ b/src/Api/AbstractAPI.php @@ -1,39 +1,60 @@ 0) { - throw new Exception\MissingDataException($missing); + throw new MissingDataException($missing); } } - /** - * - */ - function __destruct() { + public function __destruct() + { foreach ($this->temps as $temp) { @unlink($temp); } } -// -// public function __construct($baseUrl, $conta, $certificado, $certificadoChave, $certificadoSenha = null) -// { -// $this->baseUrl = $baseUrl; -// $this->conta = $conta; -// $this->certificado = $certificado; -// $this->certificadoChave = $certificadoChave; -// $this->certificadoSenha = $certificadoSenha; -// } - abstract protected function headers(); + abstract public function createBoleto(BoletoAPIContract $boleto); + abstract public function retrieveNossoNumero($nossoNumero); + + abstract public function retrieveID($id); + abstract public function cancelNossoNumero($nossoNumero, $motivo); + + abstract public function cancelID($id, $motivo); + abstract public function retrieveList($inputedParams = []); + abstract public function getPdfNossoNumero($nossoNumero); + abstract public function getPdfID($id); + + /** + * @param $url + * @param $type + * @return mixed + * @throws ValidationException + */ + public function createWebhook($url, $type = 'all') + { + throw new ValidationException('Método não disponível no banco'); + } + public function retrieve(BoletoAPIContract $boleto) { return $this->retrieveNossoNumero($boleto->getNossoNumero()); @@ -136,6 +167,7 @@ public function getConta() public function setConta($conta) { $this->conta = $conta; + return $this; } @@ -331,11 +363,12 @@ public function getBeneficiario() * @param array $beneficiario * * @return AbstractAPI - * @throws \Exception + * @throws ValidationException */ - public function setBeneficiario($beneficiario): AbstractAPI + public function setBeneficiario($beneficiario) { Util::addPessoa($this->beneficiario, $beneficiario); + return $this; } @@ -345,6 +378,7 @@ public function setBeneficiario($beneficiario): AbstractAPI public function setDebug() { $this->debug = true; + return $this; } @@ -354,6 +388,7 @@ public function setDebug() public function unsetDebug() { $this->debug = false; + return $this; } @@ -380,6 +415,7 @@ public function getLog() public function clearLog() { $this->log = null; + return $this; } @@ -399,6 +435,7 @@ protected function getResponseHttpCode() protected function setResponseHttpCode($responseHttpCode) { $this->responseHttpCode = $responseHttpCode; + return $this; } @@ -418,20 +455,22 @@ protected function getRequestInfo() protected function setRequestInfo($requestInfo) { $this->requestInfo = $requestInfo; + return $this; } /** - * @throws Exception\CurlException - * @throws Exception\HttpException|Exception\UnauthorizedException + * @throws HttpException + * @throws UnauthorizedException + * @throws CurlException */ protected function post($url, array $post, $raw = false) { $url = ltrim($url, '/'); $this->init() ->setHeaders(array_filter([ - 'Accept' => $raw ? null : 'application/json', - 'Content-type' => $raw ? 'application/x-www-form-urlencoded' : 'application/json' + 'Accept' => $raw ? null : 'application/json', + 'Content-type' => $raw ? 'application/x-www-form-urlencoded' : 'application/json', ])); // clean string @@ -443,15 +482,44 @@ protected function post($url, array $post, $raw = false) curl_setopt($this->curl, CURLOPT_POST, 1); curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $raw ? http_build_query($post) : json_encode($post)); + + return $this->execute(); + } + + /** + * @throws HttpException + * @throws UnauthorizedException + * @throws CurlException + */ + protected function put($url, array $post, $raw = false) + { + $url = ltrim($url, '/'); + $this->init() + ->setHeaders(array_filter([ + 'Accept' => $raw ? null : 'application/json', + 'Content-type' => $raw ? 'application/x-www-form-urlencoded' : 'application/json', + ])); + + // clean string + $post = $this->arrayMapRecursive(function ($data) { + return Util::normalizeChars($data); + }, $post); + + curl_setopt($this->curl, CURLOPT_URL, $this->getBaseUrl() . $url); + curl_setopt($this->curl, CURLOPT_POST, 1); + curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT'); + curl_setopt($this->curl, CURLOPT_POSTFIELDS, $raw ? http_build_query($post) : json_encode($post)); + return $this->execute(); } /** * @param $url * - * @return \stdClass - * @throws Exception\HttpException - * @throws Exception\CurlException|Exception\UnauthorizedException + * @return stdClass + * @throws HttpException + * @throws UnauthorizedException + * @throws CurlException */ protected function get($url) { @@ -463,6 +531,7 @@ protected function get($url) curl_setopt($this->curl, CURLOPT_URL, $this->getBaseUrl() . $url); curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'GET'); + return $this->execute(); } @@ -472,13 +541,13 @@ protected function get($url) private function init() { if ($this->getCertificado() - && !file_exists($this->getCertificado()) + && ! file_exists($this->getCertificado()) && openssl_x509_read($this->getCertificado())) { $this->setCertificado($this->tempFile($this->getCertificado())); } if ($this->getCertificadoChave() - && !file_exists($this->getCertificadoChave()) + && ! file_exists($this->getCertificadoChave()) && openssl_pkey_get_private($this->getCertificadoChave())) { $this->setCertificadoChave($this->tempFile($this->getCertificadoChave())); } @@ -494,9 +563,10 @@ private function init() if ($senha = $this->getCertificadoSenha()) { curl_setopt($curl, CURLOPT_KEYPASSWD, $senha); } - curl_setopt($curl, CURLOPT_CAPATH, "/etc/ssl/certs/"); + curl_setopt($curl, CURLOPT_CAPATH, '/etc/ssl/certs/'); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST'); $this->curl = $curl; + return $this; } @@ -507,14 +577,10 @@ private function init() */ private function setHeaders($headers = []) { - $headers = array_unique( - array_merge( - $this->convertHeaders($headers), - $this->convertHeaders($this->headers()) - ) - ); + $headers = array_unique(array_merge($this->convertHeaders($headers), $this->convertHeaders($this->headers()))); curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers); + return $this; } @@ -533,17 +599,18 @@ private function convertHeaders(array $headers) $compiledHeader[] = "$param: $value"; } } + return $compiledHeader; } /** * @param $response * - * @return \stdClass + * @return stdClass */ private function parseResponse($response) { - $retorno = new \stdClass(); + $retorno = new stdClass(); $retorno->headers_text = substr($response, 0, strpos($response, "\r\n\r\n")); $retorno->body_text = substr($response, strpos($response, "\r\n\r\n")); @@ -564,34 +631,25 @@ private function parseResponse($response) /** * @param $retorno * - * @throws Exception\HttpException - * @throws Exception\UnauthorizedException + * @throws HttpException + * @throws UnauthorizedException */ private function handleException($retorno) { if ($this->getResponseHttpCode() < 200 || $this->getResponseHttpCode() > 299) { if (in_array($this->getResponseHttpCode(), [401, 403]) && empty($retorno->body_text)) { - throw new Exception\UnauthorizedException( - $this->getBaseUrl(), - $this->getCertificado(), - $this->getCertificadoChave(), - $this->getCertificadoSenha() - ); + throw new UnauthorizedException($this->getBaseUrl(), $this->getCertificado(), $this->getCertificadoChave(), $this->getCertificadoSenha()); } - throw new Exception\HttpException( - $this->getResponseHttpCode(), - $this->getRequestInfo(), - $retorno->body_text - ); + throw new HttpException($this->getResponseHttpCode(), $this->getRequestInfo(), $retorno->body_text); } } /** - * @return false|\stdClass - * @throws Exception\CurlException - * @throws Exception\HttpException - * @throws Exception\UnauthorizedException + * @return false|stdClass + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException */ private function execute() { @@ -615,6 +673,7 @@ private function execute() } $retorno = $this->parseResponse($exec); $this->handleException($retorno); + return $retorno; } @@ -629,15 +688,16 @@ private function execute() } else { $keep = false; } - $loop ++; - } while($keep == true); + $loop++; + } while ($keep == true); $error = curl_error($this->curl); curl_close($this->curl); $this->curl = null; - if (!$this->getResponseHttpCode() && $error) { - throw new Exception\CurlException($error); + if (! $this->getResponseHttpCode() && $error) { + throw new CurlException($error); } + return false; } @@ -651,6 +711,7 @@ private function tempFile($content) $tmpFile = tempnam(sys_get_temp_dir(), 'certificate'); $this->temps[] = $tmpFile; file_put_contents($tmpFile, $content); + return $tmpFile; } @@ -660,8 +721,9 @@ private function tempFile($content) * * @return array */ - private function arrayMapRecursive($callback, $input) { - $output= Array(); + private function arrayMapRecursive($callback, $input) + { + $output = []; foreach ($input as $key => $data) { if (is_array($data)) { $output[$key] = $this->arrayMapRecursive($callback, $data); @@ -669,6 +731,7 @@ private function arrayMapRecursive($callback, $input) { $output[$key] = $callback($data); } } + return $output; } -} \ No newline at end of file +} diff --git a/src/Api/Banco/Inter.php b/src/Api/Banco/Inter.php index 0bbb1afb..a867b910 100644 --- a/src/Api/Banco/Inter.php +++ b/src/Api/Banco/Inter.php @@ -1,11 +1,18 @@ version = 2; + if (isset($params['versao']) && in_array($params['versao'], [2, 3])) { + $this->version = $params['versao']; $this->camposObrigatorios = [ 'certificado', 'certificadoChave', 'client_id', - 'client_secret' + 'client_secret', ]; $this->baseUrl = 'https://cdpj.partners.bancointer.com.br'; } @@ -44,12 +51,13 @@ protected function oAuth2() if ($this->version == 1 || $this->getAccessToken()) { return $this; } - $grant = $this->post('/oauth/v2/token', [ + $grant = $this->post($this->url('auth'), [ 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'scope' => 'boleto-cobranca.read boleto-cobranca.write', - 'grant_type' => 'client_credentials' + 'grant_type' => 'client_credentials', ], true)->body; + return $this->setAccessToken('Bearer ' . $grant->access_token); } @@ -58,41 +66,78 @@ protected function oAuth2() */ protected function headers() { - if ($this->version == 2) { + if ($this->version != 1) { return array_filter([ 'Authorization' => $this->getAccessToken(), ]); } + return [ 'x-inter-conta-corrente' => $this->getConta(), ]; } /** - * @param BoletoAPIContract $boleto + * @param $url + * @param $type + * @return bool + * @throws ValidationException + */ + public function createWebhook($url, $type = 'all') + { + if ($this->version == 1) { + throw new ValidationException('Somente versão 2 e 3 da API permite criação de webhooks'); + } + try { + $this->oAuth2()->put($this->url('webhook'), ['webhookUrl' => $url]); + + return true; + } catch (Exception $e) { + return false; + } + } + + /** + * @param BoletoInter $boleto * * @return BoletoAPIContract - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\CurlException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\HttpException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\UnauthorizedException + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException + * @throws ValidationException */ public function createBoleto(BoletoAPIContract $boleto) { $data = $boleto->toAPI(); - if ($this->version == 2) { + if ($this->version != 1) { unset($data['dataEmissao']); unset($data['dataLimite']); $data['numDiasAgenda'] = (int) $boleto->getDiasBaixaAutomatica(); $data['pagador']['cpfCnpj'] = $data['pagador']['cnpjCpf']; unset($data['pagador']['cnpjCpf']); } - $retorno = $this->oAuth2()->post( - $this->version == 1 - ? 'openbanking/v1/certificado/boletos' - : 'cobranca/v2/boletos', - $data - ); - $boleto->setNossoNumero($retorno->body->nossoNumero); + if ($this->version == 3 && isset($data['desconto'])) { + $data['desconto1'] = $data['desconto']; + $data['desconto1']['codigoDesconto'] = $data['desconto']['codigo']; + unset($data['desconto1']['codigo'], $data['desconto']); + } + if ($this->version == 2 && isset($data['desconto1'])) { + $data['desconto'] = $data['desconto1']; + $data['desconto']['codigo'] = $data['desconto1']['codigoDesconto']; + unset($data['desconto']['codigoDesconto'], $data['desconto1']); + } + + $retorno = $this->oAuth2()->post($this->url('create'), $data); + + if ($this->version == 3) { + $retorno = $this->oAuth2()->get($this->url('show', $retorno->body->codigoCobranca)); + $boleto->setID($retorno->body->codigoCobranca); + $boleto->setNossoNumero($retorno->body->boleto->nossoNumero); + $boleto->setPixQrCode($retorno->body->pix->pixCopiaECola); + } else { + $boleto->setNossoNumero($retorno->body->nossoNumero); + } + return $boleto; } @@ -100,9 +145,9 @@ public function createBoleto(BoletoAPIContract $boleto) * @param array $inputedParams * * @return array - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\CurlException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\HttpException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\UnauthorizedException + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException */ public function retrieveList($inputedParams = []) { @@ -117,23 +162,30 @@ public function retrieveList($inputedParams = []) 'size' => $this->version == 1 ? 100 : null, 'paginaAtual' => $this->version == 2 ? 0 : null, 'itensPorPagina' => $this->version == 2 ? 1000 : null, - ], function($v) { return !is_null($v); }); + 'paginacao' => $this->version == 3 ? ['paginaAtual' => 0, 'itensPorPagina' => 1000] : null, + ], function ($v) { + return ! is_null($v); + }); $aRetorno = []; - do { - $retorno = $this->oAuth2()->get( - ($this->version == 1 - ? 'openbanking/v1/certificado/boletos?' - : 'cobranca/v2/boletos?') - . http_build_query($params) - ); - array_push($aRetorno, ...$retorno->body->content); - if ($this->version == 1) { - $params['page'] += 1; - } else { - $params['paginaAtual'] += 1; - } - } while (!$retorno->body->last); + if (in_array($this->version, [1, 2])) { + do { + $retorno = $this->oAuth2()->get($this->url('search') . http_build_query($params)); + array_push($aRetorno, ...$retorno->body->content); + if ($this->version == 1) { + $params['page'] += 1; + } else { + $params['paginaAtual'] += 1; + } + } while (! $retorno->body->last); + } else { + do { + $retorno = $this->oAuth2()->get($this->url('search') . http_build_query($params)); + array_push($aRetorno, ...$retorno->body->cobrancas); + $params['paginacao']['paginaAtual'] += 1; + } while (! $retorno->body->ultimaPagina); + } + return array_map([$this, 'arrayToBoleto'], $aRetorno); } @@ -141,17 +193,39 @@ public function retrieveList($inputedParams = []) * @param $nossoNumero * * @return mixed - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\CurlException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\HttpException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\UnauthorizedException + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException + * @throws ValidationException */ public function retrieveNossoNumero($nossoNumero) { - return $this->oAuth2()->get( - $this->version == 1 - ? 'openbanking/v1/certificado/boletos/' . $nossoNumero - : 'cobranca/v2/boletos/' . $nossoNumero - )->body; + if ($this->version == 3) { + throw new ValidationException('Versão 3 da API somente recupera boleto pelo ID da cobrança'); + } + $response = $this->oAuth2()->get($this->url('show', $nossoNumero)); + + return $this->version == 1 + ? $response + : $response->body; + } + + /** + * @param $id + * + * @return mixed + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException + * @throws ValidationException + */ + public function retrieveID($id) + { + if ($this->version != 3) { + throw new ValidationException('Versão 1 e 2 da API somente recupera boleto pelo nosso número'); + } + + return $this->oAuth2()->get($this->url('show', $id))->body; } /** @@ -159,12 +233,16 @@ public function retrieveNossoNumero($nossoNumero) * @param string $motivo * * @return mixed - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\CurlException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\HttpException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\UnauthorizedException + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException + * @throws ValidationException */ public function cancelNossoNumero($nossoNumero, $motivo = 'ACERTOS') { + if ($this->version == 3) { + throw new ValidationException('Versão 3 da API somente cancela boleto pelo ID da cobrança'); + } $motivosValidos = [ 'ACERTOS', 'PAGODIRETOAOCLIENTE', @@ -182,47 +260,122 @@ public function cancelNossoNumero($nossoNumero, $motivo = 'ACERTOS') ]; } - if (!in_array(Util::upper($motivo), $motivosValidos)) { + if (! in_array(Util::upper($motivo), $motivosValidos)) { $motivo = 'ACERTOS'; } + return $this->oAuth2()->post( - $this->version == 1 - ? 'openbanking/v1/certificado/boletos/' . $nossoNumero . '/baixas' - : 'cobranca/v2/boletos/' . $nossoNumero . '/cancelar', + $this->url('cancel', $nossoNumero), $this->version == 1 ? ['codigoBaixa' => $motivo] : ['motivoCancelamento' => $motivo] )->body; } + /** + * @param $id + * @param string $motivo + * + * @return mixed + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException + * @throws ValidationException + */ + public function cancelID($id, $motivo) + { + if ($this->version != 3) { + throw new ValidationException('Versão 1 e 2 da API somente cancela boleto pelo nosso número'); + } + + return $this->oAuth2()->post($this->url('cancel', $id), ['motivoCancelamento' => $motivo])->body; + } + /** * @param $nossoNumero * * @return mixed - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\CurlException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\HttpException - * @throws \VinicciusGuedes\LaravelCnab\Api\Exception\UnauthorizedException + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException + * @throws ValidationException */ public function getPdfNossoNumero($nossoNumero) { - return $this->oAuth2()->get( - $this->version == 1 - ? 'openbanking/v1/certificado/boletos/' . $nossoNumero . '/pdf' - : 'cobranca/v2/boletos/' . $nossoNumero . '/pdf' - )->body; + if ($this->version == 3) { + throw new ValidationException('Versão 3 da API somente recupera PDF pelo ID da cobrança'); + } + + return $this->oAuth2()->get($this->url('pdf', $nossoNumero))->body; + } + + /** + * @param $id + * + * @return mixed + * @throws CurlException + * @throws HttpException + * @throws UnauthorizedException + * @throws ValidationException + */ + public function getPdfID($id) + { + if ($this->version == 3) { + throw new ValidationException('Versão 1, 2 da API somente recupera PDF pelo nosso número'); + } + + return $this->oAuth2()->get($this->url('pdf', $id))->body; } /** * @param $boleto * - * @return \VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter - * @throws \Exception + * @return BoletoInter + * @throws ValidationException */ private function arrayToBoleto($boleto) { - return \VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter::fromAPI($boleto, [ + return BoletoInter::fromAPI($boleto, [ 'conta' => $this->getConta(), 'beneficiario' => $this->getBeneficiario(), ]); } -} \ No newline at end of file + + /** + * @param $type + * @param $param + * @return string + */ + private function url($type, $param = null) + { + $aUrls = [ + 1 => [ + 'create' => 'openbanking/v1/certificado/boletos', + 'show' => 'openbanking/v1/certificado/boletos/' . $param, + 'cancel' => 'openbanking/v1/certificado/boletos/' . $param . '/baixas', + 'pdf' => 'openbanking/v1/certificado/boletos/' . $param . '/pdf', + 'search' => 'openbanking/v1/certificado/boletos?', + ], + 2 => [ + 'create' => 'cobranca/v2/boletos', + 'show' => 'cobranca/v2/boletos/' . $param, + 'cancel' => 'cobranca/v2/boletos/' . $param . '/cancelar', + 'pdf' => 'cobranca/v2/boletos/' . $param . '/pdf', + 'search' => 'cobranca/v2/boletos?', + 'auth' => '/oauth/v2/token', + 'webhook' => 'cobranca/v2/boletos/webhook', + ], + 3 => [ + 'create' => 'cobranca/v3/cobrancas', + 'show' => 'cobranca/v3/cobrancas/' . $param, + 'cancel' => 'cobranca/v3/cobrancas/' . $param . '/cancelar', + 'pdf' => 'cobranca/v3/cobrancas/' . $param . '/pdf', + 'search' => 'cobranca/v3/cobrancas?', + 'auth' => '/oauth/v2/token', + 'webhook' => 'cobranca/v3/cobrancas/webhook', + ], + ]; + + return Arr::get($aUrls, "$this->version.$type"); + } +} diff --git a/src/Api/Exception/CurlException.php b/src/Api/Exception/CurlException.php index 11cf264b..771cefa9 100644 --- a/src/Api/Exception/CurlException.php +++ b/src/Api/Exception/CurlException.php @@ -1,9 +1,9 @@ http_code = $http_code; @@ -34,12 +35,6 @@ public function getInfo() public function __toString() { - return sprintf( - "\nMessage:%s\nHttpCode: %s\nInfo:%s\n\nTrace:%s", - trim($this->getMessage()), - $this->getHttpCode(), - is_array($this->getInfo()) ? print_r($this->getInfo(), true) : $this->getInfo(), - $this->getTraceAsString() - ); + return sprintf("\nMessage:%s\nHttpCode: %s\nInfo:%s\n\nTrace:%s", trim($this->getMessage()), $this->getHttpCode(), is_array($this->getInfo()) ? print_r($this->getInfo(), true) : $this->getInfo(), $this->getTraceAsString()); } -} \ No newline at end of file +} diff --git a/src/Api/Exception/MissingDataException.php b/src/Api/Exception/MissingDataException.php index e916ec7a..45c393b5 100644 --- a/src/Api/Exception/MissingDataException.php +++ b/src/Api/Exception/MissingDataException.php @@ -1,9 +1,10 @@ container = new Container; $this->viewPaths = (array) $viewPaths; $this->cachePath = $cachePath; @@ -78,6 +79,7 @@ public function registerEngineResolver() $resolver = new EngineResolver; $self->registerPhpEngine($resolver); $self->registerBladeEngine($resolver); + return $resolver; }); } @@ -85,18 +87,20 @@ public function registerEngineResolver() /** * Register the PHP engine implementation. * - * @param \Illuminate\View\Engines\EngineResolver $resolver + * @param EngineResolver $resolver * @return void */ public function registerPhpEngine($resolver) { - $resolver->register('php', function() { return new PhpEngine; }); + $resolver->register('php', function () { + return new PhpEngine; + }); } /** * Register the Blade engine implementation. * - * @param \Illuminate\View\Engines\EngineResolver $resolver + * @param EngineResolver $resolver * @return void */ public function registerBladeEngine($resolver) @@ -106,6 +110,7 @@ public function registerBladeEngine($resolver) $this->container->singleton('blade.compiler', function($app) use ($self) { $cache = $self->cachePath; + return new BladeCompiler($app['files'], $cache); }); @@ -131,7 +136,6 @@ public function registerViewFinder() /** * Register the view environment. - * */ public function registerFactory() { diff --git a/src/Boleto/AbstractBoleto.php b/src/Boleto/AbstractBoleto.php index 9ad634c5..e7ba3d6a 100644 --- a/src/Boleto/AbstractBoleto.php +++ b/src/Boleto/AbstractBoleto.php @@ -2,32 +2,46 @@ namespace VinicciusGuedes\LaravelCnab\Boleto; +use Exception; +use Throwable; use Carbon\Carbon; -use VinicciusGuedes\LaravelCnab\Boleto\Render\Html; +use Illuminate\Support\Str; +use chillerlan\QRCode\QRCode; +use chillerlan\QRCode\QROptions; +use VinicciusGuedes\LaravelCnab\Util; +use chillerlan\QRCode\Data\QRMatrix; +use VinicciusGuedes\LaravelCnab\MagicTrait; +use chillerlan\QRCode\Output\QROutputInterface; use VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf; +use VinicciusGuedes\LaravelCnab\Boleto\Render\Html; use VinicciusGuedes\LaravelCnab\Boleto\Render\PdfCaixa; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Pessoa as PessoaContract; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Str; /** * Class AbstractBoleto - * - * @package VinicciusGuedes\LaravelCnab\Boleto */ abstract class AbstractBoleto implements BoletoContract { + use MagicTrait; const SITUACAO_REJEITADO = 'rejeitado'; const SITUACAO_ABERTO = 'aberto'; const SITUACAO_BAIXADO = 'baixado'; const SITUACAO_PAGO = 'pago'; const SITUACAO_PROTESTADO = 'protestado'; + const TIPO_CHAVEPIX_CPF = 'cpf'; + const TIPO_CHAVEPIX_CNPJ = 'cnpj'; + const TIPO_CHAVEPIX_CELULAR = 'celular'; + const TIPO_CHAVEPIX_EMAIL = 'email'; + const TIPO_CHAVEPIX_ALEATORIA = 'aleatoria'; + const QRCODE_ESTILO_QUADRADO = 'square'; + const QRCODE_ESTILO_PONTO = 'dot'; /** - * Campos que são necessários para o boleto + * Campos necessários para o boleto * * @var array */ @@ -42,262 +56,307 @@ abstract class AbstractBoleto implements BoletoContract 'nossoNumero', ]; + /** + * @var string + */ + protected $id; + /** * Código do banco * * @var string */ protected $codigoBanco; + /** * Moeda * * @var int */ protected $moeda = 9; + /** * Valor total do boleto * * @var float */ public $valor; + /** * Desconto total do boleto * * @var float */ public $desconto; + /** * Valor para multa * * @var float */ public $multa = 0; + /** * Valor para mora juros * * @var float */ public $juros = 0; + /** * Dias apos vencimento do juros * * @var int */ public $jurosApos = 0; + /** * Dias para protesto * - * @var integer + * @var int */ public $diasProtesto = 0; + /** * Dias para baixa automática * - * @var integer + * @var int */ public $diasBaixaAutomatica; + /** * Data do documento * - * @var \Carbon\Carbon + * @var Carbon */ public $dataDocumento; + /** * Data de emissão * - * @var \Carbon\Carbon + * @var Carbon */ public $dataProcessamento; + /** * Data de vencimento * - * @var \Carbon\Carbon + * @var Carbon */ public $dataVencimento; + /** * Data de limite de desconto * - * @var \Carbon\Carbon + * @var Carbon */ public $dataDesconto; + /** * Campo de aceite * * @var string */ protected $aceite = 'N'; + /** * Espécie do documento, geralmente DM (Duplicata Mercantil) * * @var string */ protected $especieDoc = 'DM'; + /** * Espécie do documento, coódigo para remessa * * @var array */ protected $especiesCodigo = []; + /** * Espécie do documento, coódigo para remessa * * @var array */ protected $especiesCodigo240 = []; + /** * Espécie do documento, coódigo para remessa * * @var array */ protected $especiesCodigo400 = []; + /** * Número do documento * * @var int */ public $numeroDocumento; + /** * Define o número definido pelo cliente para compor o Nosso Número * * @var int */ public $numero; + /** * Define o número definido pelo cliente para controle da remessa * * @var string */ public $numeroControle; + /** * Campo de uso do banco no boleto * * @var string */ protected $usoBanco; + /** * Chave da nfe para cnab de 444 posições * * @var string */ public $chaveNfe; + /** * Agência * * @var string */ protected $agencia; + /** * Dígito da agência * * @var string */ protected $agenciaDv; + /** * Conta * * @var string */ protected $conta; + /** * Dígito da conta * * @var string */ protected $contaDv; + /** * Modalidade de cobrança do cliente, geralmente Cobrança Simples ou Registrada * * @var string */ protected $carteira; + /** * Define as carteiras disponíveis para cada banco * * @var array|bool */ protected $carteiras = []; + /** * Define as carteiras disponíveis para cada banco * * @var array */ protected $carteirasNomes = []; + /** - * Entidade beneficiario (quem emite o boleto) + * Entidade beneficiária (quem emite o boleto) * * @var PessoaContract */ public $beneficiario; + /** * Entidade pagadora (de quem se cobra o boleto) * * @var PessoaContract */ public $pagador; + /** - * Entidade sacador avalista + * Entidade sacadora avalista * * @var PessoaContract */ public $sacadorAvalista; + /** * Array com as linhas do demonstrativo (descrição do pagamento) * * @var array */ protected $descricaoDemonstrativo; + /** * Linha de local de pagamento * * @var string */ protected $localPagamento = 'Pagável em qualquer agência bancária até o vencimento.'; + /** * Array com as linhas de instruções * * @var array */ protected $instrucoes = ['Pagar até a data do vencimento.']; + /** * Array com as linhas de instruções de impressão * * @var array */ protected $instrucoes_impressao = []; + /** * Localização do logotipo do banco, referente ao diretório de imagens * * @var string */ protected $logo; + /** * Variáveis adicionais. * * @var array */ public $variaveis_adicionais = []; + /** * Cache do campo livre para evitar processamento desnecessário. * * @var string */ protected $campoLivre; + /** - * Cache do nosso numero para evitar processamento desnecessário. + * Cache do nosso número para evitar processamento desnecessário. * * @var string */ protected $campoNossoNumero; /** - * Cache da linha digitabel para evitar processamento desnecessário. + * Cache da linha digitável para evitar processamento desnecessário. * * @var string */ protected $campoLinhaDigitavel; /** - * Cache do codigo de barras para evitar processamento desnecessário. + * Cache do código de barras para evitar processamento desnecessário. * * @var string */ @@ -325,21 +384,21 @@ abstract class AbstractBoleto implements BoletoContract /** * Mostrar o endereço do beneficiário abaixo da razão e CNPJ na ficha de compensação * - * @var boolean + * @var bool */ protected $mostrarEnderecoFichaCompensacao = false; /** - * Situacao do boleto no banco, pago aberto portestado... + * Situação do boleto no banco, pago aberto protestado... * * @var string */ public $situacao; /** - * Data da situacao + * Data da situação * - * @var \Carbon\Carbon + * @var Carbon */ public $dataSituacao; @@ -349,7 +408,11 @@ abstract class AbstractBoleto implements BoletoContract public $valorRecebido; /** - * + * @var string + */ + private $qrCodeStyle = self::QRCODE_ESTILO_QUADRADO; + + /** * Recebe a imagem em base 64 do QR Code do PIX * * @var ?string @@ -357,19 +420,21 @@ abstract class AbstractBoleto implements BoletoContract private $pixQrCode = null; /** - * - * Código PIX - TXID - * - * @var ?string + * Chave Pix para criação de boleto com pix + * @var null + */ + private $pixChave = null; + + /** + * Tipo da chave pix + * @var null */ - private $pixTxid = null; + private $pixChaveTipo = null; /** * AbstractBoleto constructor. * * @param array $params - * - * @throws \Exception */ public function __construct($params = []) { @@ -412,6 +477,7 @@ protected function setCamposObrigatorios() foreach ($args as $arg) { $this->addCampoObrigatorio($arg); } + return $this; } @@ -427,9 +493,30 @@ protected function addCampoObrigatorio() !is_array($arg) || call_user_func_array([$this, __FUNCTION__], $arg); !is_string($arg) || array_push($this->camposObrigatorios, $arg); } + return $this; } + /** + * @param $id + * @return AbstractBoleto + * @throws ValidationException + */ + public function setID($id) + { + $this->id = $this->validateId($id); + + return $this; + } + + /** + * @return string + */ + public function getID() + { + return $this->id; + } + /** * Define a agência * @@ -484,12 +571,12 @@ public function getAgenciaDv() * @param string $carteira * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setCarteira($carteira) { if ($this->getCarteiras() !== false && !in_array($carteira, $this->getCarteiras())) { - throw new \Exception("Carteira não disponível!"); + throw new ValidationException('Carteira não disponível!'); } $this->carteira = $carteira; @@ -522,16 +609,17 @@ public function getCarteiras() * @param $beneficiario * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setBeneficiario($beneficiario) { Util::addPessoa($this->beneficiario, $beneficiario); + return $this; } /** - * Retorna a entidade beneficiario + * Retorna a entidade beneficiário * * @return PessoaContract */ @@ -564,6 +652,20 @@ public function setConta($conta) return $this; } + /** + * Define o número da conta + * + * @param string $conta + * + * @return AbstractBoleto + */ + public function setContaCorrente($conta) + { + $this->conta = (string) $conta; + + return $this; + } + /** * Retorna o número da conta * @@ -588,6 +690,20 @@ public function setContaDv($contaDv) return $this; } + /** + * Define o dígito verificador da conta + * + * @param string $contaDv + * + * @return AbstractBoleto + */ + public function setContaCorrenteDv($contaDv) + { + $this->contaDv = $contaDv; + + return $this; + } + /** * Retorna o dígito verificador da conta * @@ -601,7 +717,7 @@ public function getContaDv() /** * Define a data de vencimento * - * @param \Carbon\Carbon $dataVencimento + * @param Carbon $dataVencimento * * @return AbstractBoleto */ @@ -615,7 +731,7 @@ public function setDataVencimento(Carbon $dataVencimento) /** * Retorna a data de vencimento * - * @return \Carbon\Carbon + * @return Carbon */ public function getDataVencimento() { @@ -625,7 +741,7 @@ public function getDataVencimento() /** * Define a data de limite de desconto * - * @param \Carbon\Carbon $dataDesconto + * @param Carbon $dataDesconto * * @return AbstractBoleto */ @@ -639,7 +755,7 @@ public function setDataDesconto(Carbon $dataDesconto) /** * Retorna a data de limite de desconto * - * @return \Carbon\Carbon + * @return Carbon */ public function getDataDesconto() { @@ -649,7 +765,7 @@ public function getDataDesconto() /** * Define a data do documento * - * @param \Carbon\Carbon $dataDocumento + * @param Carbon $dataDocumento * * @return AbstractBoleto */ @@ -663,7 +779,7 @@ public function setDataDocumento(Carbon $dataDocumento) /** * Retorna a data do documento * - * @return \Carbon\Carbon + * @return Carbon */ public function getDataDocumento() { @@ -671,9 +787,9 @@ public function getDataDocumento() } /** - * Retorna a data do juros após + * Retorna a data do juro após * - * @return \Carbon\Carbon + * @return Carbon */ public function getDataVencimentoApos() { @@ -729,7 +845,7 @@ public function getEspecieDoc() } /** - * Retorna o codigo da Espécie Doc + * Retorna o código da Espécie Doc * * @param int $default * @param int $tipo @@ -745,6 +861,7 @@ public function getEspecieDocCodigo($default = 99, $tipo = 240) } else { $especie = $this->especiesCodigo; } + return key_exists(strtoupper($this->especieDoc), $especie) ? $especie[strtoupper($this->getEspecieDoc())] : $default; @@ -852,14 +969,14 @@ public function getUsoBanco() * @param string $chaveNfe * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setChaveNfe($chaveNfe) { $chaveNfe = Util::onlyNumbers($chaveNfe); - if (strlen($chaveNfe) != 44) { - throw new \Exception('Chave de nfe não possui 44 posições'); + if (strlen($chaveNfe) != 44 && ! empty($chaveNfe)) { + throw new ValidationException('Chave de nfe não possui 44 posições'); } $this->chaveNfe = $chaveNfe; @@ -874,13 +991,17 @@ public function setChaveNfe($chaveNfe) */ public function getChaveNfe() { + if (strlen($this->chaveNfe) != 44) { + return null; + } + return $this->chaveNfe; } /** * Define a data de geração do boleto * - * @param \Carbon\Carbon $dataProcessamento + * @param Carbon $dataProcessamento * * @return AbstractBoleto */ @@ -894,7 +1015,7 @@ public function setDataProcessamento(Carbon $dataProcessamento) /** * Retorna a data de geração do boleto * - * @return \Carbon\Carbon + * @return Carbon */ public function getDataProcessamento() { @@ -907,12 +1028,12 @@ public function getDataProcessamento() * @param string $instrucao * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function addInstrucao($instrucao) { if (count($this->getInstrucoes()) > 8) { - throw new \Exception('Atingido o máximo de 5 instruções.'); + throw new ValidationException('Atingido o máximo de 5 instruções.'); } array_push($this->instrucoes, $instrucao); @@ -925,12 +1046,12 @@ public function addInstrucao($instrucao) * @param array $instrucoes * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setInstrucoes(array $instrucoes) { if (count($instrucoes) > 8) { - throw new \Exception('Máximo de 8 instruções.'); + throw new ValidationException('Máximo de 8 instruções.'); } $this->instrucoes = $instrucoes; @@ -953,12 +1074,12 @@ public function getInstrucoes() * @param array $instrucoes_impressao * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setInstrucoesImpressao(array $instrucoes_impressao) { if (count($instrucoes_impressao) > 5) { - throw new \Exception('Máximo de 5 instruções.'); + throw new ValidationException('Máximo de 5 instruções.'); } $this->instrucoes_impressao = $instrucoes_impressao; @@ -972,11 +1093,12 @@ public function setInstrucoesImpressao(array $instrucoes_impressao) */ public function getInstrucoesImpressao() { - if (!empty($this->instrucoes_impressao)) + if (! empty($this->instrucoes_impressao)) { return array_slice((array)$this->instrucoes_impressao + [null, null, null, null, null], 0, 5); - else + } else { return []; } + } /** * Adiciona um demonstrativo (máximo 5) @@ -984,12 +1106,12 @@ public function getInstrucoesImpressao() * @param string $descricaoDemonstrativo * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function addDescricaoDemonstrativo($descricaoDemonstrativo) { if (count($this->getDescricaoDemonstrativo()) > 5) { - throw new \Exception('Atingido o máximo de 5 demonstrativos.'); + throw new ValidationException('Atingido o máximo de 5 demonstrativos.'); } array_push($this->descricaoDemonstrativo, $descricaoDemonstrativo); @@ -1002,12 +1124,12 @@ public function addDescricaoDemonstrativo($descricaoDemonstrativo) * @param array $descricaoDemonstrativo * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setDescricaoDemonstrativo(array $descricaoDemonstrativo) { if (count($descricaoDemonstrativo) > 5) { - throw new \Exception('Máximo de 5 demonstrativos.'); + throw new ValidationException('Máximo de 5 demonstrativos.'); } $this->descricaoDemonstrativo = $descricaoDemonstrativo; @@ -1078,11 +1200,12 @@ public function getMoeda() * @param $pagador * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setPagador($pagador) { Util::addPessoa($this->pagador, $pagador); + return $this; } @@ -1102,11 +1225,12 @@ public function getPagador() * @param $sacadorAvalista * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setSacadorAvalista($sacadorAvalista) { Util::addPessoa($this->sacadorAvalista, $sacadorAvalista); + return $this; } @@ -1226,6 +1350,7 @@ public function getMoraDia() if ($this->getJuros() <= 0) { return 0; } + return Util::percent($this->getValor(), $this->getJuros())/30; } @@ -1260,7 +1385,7 @@ public function getJurosApos() * @param int $diasProtesto * * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setDiasProtesto($diasProtesto) { @@ -1268,7 +1393,7 @@ public function setDiasProtesto($diasProtesto) $this->diasProtesto = $diasProtesto > 0 ? $diasProtesto : 0; if (!empty($diasProtesto) && $this->getDiasBaixaAutomatica() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } return $this; @@ -1287,19 +1412,19 @@ public function getDiasProtesto($default = 0) } /** - * Seta dias para baixa automática + * Seta os dias para baixa automática * * @param int $baixaAutomatica - * @throws \Exception + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { $exception = sprintf('O banco %s não suporta baixa automática, pode usar também: setDiasProtesto(%s)', basename(get_class($this)), $baixaAutomatica); - throw new \Exception($exception); + throw new ValidationException($exception); } /** - * Retorna os diasBaixaAutomatica + * Retorna os dias de Baixa Automática * * @param int $default * @@ -1312,6 +1437,7 @@ public function getDiasBaixaAutomatica($default = 0) if(empty($this->getDiasProtesto())){ $default = (empty($default)?60:$default); } + return $this->diasBaixaAutomatica > 0 ? $this->diasBaixaAutomatica : $default; } @@ -1336,7 +1462,7 @@ public function setLogo($logo) */ public function getLogo() { - return $this->logo ? $this->logo : "http://dummyimage.com/300x70/f5/0.png&text=Sem+Logo"; + return $this->logo ? $this->logo : 'http://dummyimage.com/300x70/f5/0.png&text=Sem+Logo'; } /** @@ -1434,18 +1560,17 @@ public function baixarBoleto() */ public function getLogoBancoBase64() { - return 'data:image/' . pathinfo($this->getLogoBanco(), - PATHINFO_EXTENSION) . ';base64,' . base64_encode(file_get_contents($this->getLogoBanco())); + return 'data:image/' . pathinfo($this->getLogoBanco(), PATHINFO_EXTENSION) . ';base64,' . base64_encode(file_get_contents($this->getLogoBanco())); } /** * Mostra exception ao erroneamente tentar setar o nosso número * - * @throws \Exception + * @throws ValidationException */ public function setNossoNumero($nossoNumero) { - throw new \Exception('Não é possível definir o nosso número diretamente. Utilize o método setNumero.'); + throw new ValidationException('Não é possível definir o nosso número diretamente. Utilize o método setNumero.'); } /** @@ -1458,11 +1583,12 @@ public function getNossoNumero() if (empty($this->campoNossoNumero)) { return $this->campoNossoNumero = $this->gerarNossoNumero(); } + return $this->campoNossoNumero; } /** - * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. + * Método que retorna o nosso número usado no boleto. Alguns bancos possuem algumas diferenças. * * @return string */ @@ -1486,11 +1612,11 @@ abstract protected function gerarNossoNumero(); abstract protected function getCampoLivre(); /** - * Método que valida se o banco tem todos os campos obrigadotorios preenchidos + * Método que valida se o banco tem todos os campos obrigatórios preenchidos * * @param $messages * - * @return boolean + * @return bool */ public function isValid(&$messages) { @@ -1498,13 +1624,16 @@ public function isValid(&$messages) $test = call_user_func([$this, 'get' . Str::camel($campo)]); if ($test === '' || is_null($test)) { $messages .= "Campo $campo está em branco"; + return false; } } if (empty($this->campoNossoNumero) && empty($this->gerarNossoNumero())) { - $messages .= "Campo nosso número está em branco"; + $messages .= 'Campo nosso número está em branco'; + return false; } + return true; } @@ -1537,10 +1666,10 @@ public function getCarteiraNome() } /** - * Retorna o codigo de barras + * Retorna o código de barras * * @return string - * @throws \Exception + * @throws ValidationException */ public function getCodigoBarras() { @@ -1549,7 +1678,7 @@ public function getCodigoBarras() } if (!$this->isValid($messages)) { - throw new \Exception('Campos requeridos pelo banco, aparentam estar ausentes ' . $messages); + throw new ValidationException('Campos requeridos pelo banco, aparentam estar ausentes ' . $messages); } $codigo = Util::numberFormatGeral($this->getCodigoBanco(), 3) @@ -1564,7 +1693,6 @@ public function getCodigoBarras() return $this->campoCodigoBarras = substr($codigo, 0, 4) . $dv . substr($codigo, 4); } - /** * Retorna código de barras inserido * @@ -1598,7 +1726,7 @@ public function getCodigoBancoComDv() { $codigoBanco = $this->getCodigoBanco(); - $semX = [BoletoContract::COD_BANCO_CEF]; + $semX = [BoletoContract::COD_BANCO_CEF, BoletoContract::COD_BANCO_AILOS]; $x10 = in_array($codigoBanco, $semX) ? 0 : 'X'; return $codigoBanco . '-' . Util::modulo11($codigoBanco, 2, 9, 0, $x10); @@ -1608,7 +1736,7 @@ public function getCodigoBancoComDv() * Retorna a linha digitável do boleto * * @return string - * @throws \Exception + * @throws ValidationException */ public function getLinhaDigitavel() { @@ -1616,25 +1744,7 @@ public function getLinhaDigitavel() return $this->campoLinhaDigitavel; } - $codigo = $this->getCodigoBarras(); - - $s1 = substr($codigo, 0, 4) . substr($codigo, 19, 5); - $s1 = $s1 . Util::modulo10($s1); - $s1 = substr_replace($s1, '.', 5, 0); - - $s2 = substr($codigo, 24, 10); - $s2 = $s2 . Util::modulo10($s2); - $s2 = substr_replace($s2, '.', 5, 0); - - $s3 = substr($codigo, 34, 10); - $s3 = $s3 . Util::modulo10($s3); - $s3 = substr_replace($s3, '.', 5, 0); - - $s4 = substr($codigo, 4, 1); - - $s5 = substr($codigo, 5, 14); - - return $this->campoLinhaDigitavel = sprintf('%s %s %s %s %s', $s1, $s2, $s3, $s4, $s5); + return $this->campoLinhaDigitavel = Util::formatLinhaDigitavel(Util::codigoBarras2LinhaDigitavel($this->getCodigoBarras())); } /** @@ -1720,15 +1830,124 @@ public function setValorRecebido($valorRecebido) /** * @return ?string */ - public function getPixQrCode(): ?string + public function getPixQrCode() { return $this->pixQrCode; } + /** + * @return null + */ + public function getPixChave() + { + return $this->pixChave; + } + + /** + * @param null $pixChave + * @return AbstractBoleto + */ + public function setPixChave($pixChave) + { + $this->pixChave = $pixChave; + + return $this; + } + + /** + * @return null + */ + public function getPixChaveTipo() + { + return $this->pixChaveTipo; + } + + /** + * @param null $pixChaveTipo + * @return AbstractBoleto + * @throws ValidationException + */ + public function setPixChaveTipo($pixChaveTipo) + { + if (! in_array($pixChaveTipo, [self::TIPO_CHAVEPIX_CPF, self::TIPO_CHAVEPIX_CNPJ, self::TIPO_CHAVEPIX_CELULAR, self::TIPO_CHAVEPIX_EMAIL, self::TIPO_CHAVEPIX_ALEATORIA])) { + throw new ValidationException(sprintf('Tipo de chave %s não é válido', $pixChaveTipo)); + } + $this->pixChaveTipo = $pixChaveTipo; + + return $this; + } + + /** + * @return string + */ + public function getQrCodeStyle() + { + return $this->qrCodeStyle; + } + + /** + * @param string $qrCodeStyle + * @return AbstractBoleto + * @throws ValidationException + */ + public function setQrCodeStyle($qrCodeStyle) + { + if (! in_array($qrCodeStyle, [self::QRCODE_ESTILO_QUADRADO, self::QRCODE_ESTILO_PONTO])) { + throw new ValidationException(sprintf('Estilo QRCODE %s não é válido', $qrCodeStyle)); + } + + $this->qrCodeStyle = $qrCodeStyle; + + return $this; + } + + /** + * @return ?string + */ + public function getPixQrCodeBase64() + { + if ($this->getPixQrCode() == null) { + return null; + } + if (Util::isBase64($this->getPixQrCode())) { + return 'data://text/plain;base64,' . $this->getPixQrCode(); + } + + if (Str::startsWith($this->getPixQrCode(), 'data:')) { + return $this->getPixQrCode(); + } + + $options = new QROptions; + + if (defined('\chillerlan\QRCode\QRCode::OUTPUT_IMAGE_PNG')) { + $options->outputType = QRCode::OUTPUT_IMAGE_PNG; + $options->eccLevel = QRCode::ECC_L; + } else { + $options->outputType = QROutputInterface::GDIMAGE_PNG; + $options->addQuietzone = true; + } + + $options->scale = 20; + $options->quietzoneSize = 1; + $options->drawLightModules = false; + + if ($this->getQrCodeStyle() == self::QRCODE_ESTILO_PONTO) { + $options->drawCircularModules = true; + $options->circleRadius = .5; + $options->keepAsSquare = [ + QRMatrix::M_FINDER_DOT, + QRMatrix::M_FINDER_DARK, + ]; + } + $qrCode = new QRCode($options); + + return $qrCode->render($this->getPixQrCode()); + } + /** * @param string $pixQrCode */ - public function setPixQrCode(string $pixQrCode): void + public function setPixQrCode($pixQrCode) { $this->pixQrCode = $pixQrCode; } @@ -1799,6 +2018,88 @@ public function isProtestado() return $this->isSituacao(self::SITUACAO_PROTESTADO); } + /** + * @return bool + */ + public function imprimeBoleto() + { + return true; + } + + /** + * @param $id + * @return string + * @throws ValidationException + */ + protected function validateId($id) + { + return $id; + } + + /** + * @return bool + * @throws ValidationException + */ + public function validarPix() + { + if ($this->getPixChave() || $this->getPixChaveTipo()) { + if (! $this->getPixChave()) { + throw new ValidationException('Informado tipo de chave de Pix porém não foi informado a chave'); + } + if (! $this->getPixChaveTipo()) { + throw new ValidationException('Informado chave de Pix porém não foi informado o tipo de chave'); + } + if (! $this->getID()) { + throw new ValidationException('ID necessita ser informado para geração da cobrança'); + } + + switch ($this->getPixChaveTipo()) { + case self::TIPO_CHAVEPIX_CPF: + if (! Util::validarCpf($this->getPixChave())) { + throw new ValidationException(sprintf('Chave do tipo CPF é invalida: %s', $this->getPixChave())); + } + break; + case self::TIPO_CHAVEPIX_CNPJ: + if (! Util::validarCnpj($this->getPixChave())) { + throw new ValidationException(sprintf('Chave do tipo CNPJ é invalida: %s', $this->getPixChave())); + } + break; + case self::TIPO_CHAVEPIX_EMAIL: + if (! filter_var($this->getPixChave(), FILTER_VALIDATE_EMAIL)) { + throw new ValidationException(sprintf('Chave do tipo EMAIL é invalida: %s', $this->getPixChave())); + } + break; + case self::TIPO_CHAVEPIX_CELULAR: + if (! preg_match('/^(\+\d{2}\s?)?[-.\s]?\(?\d{2}\)?[-.\s]?(\d\s?)?\d{4}[-.\s]?\d{4}$/', $this->getPixChave())) { + throw new ValidationException(sprintf('Chave do tipo CELULAR é invalida: %s', $this->getPixChave())); + } + break; + case self::TIPO_CHAVEPIX_ALEATORIA: + if (! preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $this->getPixChave())) { + throw new ValidationException(sprintf('Chave do tipo ALEATÓRIA é invalida: %s', $this->getPixChave())); + } + break; + } + + return true; + } + + return false; + } + + /** + * @return string|null + * @throws ValidationException + */ + public function gerarPixCopiaECola() + { + if ($this->getPixChave() && $this->getValor() && $this->getID() && $this->getBeneficiario()) { + $this->setPixQrCode(Util::gerarPixCopiaECola($this->getPixChave(), $this->getValor(), $this->getID(), $this->getBeneficiario())); + } + + return $this->getPixQrCode(); + } + /** * Render PDF * @@ -1806,7 +2107,7 @@ public function isProtestado() * @param bool $instrucoes * * @return string - * @throws \Exception + * @throws ValidationException */ public function renderPDF($print = false, $instrucoes = true) { @@ -1829,7 +2130,7 @@ public function renderPDF($print = false, $instrucoes = true) * @param bool $instrucoes * * @return string - * @throws \Throwable + * @throws Throwable */ public function renderHTML($print = false, $instrucoes = true) { @@ -1852,7 +2153,7 @@ public function copy() /** * On clone clean variables */ - function __clone() + public function __clone() { $this->campoLivre = null; $this->campoNossoNumero = null; @@ -1864,7 +2165,7 @@ function __clone() * Return Boleto Array. * * @return array - * @throws \Exception + * @throws ValidationException */ public function toArray() { @@ -1874,97 +2175,99 @@ public function toArray() $nosso_numero_boleto = $this->getNossoNumeroBoleto(); $linha_digitavel = $this->getLinhaDigitavel(); $codigo_barras = $this->getCodigoBarras(); - } catch (\Exception $e) {} + } catch (Exception $e) { + } + + $this->validarPix(); - return array_merge( - [ - 'linha_digitavel' => $linha_digitavel, - 'codigo_barras' => $codigo_barras, + return array_merge([ + 'linha_digitavel' => $linha_digitavel, + 'codigo_barras' => $codigo_barras, 'codigo_barras_inserido' => $this->getCodigoBarrasInserido(), 'beneficiario' => [ - 'nome' => $this->getBeneficiario()->getNome(), - 'endereco' => $this->getBeneficiario()->getEndereco(), - 'numero' => $this->getBeneficiario()->getNumero(), - 'complemento' => $this->getBeneficiario()->getComplemento(), - 'bairro' => $this->getBeneficiario()->getBairro(), - 'cep' => $this->getBeneficiario()->getCep(), - 'uf' => $this->getBeneficiario()->getUf(), - 'cidade' => $this->getBeneficiario()->getCidade(), - 'documento' => $this->getBeneficiario()->getDocumento(), - 'nome_documento' => $this->getBeneficiario()->getNomeDocumento(), - 'endereco2' => $this->getBeneficiario()->getCepCidadeUf(), + 'nome' => $this->getBeneficiario()->getNome(), + 'endereco' => $this->getBeneficiario()->getEndereco(), + 'numero' => $this->getBeneficiario()->getNumero(), + 'complemento' => $this->getBeneficiario()->getComplemento(), + 'bairro' => $this->getBeneficiario()->getBairro(), + 'cep' => $this->getBeneficiario()->getCep(), + 'uf' => $this->getBeneficiario()->getUf(), + 'cidade' => $this->getBeneficiario()->getCidade(), + 'documento' => $this->getBeneficiario()->getDocumento(), + 'nome_documento' => $this->getBeneficiario()->getNomeDocumento(), + 'endereco2' => $this->getBeneficiario()->getCepCidadeUf(), 'endereco_completo' => $this->getBeneficiario()->getEnderecoCompleto(), ], - 'logo_base64' => $this->getLogoBase64(), - 'logo' => $this->getLogo(), - 'logo_banco_base64' => $this->getLogoBancoBase64(), - 'logo_banco' => $this->getLogoBanco(), - 'codigo_banco' => $this->getCodigoBanco(), + 'logo_base64' => $this->getLogoBase64(), + 'logo' => $this->getLogo(), + 'logo_banco_base64' => $this->getLogoBancoBase64(), + 'logo_banco' => $this->getLogoBanco(), + 'codigo_banco' => $this->getCodigoBanco(), 'codigo_banco_com_dv' => $this->getCodigoBancoComDv(), - 'especie' => 'R$', - 'data_vencimento' => $this->getDataVencimento(), - 'data_processamento' => $this->getDataProcessamento(), - 'data_documento' => $this->getDataDocumento(), - 'data_desconto' => $this->getDataDesconto(), - 'valor' => Util::nReal($this->getValor(), 2, false), - 'desconto' => Util::nReal($this->getDesconto(), 2, false), - 'multa' => Util::nReal($this->getMulta(), 2, false), - 'juros' => Util::nReal($this->getJuros(), 2, false), - 'juros_apos' => $this->getJurosApos(), - 'dias_protesto' => $this->getDiasProtesto(), - 'sacador_avalista' => - $this->getSacadorAvalista() + 'especie' => 'R$', + 'data_vencimento' => $this->getDataVencimento(), + 'data_processamento' => $this->getDataProcessamento(), + 'data_documento' => $this->getDataDocumento(), + 'data_desconto' => $this->getDataDesconto(), + 'valor' => Util::nReal($this->getValor(), 2, false), + 'desconto' => Util::nReal($this->getDesconto(), 2, false), + 'multa' => Util::nReal($this->getMulta(), 2, false), + 'juros' => Util::nReal($this->getJuros(), 2, false), + 'juros_apos' => $this->getJurosApos(), + 'dias_protesto' => $this->getDiasProtesto(), + 'sacador_avalista' => $this->getSacadorAvalista() ? [ - 'nome' => $this->getSacadorAvalista()->getNome(), - 'endereco' => $this->getSacadorAvalista()->getEndereco(), - 'numero' => $this->getSacadorAvalista()->getNumero(), - 'complemento' => $this->getSacadorAvalista()->getComplemento(), - 'bairro' => $this->getSacadorAvalista()->getBairro(), - 'cep' => $this->getSacadorAvalista()->getCep(), - 'uf' => $this->getSacadorAvalista()->getUf(), - 'cidade' => $this->getSacadorAvalista()->getCidade(), - 'documento' => $this->getSacadorAvalista()->getDocumento(), - 'nome_documento' => $this->getSacadorAvalista()->getNomeDocumento(), - 'endereco2' => $this->getSacadorAvalista()->getCepCidadeUf(), + 'nome' => $this->getSacadorAvalista()->getNome(), + 'endereco' => $this->getSacadorAvalista()->getEndereco(), + 'numero' => $this->getSacadorAvalista()->getNumero(), + 'complemento' => $this->getSacadorAvalista()->getComplemento(), + 'bairro' => $this->getSacadorAvalista()->getBairro(), + 'cep' => $this->getSacadorAvalista()->getCep(), + 'uf' => $this->getSacadorAvalista()->getUf(), + 'cidade' => $this->getSacadorAvalista()->getCidade(), + 'documento' => $this->getSacadorAvalista()->getDocumento(), + 'nome_documento' => $this->getSacadorAvalista()->getNomeDocumento(), + 'endereco2' => $this->getSacadorAvalista()->getCepCidadeUf(), 'endereco_completo' => $this->getSacadorAvalista()->getEnderecoCompleto(), ] : [], 'pagador' => [ - 'nome' => $this->getPagador()->getNome(), - 'endereco' => $this->getPagador()->getEndereco(), - 'numero' => $this->getPagador()->getNumero(), - 'complemento' => $this->getPagador()->getComplemento(), - 'bairro' => $this->getPagador()->getBairro(), - 'cep' => $this->getPagador()->getCep(), - 'uf' => $this->getPagador()->getUf(), - 'cidade' => $this->getPagador()->getCidade(), - 'documento' => $this->getPagador()->getDocumento(), - 'nome_documento' => $this->getPagador()->getNomeDocumento(), - 'endereco2' => $this->getPagador()->getCepCidadeUf(), + 'nome' => $this->getPagador()->getNome(), + 'endereco' => $this->getPagador()->getEndereco(), + 'numero' => $this->getPagador()->getNumero(), + 'complemento' => $this->getPagador()->getComplemento(), + 'bairro' => $this->getPagador()->getBairro(), + 'cep' => $this->getPagador()->getCep(), + 'uf' => $this->getPagador()->getUf(), + 'cidade' => $this->getPagador()->getCidade(), + 'documento' => $this->getPagador()->getDocumento(), + 'nome_documento' => $this->getPagador()->getNomeDocumento(), + 'endereco2' => $this->getPagador()->getCepCidadeUf(), 'endereco_completo' => $this->getPagador()->getEnderecoCompleto(), ], - 'demonstrativo' => $this->getDescricaoDemonstrativo(), - 'instrucoes' => $this->getInstrucoes(), - 'instrucoes_impressao' => $this->getInstrucoesImpressao(), - 'local_pagamento' => $this->getLocalPagamento(), - 'numero' => $this->getNumero(), - 'numero_documento' => $this->getNumeroDocumento(), - 'numero_controle' => $this->getNumeroControle(), - 'agencia_codigo_beneficiario' => $this->getAgenciaCodigoBeneficiario(), - 'nosso_numero' => $nosso_numero, - 'nosso_numero_boleto' => $nosso_numero_boleto, - 'especie_doc' => $this->getEspecieDoc(), - 'especie_doc_cod' => $this->getEspecieDocCodigo(), - 'aceite' => $this->getAceite(), - 'carteira' => $this->getCarteira(), - 'carteira_nome' => $this->getCarteiraNome(), - 'uso_banco' => $this->getUsoBanco(), - 'status' => $this->getStatus(), + 'demonstrativo' => $this->getDescricaoDemonstrativo(), + 'instrucoes' => $this->getInstrucoes(), + 'instrucoes_impressao' => $this->getInstrucoesImpressao(), + 'local_pagamento' => $this->getLocalPagamento(), + 'numero' => $this->getNumero(), + 'numero_documento' => $this->getNumeroDocumento(), + 'numero_controle' => $this->getNumeroControle(), + 'agencia_codigo_beneficiario' => $this->getAgenciaCodigoBeneficiario(), + 'nosso_numero' => $nosso_numero, + 'nosso_numero_boleto' => $nosso_numero_boleto, + 'especie_doc' => $this->getEspecieDoc(), + 'especie_doc_cod' => $this->getEspecieDocCodigo(), + 'aceite' => $this->getAceite(), + 'carteira' => $this->getCarteira(), + 'carteira_nome' => $this->getCarteiraNome(), + 'uso_banco' => $this->getUsoBanco(), + 'status' => $this->getStatus(), 'mostrar_endereco_ficha_compensacao' => $this->getMostrarEnderecoFichaCompensacao(), - 'pix_qrcode' => $this->getPixQrCode(), - 'pix_txid' => $this->getPixTxid(), - ], $this->variaveis_adicionais - ); + 'pix_chave' => $this->getPixChave(), + 'pix_chave_tipo' => $this->getPixChaveTipo(), + 'pix_qrcode' => $this->getPixQrCode(), + 'pix_qrcode_image' => $this->getPixQrCodeBase64(), + 'pix_txid' => $this->getPixTxid(), + ], $this->variaveis_adicionais); } } - diff --git a/src/Boleto/Banco/Ailos.php b/src/Boleto/Banco/Ailos.php new file mode 100644 index 00000000..98c04fa5 --- /dev/null +++ b/src/Boleto/Banco/Ailos.php @@ -0,0 +1,180 @@ +addCampoObrigatorio('convenio', 'contaDv', 'agenciaDv'); + } + + /** + * Local de pagamento + * + * @var string + */ + protected $localPagamento = 'Pagável preferencialmente nas cooperativas do Sistema AILOS'; + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = self::COD_BANCO_AILOS; + /** + * Define as carteiras disponíveis para este banco + * + * @var array + */ + protected $carteiras = ['1']; + /** + * Espécie do documento, coódigo para remessa + * + * @var string + */ + protected $especiesCodigo = [ + 'DM' => '02', // Duplicata Mercantil por Indicação + 'DS' => '04', // Duplicata Serviço por Indicação + ]; + /** + * Se possui registro o boleto (tipo = 1 com registro e 3 sem registro) + * + * @var bool + */ + protected $registro = true; + + /** + * Define o número do convênio (6 dígitos. Iniciar na primeira posição e deixar as demais em branco). + * + * @var string + */ + protected $convenio; + + /** + * Define se possui ou não registro + * + * @param bool $registro + * @return Ailos + */ + public function setComRegistro($registro) + { + $this->registro = $registro; + return $this; + } + /** + * Retorna se é com registro. + * + * @return bool + */ + public function isComRegistro() + { + return $this->registro; + } + /** + * Seta o codigo do cliente. + * + * @param mixed $convenio + * + * @return Ailos + */ + public function setConvenio($convenio) + { + $this->convenio = $convenio; + + return $this; + } + /** + * Retorna o codigo do cliente. + * + * @return string + */ + public function getConvenio() + { + return $this->convenio; + } + /** + * Retorna o campo Agência/Beneficiário do boleto + * + * @return string + */ + public function getAgenciaCodigoBeneficiario() + { + $conta = $this->getConta(); + $contaDV = $this->getContaDv(); + + if (!empty($contaDV) || $contaDV == '0') { + $conta .= '-' . $contaDV; + } + + $agenciaDV = $this->getAgencia() . '-' . $this->getAgenciaDv(); + + return $agenciaDV . '/' . $conta; + } + /** + * Gera o Nosso Número. + * + * @return string + */ + protected function gerarNossoNumero() + { + $conta = Util::numberFormatGeral($this->getConta() . $this->getContaDv(), 8); + $numero_boleto = Util::numberFormatGeral($this->getNumero(), 9); + $nossoNumero = $conta . $numero_boleto; + return $nossoNumero; + } + /** + * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. + * + * @return string + */ + public function getNossoNumeroBoleto() + { + return $this->getNossoNumero(); + } + /** + * Método para gerar o código da posição de 20 a 44 + * + * @return string + * @throws ValidationException + */ + protected function getCampoLivre() + { + if ($this->campoLivre) { + return $this->campoLivre; + } + + $campoLivre = Util::numberFormatGeral($this->getConvenio(), 6); + $campoLivre .= $this->getNossoNumero(); + $campoLivre .= Util::numberFormatGeral($this->getCarteira(), 2); + + return $this->campoLivre .= $campoLivre; + } + + /** + * Método onde qualquer boleto deve extender para gerar o código da posição de 20 a 44 + * + * @param $campoLivre + * + * @return array + */ + public static function parseCampoLivre($campoLivre) + { + return [ + 'agenciaDv' => null, + 'contaCorrenteDv' => null, + 'convenio' => substr($campoLivre, 20, 6), + 'carteira' => substr($campoLivre, -2), + 'nossoNumero' => substr($campoLivre, 26, 17), + 'nossoNumeroDv' => null, + 'nossoNumeroFull' => substr($campoLivre, 26, 17), + 'agencia' => null, + 'contaCorrente' => substr($campoLivre, 26, 8), + ]; + } +} diff --git a/src/Boleto/Banco/Bancoob.php b/src/Boleto/Banco/Bancoob.php index 7824f802..73b12469 100644 --- a/src/Boleto/Banco/Bancoob.php +++ b/src/Boleto/Banco/Bancoob.php @@ -1,10 +1,11 @@ '25', //Cédula de Produto Rural, 'O' => '99', //Outros, //Equivalente no CNAB400 que não existe no CNAB240 - 'W' => '100', //Warrant CNAB400 + 'W' => '100', //Warrant CNAB400 ]; + /** * Define o número do convênio (4, 6 ou 7 caracteres) * * @var string */ protected $convenio; + /** * Define o número do convênio. Sempre use string pois a quantidade de caracteres é validada. * - * @param string $convenio + * @param string $convenio * @return Bancoob */ public function setConvenio($convenio) { $this->convenio = $convenio; + return $this; } + /** * Retorna o número do convênio * @@ -91,10 +98,10 @@ public function getConvenio() { return $this->convenio; } + /** * Gera o Nosso Número. * - * @throws \Exception * @return string */ protected function gerarNossoNumero() @@ -102,6 +109,7 @@ protected function gerarNossoNumero() return Util::numberFormatGeral($this->getNumero(), 7) . CalculoDV::bancoobNossoNumero($this->getAgencia(), $this->getConvenio(), $this->getNumero()); } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -111,11 +119,11 @@ public function getNossoNumeroBoleto() { return substr_replace($this->getNossoNumero(), '-', -1, 0); } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception */ protected function getCampoLivre() { @@ -142,32 +150,32 @@ protected function getCampoLivre() * * @return array */ - static public function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'codigoCliente' => null, - 'agenciaDv' => null, - 'contaCorrente' => null, + 'codigoCliente' => null, + 'agenciaDv' => null, + 'contaCorrente' => null, 'contaCorrenteDv' => null, - 'carteira' => substr($campoLivre, 0, 1), - 'agencia' => substr($campoLivre, 1, 4), - 'modalidade' => substr($campoLivre, 5, 2), - 'convenio' => substr($campoLivre, 7, 7), - 'nossoNumero' => substr($campoLivre, 14, 7), - 'nossoNumeroDv' => substr($campoLivre, 21, 1), + 'carteira' => substr($campoLivre, 0, 1), + 'agencia' => substr($campoLivre, 1, 4), + 'modalidade' => substr($campoLivre, 5, 2), + 'convenio' => substr($campoLivre, 7, 7), + 'nossoNumero' => substr($campoLivre, 14, 7), + 'nossoNumeroDv' => substr($campoLivre, 21, 1), 'nossoNumeroFull' => substr($campoLivre, 14, 8), - 'parcela' => substr($campoLivre, 22, 3), + 'parcela' => substr($campoLivre, 22, 3), ]; } - /** * Agência/Código do Beneficiário: Informar o prefixo da agência e o código de associado/cliente. * Estes dados constam na planilha "Capa" deste arquivo. O código de cliente não deve ser * confundido com o número da conta corrente, pois são códigos diferentes. * @return string */ - public function getAgenciaCodigoBeneficiario(){ - return sprintf('%s / %s',$this->getAgencia(), $this->getConvenio()); + public function getAgenciaCodigoBeneficiario() + { + return sprintf('%s / %s', $this->getAgencia(), $this->getConvenio()); } - } diff --git a/src/Boleto/Banco/Banrisul.php b/src/Boleto/Banco/Banrisul.php index 4f8573b1..2babcf15 100644 --- a/src/Boleto/Banco/Banrisul.php +++ b/src/Boleto/Banco/Banrisul.php @@ -2,10 +2,11 @@ namespace VinicciusGuedes\LaravelCnab\Boleto\Banco; -use VinicciusGuedes\LaravelCnab\Boleto\AbstractBoleto; +use VinicciusGuedes\LaravelCnab\Util; use VinicciusGuedes\LaravelCnab\CalculoDV; +use VinicciusGuedes\LaravelCnab\Boleto\AbstractBoleto; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Util; class Banrisul extends AbstractBoleto implements BoletoContract { @@ -72,20 +73,21 @@ class Banrisul extends AbstractBoleto implements BoletoContract protected $codigoCliente; /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { if ($this->getDiasProtesto() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } $baixaAutomatica = (int) $baixaAutomatica; $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + return $this; } @@ -99,8 +101,10 @@ protected function gerarNossoNumero() $numero_boleto = $this->getNumero(); $nossoNumero = Util::numberFormatGeral($numero_boleto, 8) . CalculoDV::banrisulNossoNumero(Util::numberFormatGeral($numero_boleto, 8)); + return $nossoNumero; } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -110,11 +114,12 @@ public function getNossoNumeroBoleto() { return substr_replace($this->getNossoNumero(), '-', -2, 0); } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -139,13 +144,14 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'carteira' => substr($campoLivre, 0, 1), - 'agencia' => substr($campoLivre, 2, 4), - 'contaCorrente' => substr($campoLivre, 6, 7), - 'nossoNumero' => substr($campoLivre, 13, 8), - 'nossoNumeroDv' => null, + 'carteira' => substr($campoLivre, 0, 1), + 'agencia' => substr($campoLivre, 2, 4), + 'contaCorrente' => substr($campoLivre, 6, 7), + 'nossoNumero' => substr($campoLivre, 13, 8), + 'nossoNumeroDv' => null, 'nossoNumeroFull' => substr($campoLivre, 13, 8), ]; } @@ -183,4 +189,4 @@ public function getAgenciaCodigoBeneficiario() { return $this->getCodigoCliente(); } -} +} \ No newline at end of file diff --git a/src/Boleto/Banco/Bb.php b/src/Boleto/Banco/Bb.php index 46e7dd5d..676f09be 100644 --- a/src/Boleto/Banco/Bb.php +++ b/src/Boleto/Banco/Bb.php @@ -1,10 +1,12 @@ setCamposObrigatorios('numero', 'convenio', 'carteira'); } + /** * Código do banco * * @var string */ protected $codigoBanco = self::COD_BANCO_BB; + /** * Define as carteiras disponíveis para este banco * * @var array */ protected $carteiras = ['11', '12', '15', '17', '18', '31', '51']; + /** * Espécie do documento, coódigo para remessa * * @var string */ protected $especiesCodigo240 = [ - 'CH' => '01', // Cheque - 'DM' => '02', // Duplicata Mercantil 'DM' => '02', // Duplicata Mercantil - 'DS' => '04', // Duplicata de Serviço 'DS' => '04', // Duplicata de Serviço - 'DR' => '06', // Duplicata Rural 'DR' => '06', // Duplicata Rural - 'LC' => '07', // Letra de Cambio 'LC' => '07', // Letra de Cambio - 'NP' => '12', // Nota Provisoria 'NP' => '12', // Nota Provisoria - 'NS' => '16', // Nota de Seguro 'NS' => '16', // Nota de Seguro + 'CH' => '01', // Cheque + 'DM' => '02', // Duplicata Mercantil 'DM' => '02', // Duplicata Mercantil + 'DS' => '04', // Duplicata de Serviço 'DS' => '04', // Duplicata de Serviço + 'DR' => '06', // Duplicata Rural 'DR' => '06', // Duplicata Rural + 'LC' => '07', // Letra de Cambio 'LC' => '07', // Letra de Cambio + 'NP' => '12', // Nota Provisoria 'NP' => '12', // Nota Provisoria + 'NS' => '16', // Nota de Seguro 'NS' => '16', // Nota de Seguro 'REC' => '17', // Recibo 'REC' => '17', // Recibo - 'ND' => '19', // Nota de Débito 'ND' => '19', // Nota de Débito - 'AS' => '20', // Apolice de Seguro 'AS' => '20', // Apolice de Seguro - 'W' => '26', // Warrant 'W' => '26', // Warrant + 'ND' => '19', // Nota de Débito 'ND' => '19', // Nota de Débito + 'AS' => '20', // Apolice de Seguro 'AS' => '20', // Apolice de Seguro + 'W' => '26', // Warrant 'W' => '26', // Warrant 'DAE' => '27', // Divida Ativa de Estado 'DAE' => '27', // Divida Ativa de Estado 'DAM' => '28', // Divida Ativa de Municipio 'DAM' => '28', // Divida Ativa de Municipio - 'DAU' => '29' // Divida Ativa União 'DAU' => '29' // Divida Ativa União + 'DAU' => '29', // Divida Ativa União 'DAU' => '29' // Divida Ativa União ]; + /** * Espécie do documento, coódigo para remessa * @@ -64,14 +70,16 @@ public function __construct(array $params = []) 'AS' => '15', // Apolice de Seguro 'DAE' => '25', // Divida Ativa de Estado 'DAM' => '26', // Divida Ativa de Municipio - 'DAU' => '27' // Divida Ativa União + 'DAU' => '27', // Divida Ativa União ]; + /** * Define o número do convênio (4, 6 ou 7 caracteres) * * @var string */ protected $convenio; + /** * Defgine o numero da variação da carteira. * @@ -86,8 +94,8 @@ public function __construct(array $params = []) */ public function getAgenciaCodigoBeneficiario() { - $agencia = $this->getAgencia() . '-' . CalculoDV::bbAgencia($this->getAgencia()); - $codigoCliente = $this->getConta() . '-' . CalculoDV::bbContaCorrente($this->getConta()); + $agencia = $this->getAgencia() . '-' . (! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); + $codigoCliente = $this->getConta() . '-' . (! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); return sprintf('%s / %s', $agencia, $codigoCliente); } @@ -95,14 +103,16 @@ public function getAgenciaCodigoBeneficiario() /** * Define o número do convênio. Sempre use string pois a quantidade de caracteres é validada. * - * @param string $convenio + * @param string $convenio * @return Bb */ public function setConvenio($convenio) { $this->convenio = $convenio; + return $this; } + /** * Retorna o número do convênio * @@ -112,17 +122,20 @@ public function getConvenio() { return $this->convenio; } + /** * Define o número da variação da carteira, para saber quando utilizar o nosso numero de 17 posições. * - * @param string $variacao_carteira + * @param string $variacao_carteira * @return Bb */ public function setVariacaoCarteira($variacao_carteira) { $this->variacao_carteira = $variacao_carteira; + return $this; } + /** * Retorna o número da variacao de carteira * @@ -132,35 +145,38 @@ public function getVariacaoCarteira() { return $this->variacao_carteira; } + /** * Gera o Nosso Número. * - * @throws \Exception * @return string + * @throws ValidationException */ protected function gerarNossoNumero() { $convenio = $this->getConvenio(); $numero_boleto = $this->getNumero(); switch (strlen($convenio)) { - case 4: - $numero = Util::numberFormatGeral($convenio, 4) . Util::numberFormatGeral($numero_boleto, 7); - break; - case 6: - if (in_array($this->getCarteira(), ['16', '18']) && $this->getVariacaoCarteira() == 17) { - $numero = Util::numberFormatGeral($numero_boleto, 17); - } else { - $numero = Util::numberFormatGeral($convenio, 6) . Util::numberFormatGeral($numero_boleto, 5); - } - break; - case 7: - $numero = Util::numberFormatGeral($convenio, 7) . Util::numberFormatGeral($numero_boleto, 10); - break; - default: - throw new \Exception('O código do convênio precisa ter 4, 6 ou 7 dígitos!'); + case 4: + $numero = Util::numberFormatGeral($convenio, 4) . Util::numberFormatGeral($numero_boleto, 7); + break; + case 6: + if (in_array($this->getCarteira(), ['16', '18']) && $this->getVariacaoCarteira() == 17) { + $numero = Util::numberFormatGeral($numero_boleto, 17); + } else { + $numero = Util::numberFormatGeral($convenio, 6) . Util::numberFormatGeral($numero_boleto, 5); + } + break; + case 7: + $numero = Util::numberFormatGeral($convenio, 7) . Util::numberFormatGeral($numero_boleto, 10); + break; + default: + throw new ValidationException('O código do convênio precisa ter 4, 6 ou 7 dígitos!'); } + return $numero; } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -169,13 +185,15 @@ protected function gerarNossoNumero() public function getNossoNumeroBoleto() { $nn = $this->getNossoNumero() . CalculoDV::bbNossoNumero($this->getNossoNumero()); + return strlen($nn) < 17 ? substr_replace($nn, '-', -1, 0) : $nn; } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -188,17 +206,17 @@ protected function getCampoLivre() if ($length == 6 && in_array($this->getCarteira(), ['16', '18']) && Util::numberFormatGeral($this->getVariacaoCarteira(), 3) == '017') { return $this->campoLivre = Util::numberFormatGeral($this->getConvenio(), 6) . $nossoNumero . '21'; } else { - throw new \Exception('Só é possível criar um boleto com mais de 10 dígitos no nosso número quando a carteira é 21 e o convênio possuir 6 dígitos.'); + throw new ValidationException('Só é possível criar um boleto com mais de 10 dígitos no nosso número quando a carteira é 21 e o convênio possuir 6 dígitos.'); } } switch ($length) { - case 4: - case 6: - return $this->campoLivre = $nossoNumero . Util::numberFormatGeral($this->getAgencia(), 4) . Util::numberFormatGeral($this->getConta(), 8) . Util::numberFormatGeral($this->getCarteira(), 2); - case 7: - return $this->campoLivre = '000000' . $nossoNumero . Util::numberFormatGeral($this->getCarteira(), 2); + case 4: + case 6: + return $this->campoLivre = $nossoNumero . Util::numberFormatGeral($this->getAgencia(), 4) . Util::numberFormatGeral($this->getConta(), 8) . Util::numberFormatGeral($this->getCarteira(), 2); + case 7: + return $this->campoLivre = '000000' . $nossoNumero . Util::numberFormatGeral($this->getCarteira(), 2); } - throw new \Exception('O código do convênio precisa ter 4, 6 ou 7 dígitos!'); + throw new ValidationException('O código do convênio precisa ter 4, 6 ou 7 dígitos!'); } /** @@ -208,32 +226,33 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { $convenio = substr($campoLivre, 0, 6); $nossoNumero = substr($campoLivre, 6, 5); if ($convenio == '000000') { $convenio = substr($campoLivre, 6, 7); $nossoNumero = substr($campoLivre, 13, 10); } - if ($convenio == '0000000' && in_array(substr($campoLivre, -2), ['16', '18']) ) { + if ($convenio == '0000000' && in_array(substr($campoLivre, -2), ['16', '18'])) { $convenio = substr($campoLivre, 0, 4); $nossoNumero = substr($campoLivre, 4, 7); } - if ($convenio == '0000000' && !in_array(substr($campoLivre, -2), ['16', '18']) ) { + if ($convenio == '0000000' && ! in_array(substr($campoLivre, -2), ['16', '18'])) { $convenio = null; $nossoNumero = substr($campoLivre, 0, 17); } return [ - 'codigoCliente' => null, - 'agencia' => null, - 'agenciaDv' => null, - 'contaCorrente' => null, + 'codigoCliente' => null, + 'agencia' => null, + 'agenciaDv' => null, + 'contaCorrente' => null, 'contaCorrenteDv' => null, - 'carteira' => substr($campoLivre, -2), - 'convenio' => $convenio, - 'nossoNumero' => $nossoNumero, - 'nossoNumeroDv' => null, + 'carteira' => substr($campoLivre, -2), + 'convenio' => $convenio, + 'nossoNumero' => $nossoNumero, + 'nossoNumeroDv' => null, 'nossoNumeroFull' => $nossoNumero, ]; } diff --git a/src/Boleto/Banco/Bnb.php b/src/Boleto/Banco/Bnb.php index e048b542..a06a6272 100644 --- a/src/Boleto/Banco/Bnb.php +++ b/src/Boleto/Banco/Bnb.php @@ -1,10 +1,12 @@ '', ]; + /** * Define as carteiras disponíveis para este banco * * @var array */ protected $carteiras = ['21', '31', '41']; + /** * Espécie do documento, coódigo para remessa * @@ -45,23 +50,25 @@ class Bnb extends AbstractBoleto implements BoletoContract 'NP' => '02', 'CH' => '03', 'CN' => '04', - 'RC' => '05' + 'RC' => '05', ]; + /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Bnb + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { if ($this->getDiasProtesto() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } $baixaAutomatica = (int) $baixaAutomatica; $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + return $this; } @@ -69,13 +76,13 @@ public function setDiasBaixaAutomatica($baixaAutomatica) * Gera o Nosso Número. * * @return string - * @throws \Exception + * @throws ValidationException */ protected function gerarNossoNumero() { - $numero_boleto = $this->getNumero(); - return Util::numberFormatGeral($numero_boleto, 7) . CalculoDV::bnbNossoNumero($this->getNumero()); + return Util::numberFormatGeral($this->getNumero(), 7) . CalculoDV::bnbNossoNumero($this->getNumero()); } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -90,7 +97,7 @@ public function getNossoNumeroBoleto() * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -100,7 +107,7 @@ protected function getCampoLivre() $campoLivre = Util::numberFormatGeral($this->getAgencia(), 4); $campoLivre .= Util::numberFormatGeral($this->getConta(), 7); - $campoLivre .= $this->getContaDv() ?: CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta()); + $campoLivre .= ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta()); $campoLivre .= $this->getNossoNumero(); $campoLivre .= Util::numberFormatGeral($this->getCarteira(), 2); $campoLivre .= '000'; @@ -115,18 +122,19 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'codigoCliente' => null, - 'convenio' => null, - 'agenciaDv' => null, - 'agencia' => substr($campoLivre, 0, 4), - 'contaCorrente' => substr($campoLivre, 4, 7), + 'codigoCliente' => null, + 'convenio' => null, + 'agenciaDv' => null, + 'agencia' => substr($campoLivre, 0, 4), + 'contaCorrente' => substr($campoLivre, 4, 7), 'contaCorrenteDv' => substr($campoLivre, 11, 1), - 'nossoNumero' => substr($campoLivre, 12, 7), - 'nossoNumeroDv' => substr($campoLivre, 19, 1), + 'nossoNumero' => substr($campoLivre, 12, 7), + 'nossoNumeroDv' => substr($campoLivre, 19, 1), 'nossoNumeroFull' => substr($campoLivre, 12, 8), - 'carteira' => substr($campoLivre, 20, 2), + 'carteira' => substr($campoLivre, 20, 2), ]; } } diff --git a/src/Boleto/Banco/Bradesco.php b/src/Boleto/Banco/Bradesco.php index 3510b797..b1278c83 100644 --- a/src/Boleto/Banco/Bradesco.php +++ b/src/Boleto/Banco/Bradesco.php @@ -1,13 +1,15 @@ Com registro | '09' => Com registro | '06' => Sem Registro | '21' => Com Registro - Pagável somente no Bradesco | '22' => Sem Registro - Pagável somente no Bradesco | '25' => Sem Registro - Emissão na Internet | '26' => Com Registro - Emissão na Internet @@ -22,6 +25,7 @@ class Bradesco extends AbstractBoleto implements BoletoContract * @var array */ protected $carteiras = ['02', '04', '09', '21', '26']; + /** * Trata-se de código utilizado para identificar mensagens especificas ao cedente, sendo * que o mesmo consta no cadastro do Banco, quando não houver código cadastrado preencher @@ -30,6 +34,7 @@ class Bradesco extends AbstractBoleto implements BoletoContract * @var int */ protected $cip = '000'; + /** * Código do cliente. * @@ -42,9 +47,10 @@ class Bradesco extends AbstractBoleto implements BoletoContract * @var array */ public $variaveis_adicionais = [ - 'cip' => '000', + 'cip' => '000', 'mostra_cip' => true, ]; + /** * Espécie do documento, coódigo para remessa * @@ -62,6 +68,7 @@ class Bradesco extends AbstractBoleto implements BoletoContract 'BP' => '30', //Boleto de Proposta 'O' => '99', //Outros, ]; + /** * Espécie do documento, coódigo para remessa * @@ -80,12 +87,14 @@ class Bradesco extends AbstractBoleto implements BoletoContract 'BDP' => '32', // Boleto de Proposta 'O' => '99', // Outros ]; + /** * Mostrar o endereço do beneficiário abaixo da razão e CNPJ na ficha de compensação * - * @var boolean + * @var bool */ protected $mostrarEnderecoFichaCompensacao = true; + /** * Gera o Nosso Número. * @@ -98,32 +107,34 @@ protected function gerarNossoNumero() } /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { if ($this->getDiasProtesto() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } $baixaAutomatica = (int) $baixaAutomatica; $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + return $this; } /** - * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. + * Método que retorna o nosso número usado no boleto. Alguns bancos possuem algumas diferenças. * * @return string */ public function getNossoNumeroBoleto() { - return Util::numberFormatGeral($this->getCarteira(), 2) . ' / ' . substr_replace($this->getNossoNumero(), '-', -1, 0); + return Util::numberFormatGeral($this->getCarteira(), 2) . ' / ' . substr_replace($this->getNossoNumero(), '-', -1, 0); } + /** * Método para gerar o código da posição de 20 a 44 * @@ -151,30 +162,32 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'agenciaDv' => null, + 'convenio' => null, + 'agenciaDv' => null, 'contaCorrenteDv' => null, - 'agencia' => substr($campoLivre, 0, 4), - 'carteira' => substr($campoLivre, 4, 2), - 'nossoNumero' => substr($campoLivre, 6, 11), - 'nossoNumeroDv' => null, + 'agencia' => substr($campoLivre, 0, 4), + 'carteira' => substr($campoLivre, 4, 2), + 'nossoNumero' => substr($campoLivre, 6, 11), + 'nossoNumeroDv' => null, 'nossoNumeroFull' => substr($campoLivre, 6, 11), - 'contaCorrente' => substr($campoLivre, 17, 7), + 'contaCorrente' => substr($campoLivre, 17, 7), ]; } /** * Define o campo CIP do boleto * - * @param int $cip + * @param int $cip * @return Bradesco */ public function setCip($cip) { $this->cip = $cip; $this->variaveis_adicionais['cip'] = $this->getCip(); + return $this; } diff --git a/src/Boleto/Banco/Btg.php b/src/Boleto/Banco/Btg.php new file mode 100644 index 00000000..31de4c9f --- /dev/null +++ b/src/Boleto/Banco/Btg.php @@ -0,0 +1,165 @@ + '01', + 'DS' => '02', + 'NP' => '03', + 'NS' => '04', + 'REC' => '05', + 'LC' => '06', + 'FC' => '07', + 'CAR' => '08', + 'CT' => '09', + 'ME' => '12', + 'ND' => '13', + 'CDA' => '15', + 'EC' => '16', + 'CPS' => '17', + 'FT' => '31', + 'BA' => '33', + 'O' => '99', + ]; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Gera o Nosso Número. + * + * @return string + */ + protected function gerarNossoNumero() + { + return Util::numberFormatGeral($this->getNumero(), 11) . CalculoDV::btgNossoNumero($this->getCarteira(), $this->getNumero()); + } + + /** + * Método que retorna o nosso número usado no boleto. alguns bancos possuem algumas diferenças. + * + * @return string + */ + public function getNossoNumeroBoleto() + { + return substr_replace($this->getNossoNumero(), '-', -1, 0); + } + + /** + * Método para gerar o código da posição de 20 a 44 + * + * @return string + */ + protected function getCampoLivre() + { + if ($this->campoLivre) { + return $this->campoLivre; + } + + $campoLivre = Util::numberFormatGeral($this->getAgencia(), 4); + $campoLivre .= Util::numberFormatGeral($this->getCarteira(), 2); + $campoLivre .= Util::numberFormatGeral(substr($this->getNossoNumero(), -11), 11); + $campoLivre .= Util::numberFormatGeral($this->getConta(), 7); + $campoLivre .= '0'; + + return $this->campoLivre = $campoLivre; + } + + /** + * Método onde qualquer boleto deve extender para gerar o código da posição de 20 a 44 + * + * @param $campoLivre + * + * @return array + */ + public static function parseCampoLivre($campoLivre) + { + return [ + 'convenio' => null, + 'agenciaDv' => null, + 'codigoCliente' => substr($campoLivre, 0, 12), + 'carteira' => substr($campoLivre, 22, 2), + 'nossoNumero' => substr($campoLivre, 12, 10), + 'nossoNumeroDv' => null, + 'nossoNumeroFull' => substr($campoLivre, 12, 10), + 'agencia' => null, + 'contaCorrente' => null, + 'contaCorrenteDv' => null, + ]; + } + + /** + * Retorna o codigo do cliente. + * + * @return mixed + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return Btg + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return string + */ + public function getAgenciaCodigoBeneficiario() + { + return sprintf('%04s/%012s', $this->getAgencia() ?: 1, $this->getCodigoCliente()); + } +} diff --git a/src/Boleto/Banco/C6.php b/src/Boleto/Banco/C6.php new file mode 100644 index 00000000..184e8f58 --- /dev/null +++ b/src/Boleto/Banco/C6.php @@ -0,0 +1,164 @@ +setCamposObrigatorios('codigoCliente'); + } + + /** + * Local de pagamento + * + * @var string + */ + protected $localPagamento = 'Pagável em canais eletrônicos, agências ou correspondentes'; + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = self::COD_BANCO_C6; + + /** + * Define as carteiras disponíveis para este banco + * + * @var array + */ + protected $carteiras = ['10', '20', '30', '40', '60']; + + /** + * Espécie do documento, coódigo para remessa + * + * @var string + */ + protected $especiesCodigo = [ + 'DM' => '01', + 'DS' => '02', + 'NP' => '03', + 'NS' => '04', + 'REC' => '05', + 'LC' => '06', + 'FC' => '07', + 'CAR' => '08', + 'CT' => '09', + 'ME' => '12', + 'ND' => '13', + 'CDA' => '15', + 'EC' => '16', + 'CPS' => '17', + 'FT' => '31', + 'BA' => '33', + 'O' => '99', + ]; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Gera o Nosso Número. + * + * @return string + */ + protected function gerarNossoNumero() + { + return Util::numberFormatGeral($this->getNumero(), 11) . CalculoDV::c6NossoNumero($this->getCarteira(), $this->getNumero()); + } + + /** + * Método que retorna o nosso número usado no boleto. alguns bancos possuem algumas diferenças. + * + * @return string + */ + public function getNossoNumeroBoleto() + { + return substr($this->getNossoNumero(), 1, 10); + } + + /** + * Método para gerar o código da posição de 20 a 44 + * + * @return string + */ + protected function getCampoLivre() + { + if ($this->campoLivre) { + return $this->campoLivre; + } + + $campoLivre = Util::numberFormatGeral($this->getCodigoCliente(), 12); + $campoLivre .= Util::numberFormatGeral(substr($this->getNossoNumero(), 1, 10), 10); + $campoLivre .= Util::numberFormatGeral($this->getCarteira(), 2); + $campoLivre .= in_array(((int) $this->getCarteira()), [10, 30, 60]) ? 3 : 4; + + return $this->campoLivre = $campoLivre; + } + + /** + * Método onde qualquer boleto deve extender para gerar o código da posição de 20 a 44 + * + * @param $campoLivre + * + * @return array + */ + public static function parseCampoLivre($campoLivre) + { + return [ + 'convenio' => null, + 'agenciaDv' => null, + 'codigoCliente' => substr($campoLivre, 0, 12), + 'carteira' => substr($campoLivre, 22, 2), + 'nossoNumero' => substr($campoLivre, 12, 10), + 'nossoNumeroDv' => null, + 'nossoNumeroFull' => substr($campoLivre, 12, 10), + 'agencia' => null, + 'contaCorrente' => null, + 'contaCorrenteDv' => null, + ]; + } + + /** + * Retorna o codigo do cliente. + * + * @return mixed + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return C6 + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return string + */ + public function getAgenciaCodigoBeneficiario() + { + return sprintf('%04s/%012s', $this->getAgencia() ?: 1, $this->getCodigoCliente()); + } +} diff --git a/src/Boleto/Banco/Caixa.php b/src/Boleto/Banco/Caixa.php index d0327a84..fecc8e5b 100644 --- a/src/Boleto/Banco/Caixa.php +++ b/src/Boleto/Banco/Caixa.php @@ -1,12 +1,14 @@ '05', 'LC' => '06', ]; + /** * Codigo do cliente junto ao banco. * * @var string */ protected $codigoCliente; + /** - * Seta o codigo do cliente. + * Seta o código do cliente. * * @param mixed $codigoCliente * - * @return $this + * @return Caixa */ public function setCodigoCliente($codigoCliente) { @@ -57,6 +63,7 @@ public function setCodigoCliente($codigoCliente) return $this; } + /** * Retorna o codigo do cliente. * @@ -66,6 +73,7 @@ public function getCodigoCliente() { return $this->codigoCliente; } + /** * Retorna o codigo do cliente como se fosse a conta * ja que a caixa não faz uso da conta para nada. @@ -80,8 +88,8 @@ public function getConta() /** * Gera o Nosso Número. * - * @throws \Exception * @return string + * @throws ValidationException */ protected function gerarNossoNumero() { @@ -95,8 +103,10 @@ protected function gerarNossoNumero() // As 15 próximas posições no nosso número são a critério do beneficiário, utilizando o sequencial // Depois, calcula-se o código verificador por módulo 11 $numero = $carteira . Util::numberFormatGeral($numero_boleto, 15); + return $numero; } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -111,27 +121,29 @@ public function getNossoNumeroBoleto() * Na CEF deve retornar agência (sem o DV) / código beneficiário (com DV) * @return [type] [description] */ - public function getAgenciaCodigoBeneficiario(){ + public function getAgenciaCodigoBeneficiario() + { return $this->getAgencia() . ' / ' . - $this->getCodigoCliente() . '-' . - Util::modulo11($this->getCodigoCliente()); + $this->getCodigoCliente() . '-' . + Util::modulo11($this->getCodigoCliente()); } /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { if ($this->getDiasProtesto() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } $baixaAutomatica = (int) $baixaAutomatica; $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + return $this; } @@ -139,7 +151,7 @@ public function setDiasBaixaAutomatica($baixaAutomatica) * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -161,6 +173,7 @@ protected function getCampoLivre() $campoLivre .= substr($nossoNumero, 1, 1); $campoLivre .= substr($nossoNumero, 8, 9); $campoLivre .= Util::modulo11($campoLivre); + return $this->campoLivre = $campoLivre; } @@ -171,18 +184,19 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'agencia' => null, - 'agenciaDv' => null, - 'contaCorrente' => null, + 'convenio' => null, + 'agencia' => null, + 'agenciaDv' => null, + 'contaCorrente' => null, 'contaCorrenteDv' => null, - 'codigoCliente7' => substr($campoLivre, 0, 7), - 'codigoCliente' => substr($campoLivre, 0, 6), - 'carteira' => substr($campoLivre, 10, 1), - 'nossoNumero' => substr($campoLivre, 7, 3) . substr($campoLivre, 11, 3) . substr($campoLivre, 15, 8), - 'nossoNumeroDv' => substr($campoLivre, 23, 1), + 'codigoCliente7' => substr($campoLivre, 0, 7), + 'codigoCliente' => substr($campoLivre, 0, 6), + 'carteira' => substr($campoLivre, 10, 1), + 'nossoNumero' => substr($campoLivre, 7, 3) . substr($campoLivre, 11, 3) . substr($campoLivre, 15, 8), + 'nossoNumeroDv' => substr($campoLivre, 23, 1), 'nossoNumeroFull' => substr($campoLivre, 7, 3) . substr($campoLivre, 11, 3) . substr($campoLivre, 15, 8), ]; } diff --git a/src/Boleto/Banco/Cresol.php b/src/Boleto/Banco/Cresol.php new file mode 100644 index 00000000..80aac1ea --- /dev/null +++ b/src/Boleto/Banco/Cresol.php @@ -0,0 +1,176 @@ + '000', + 'mostra_cip' => true, + ]; + + /** + * Espécie do documento, código para remessa + * + * @var string + */ + protected $especiesCodigo400 = [ + 'DM' => '01', // Duplicata Mercantil + 'NP' => '02', // Nota Promissória + 'NS' => '03', // Nota de Seguro + 'CS' => '04', // Cobrança Seriada + 'RC' => '05', // Recibo + 'LC' => '10', // Letra de Câmbio + 'ND' => '11', // Nota de Débito + 'DS' => '12', // Duplicata de Serviço + 'CC' => '31', // Cartão de Crédito + 'BDP' => '32', // Boleto de Proposta + 'O' => '99', // Outros + ]; + + /** + * Mostrar o endereço do beneficiário abaixo da razão e CNPJ na ficha de compensação + * + * @var bool + */ + protected $mostrarEnderecoFichaCompensacao = true; + + /** + * Gera o Nosso Número. + * + * @return string + */ + protected function gerarNossoNumero() + { + return Util::numberFormatGeral($this->getNumero(), 11) + . CalculoDV::cresolNossoNumero($this->getCarteira(), $this->getNumero()); + } + + /** + * Seta dias para baixa automática + * + * @param int $baixaAutomatica + * + * @return $this + * @throws \Exception + */ + public function setDiasBaixaAutomatica($baixaAutomatica) + { + if ($this->getDiasProtesto() > 0) { + throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + } + $baixaAutomatica = (int) $baixaAutomatica; + $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + + return $this; + } + + /** + * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. + * + * @return string + */ + public function getNossoNumeroBoleto() + { + return Util::numberFormatGeral($this->getCarteira(), 2) . ' / ' . substr_replace($this->getNossoNumero(), '-', -1, 0); + } + + /** + * Método para gerar o código da posição de 20 a 44 + * + * @return string + */ + protected function getCampoLivre() + { + if ($this->campoLivre) { + return $this->campoLivre; + } + + $campoLivre = Util::numberFormatGeral($this->getAgencia(), 4); + $campoLivre .= Util::numberFormatGeral($this->getCarteira(), 2); + $campoLivre .= Util::numberFormatGeral($this->getNumero(), 11); + $campoLivre .= Util::numberFormatGeral($this->getConta(), 7); + $campoLivre .= '0'; + + return $this->campoLivre = $campoLivre; + } + + /** + * Método onde qualquer boleto deve extender para gerar o código da posição de 20 a 44 + * + * @param $campoLivre + * + * @return array + */ + public static function parseCampoLivre($campoLivre) { + return [ + 'convenio' => null, + 'agenciaDv' => null, + 'contaCorrenteDv' => null, + 'agencia' => substr($campoLivre, 0, 4), + 'carteira' => substr($campoLivre, 4, 2), + 'nossoNumero' => substr($campoLivre, 6, 11), + 'nossoNumeroDv' => null, + 'nossoNumeroFull' => substr($campoLivre, 6, 11), + 'contaCorrente' => substr($campoLivre, 17, 7), + ]; + } + + /** + * Define o campo CIP do boleto + * + * @param int $cip + * @return Cresol + */ + public function setCip($cip) + { + $this->cip = $cip; + $this->variaveis_adicionais['cip'] = $this->getCip(); + + return $this; + } + + /** + * Retorna o campo CIP do boleto + * + * @return string + */ + public function getCip() + { + return Util::numberFormatGeral($this->cip, 3); + } +} diff --git a/src/Boleto/Banco/Delbank.php b/src/Boleto/Banco/Delbank.php index f95afb94..16a4a1ba 100644 --- a/src/Boleto/Banco/Delbank.php +++ b/src/Boleto/Banco/Delbank.php @@ -1,13 +1,15 @@ Com registro - Emissão na Internet | '121' => Com Registro @@ -22,6 +25,7 @@ class Delbank extends AbstractBoleto implements BoletoContract * @var array */ protected $carteiras = ['112', '121']; + /** * Trata-se de código utilizado para identificar mensagens especificas ao cedente, sendo * que o mesmo consta no cadastro do Banco, quando não houver código cadastrado preencher @@ -30,15 +34,17 @@ class Delbank extends AbstractBoleto implements BoletoContract * @var int */ protected $cip = '000'; + /** * Variaveis adicionais. * * @var array */ public $variaveis_adicionais = [ - 'cip' => '000', + 'cip' => '000', 'mostra_cip' => true, ]; + /** * Espécie do documento, coódigo para remessa * @@ -56,6 +62,7 @@ class Delbank extends AbstractBoleto implements BoletoContract 'BP' => '30', //Boleto de Proposta 'O' => '99', //Outros, ]; + /** * Espécie do documento, coódigo para remessa * @@ -74,12 +81,14 @@ class Delbank extends AbstractBoleto implements BoletoContract 'BDP' => '32', // Boleto de Proposta 'O' => '99', // Outros ]; + /** * Mostrar o endereço do beneficiário abaixo da razão e CNPJ na ficha de compensação * - * @var boolean + * @var bool */ protected $mostrarEnderecoFichaCompensacao = true; + /** * Gera o Nosso Número. * @@ -92,20 +101,21 @@ protected function gerarNossoNumero() } /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Delbank + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { if ($this->getDiasProtesto() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } $baixaAutomatica = (int) $baixaAutomatica; $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + return $this; } @@ -116,8 +126,9 @@ public function setDiasBaixaAutomatica($baixaAutomatica) */ public function getNossoNumeroBoleto() { - return Util::numberFormatGeral($this->getCarteira(), 2) . ' / ' . substr_replace($this->getNossoNumero(), '-', -1, 0); + return Util::numberFormatGeral($this->getCarteira(), 2) . ' / ' . substr_replace($this->getNossoNumero(), '-', -1, 0); } + /** * Método para gerar o código da posição de 20 a 44 * @@ -145,30 +156,32 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'agenciaDv' => null, + 'convenio' => null, + 'agenciaDv' => null, 'contaCorrenteDv' => null, - 'agencia' => substr($campoLivre, 0, 4), - 'carteira' => substr($campoLivre, 4, 2), - 'nossoNumero' => substr($campoLivre, 6, 11), - 'nossoNumeroDv' => null, + 'agencia' => substr($campoLivre, 0, 4), + 'carteira' => substr($campoLivre, 4, 2), + 'nossoNumero' => substr($campoLivre, 6, 11), + 'nossoNumeroDv' => null, 'nossoNumeroFull' => substr($campoLivre, 6, 11), - 'contaCorrente' => substr($campoLivre, 17, 7), + 'contaCorrente' => substr($campoLivre, 17, 7), ]; } /** * Define o campo CIP do boleto * - * @param int $cip + * @param int $cip * @return Delbank */ public function setCip($cip) { $this->cip = $cip; $this->variaveis_adicionais['cip'] = $this->getCip(); + return $this; } diff --git a/src/Boleto/Banco/Fibra.php b/src/Boleto/Banco/Fibra.php index ad336e74..64b50995 100644 --- a/src/Boleto/Banco/Fibra.php +++ b/src/Boleto/Banco/Fibra.php @@ -1,10 +1,12 @@ addCampoObrigatorio('range', 'codigoCliente', 'modalidadeCarteira'); } + /** * Moeda * * @var int */ protected $moeda = 0; + /** * Código do banco * @var string */ protected $codigoBanco = self::COD_BANCO_FIBRA; + /** * Define as carteiras disponíveis para este banco * @var array */ protected $carteiras = false; + /** * Espécie do documento, código para remessa do CNAB240 * @var string @@ -44,28 +50,33 @@ public function __construct(array $params = []) 'CAR' => '31', //Cartão de crédito 'O' => '99', //Outros, ]; + /** * Linha de local de pagamento * * @var string */ protected $localPagamento = 'Canais eletrônicos, agências ou correspondentes bancários de todo o BRASIL'; + /** * Código de range de composição do nosso numero. * * @var int */ protected $range = 0; + /** * @var string */ protected $codigoCliente; + /** * Modalidade da carteira * * @var string */ protected $modalidadeCarteira; + /** * @return int */ @@ -73,6 +84,7 @@ public function getRange() { return $this->range; } + /** * @param int $range * @@ -84,17 +96,20 @@ public function setRange($range) return $this; } + /** * Define o número do codigo do Cliente * - * @param string $codigoCliente + * @param string $codigoCliente * @return Fibra */ public function setCodigoCliente($codigoCliente) { $this->codigoCliente = $codigoCliente; + return $this; } + /** * Retorna o número do codigo Cliente * @@ -104,6 +119,7 @@ public function getCodigoCliente() { return $this->codigoCliente; } + /** * Retorna a modalidade da carteira * @@ -120,23 +136,24 @@ public function getModalidadeCarteira() * @param mixed $modalidadeCarteira * * @return Fibra - * @throws \Exception + * @throws ValidationException */ public function setModalidadeCarteira($modalidadeCarteira) { $modalidadeCarteira = Util::upper($modalidadeCarteira); - if (!in_array($modalidadeCarteira, ['1', '5', 'D'])) { - throw new \Exception('Modalidade da carteira inválida'); + if (! in_array($modalidadeCarteira, ['1', '5', 'D'])) { + throw new ValidationException('Modalidade da carteira inválida'); } $this->modalidadeCarteira = $modalidadeCarteira; return $this; } + /** * Gera o Nosso Número. * - * @throws \Exception * @return string + * @throws ValidationException */ protected function gerarNossoNumero() { @@ -145,13 +162,15 @@ protected function gerarNossoNumero() $nn = ((int) $this->getRange()) + ((int) $this->getNumero()); $nn .= CalculoDV::fibraNossoNumero($this->getAgencia(), $this->getCarteira(), $nn); } + return Util::numberFormatGeral($nn, 11); } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -176,19 +195,20 @@ protected function getCampoLivre() * * @return array */ - static public function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'parcela' => null, - 'agenciaDv' => null, - 'contaCorrente' => null, - 'modalidade' => null, + 'convenio' => null, + 'parcela' => null, + 'agenciaDv' => null, + 'contaCorrente' => null, + 'modalidade' => null, 'contaCorrenteDv' => null, - 'nossoNumeroDv' => null, - 'agencia' => substr($campoLivre, 0, 4), - 'nossa_carteira' => substr($campoLivre, 4, 3), - 'codigoCliente' => substr($campoLivre, 7, 7), - 'nossoNumero' => substr($campoLivre, 14, 11), + 'nossoNumeroDv' => null, + 'agencia' => substr($campoLivre, 0, 4), + 'nossa_carteira' => substr($campoLivre, 4, 3), + 'codigoCliente' => substr($campoLivre, 7, 7), + 'nossoNumero' => substr($campoLivre, 14, 11), 'nossoNumeroFull' => substr($campoLivre, 14, 11), ]; } @@ -196,7 +216,16 @@ static public function parseCampoLivre($campoLivre) { /** * @return string */ - public function getAgenciaCodigoBeneficiario(){ - return sprintf('%s%s / %s%s',$this->getAgencia(), CalculoDV::fibraAgencia($this->getAgencia()), $this->getConta(), CalculoDV::fibraConta($this->getConta())); + public function getAgenciaCodigoBeneficiario() + { + return sprintf('%s%s / %s%s', $this->getAgencia(), CalculoDV::fibraAgencia($this->getAgencia()), $this->getConta(), CalculoDV::fibraConta($this->getConta())); + } + + /** + * @return bool + */ + public function imprimeBoleto() + { + return Util::upper($this->getModalidadeCarteira()) == 'D'; } } diff --git a/src/Boleto/Banco/Hsbc.php b/src/Boleto/Banco/Hsbc.php index dd7a7307..9d44a44d 100644 --- a/src/Boleto/Banco/Hsbc.php +++ b/src/Boleto/Banco/Hsbc.php @@ -1,11 +1,12 @@ '01', - 'NP' => '02', - 'NS' => '03', + 'DM' => '01', + 'NP' => '02', + 'NS' => '03', 'REC' => '05', - 'CE' => '09', - 'DS' => '10', - 'PD' => '98', + 'CE' => '09', + 'DS' => '10', + 'PD' => '98', ]; + /** * Código de range de composição do nosso numero. * * @var string */ protected $range; + /** * Espécie do documento, geralmente DM (Duplicata Mercantil) * * @var string */ protected $especieDoc = 'PD'; + /** * @return string */ @@ -58,6 +64,7 @@ public function getRange() { return $this->range; } + /** * @param string $range * @@ -69,17 +76,20 @@ public function setRange($range) return $this; } + /** * Define o campo Espécie Doc, HSBC sempre PD * - * @param string $especieDoc + * @param string $especieDoc * @return AbstractBoleto */ public function setEspecieDoc($especieDoc) { $this->especieDoc = 'PD'; + return $this; } + /** * Retorna o campo Agência/Beneficiário do boleto * @@ -90,15 +100,16 @@ public function getAgenciaCodigoBeneficiario() $agencia = rtrim(sprintf('%s-%s', $this->getAgencia(), $this->getAgenciaDv()), '-'); if ($this->getContaDv() !== null && strlen($this->getContaDv()) == 1) { - $conta = substr($this->getConta(), 0, -1) . '-' .substr($this->getConta(), -1).$this->getContaDv(); + $conta = substr($this->getConta(), 0, -1) . '-' . substr($this->getConta(), -1) . $this->getContaDv(); } elseif ($this->getContaDv() !== null && strlen($this->getContaDv()) == 2) { - $conta = substr($this->getConta(), 0, -1) . '-' .substr($this->getConta(), -1).$this->getContaDv(); + $conta = substr($this->getConta(), 0, -1) . '-' . substr($this->getConta(), -1) . $this->getContaDv(); } else { $conta = $this->getConta(); } return sprintf('%s / %s', $agencia, $conta); } + /** * Gera o Nosso Número. * @@ -109,8 +120,10 @@ protected function gerarNossoNumero() $range = Util::numberFormatGeral($this->getRange(), 5); $numero_boleto = Util::numberFormatGeral($this->getNumero(), 5); $dv = Util::modulo11($range . $numero_boleto, 2, 7); + return $range . $numero_boleto . $dv; } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -120,6 +133,7 @@ public function getNossoNumeroBoleto() { return substr_replace($this->getNossoNumero(), '-', -1, 0); } + /** * Método para gerar o código da posição de 20 a 44 * @@ -147,15 +161,16 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'agenciaDv' => null, - 'nossoNumero' => substr($campoLivre, 0, 10), - 'nossoNumeroDv' => substr($campoLivre, 10, 1), + 'convenio' => null, + 'agenciaDv' => null, + 'nossoNumero' => substr($campoLivre, 0, 10), + 'nossoNumeroDv' => substr($campoLivre, 10, 1), 'nossoNumeroFull' => substr($campoLivre, 0, 11), - 'agencia' => substr($campoLivre, 11, 4), - 'contaCorrente' => substr($campoLivre, 15, 6), + 'agencia' => substr($campoLivre, 11, 4), + 'contaCorrente' => substr($campoLivre, 15, 6), 'contaCorrenteDv' => substr($campoLivre, 21, 1), ]; } diff --git a/src/Boleto/Banco/Inter.php b/src/Boleto/Banco/Inter.php index 78e2167f..113ba609 100644 --- a/src/Boleto/Banco/Inter.php +++ b/src/Boleto/Banco/Inter.php @@ -1,12 +1,14 @@ setCamposObrigatorios('operacao'); } + protected $agencia = '0001'; + protected $carteira = '112'; + /** * Código do banco * * @var string */ protected $codigoBanco = Boleto::COD_BANCO_INTER; + /** * Define as carteiras disponíveis para este banco * '02' => Com registro | '09' => Com registro | '06' => Sem Registro | '21' => Com Registro - Pagável somente no Bradesco | '22' => Sem Registro - Pagável somente no Bradesco | '25' => Sem Registro - Emissão na Internet | '26' => Com Registro - Emissão na Internet @@ -30,6 +36,7 @@ public function __construct(array $params = []) * @var array */ protected $carteiras = ['112']; + /** * Espécie do documento, coódigo para remessa * @@ -37,15 +44,18 @@ public function __construct(array $params = []) */ protected $especiesCodigo = [ ]; + /** * @var string */ protected $operacao; + /** * @var string[] */ protected $protectedFields = [ ]; + /** * @return string */ @@ -53,10 +63,11 @@ public function getOperacao() { return $this->operacao; } + /** * @param $operacao * - * @return $this + * @return Inter */ public function setOperacao($operacao) { @@ -64,6 +75,7 @@ public function setOperacao($operacao) return $this; } + /** * Gera o Nosso Número. * @@ -81,20 +93,18 @@ protected function gerarNossoNumero() */ public function getNossoNumeroBoleto() { - return sprintf( - '00019/112/%011s-%01s', - substr($this->getNossoNumero(), 0, -1), - substr($this->getNossoNumero(), -1) - ); + return sprintf('00019/112/%011s-%01s', substr($this->getNossoNumero(), 0, -1), substr($this->getNossoNumero(), -1)); } /** * @return string */ - public function getAgenciaCodigoBeneficiario(){ + public function getAgenciaCodigoBeneficiario() + { return $this->getAgencia() . Util::modulo11($this->getAgencia()) . ' / ' . $this->getConta() . Util::modulo11($this->getConta()); } + /** * Método para gerar o código da posição de 20 a 44 * @@ -115,19 +125,20 @@ protected function getCampoLivre() } /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Inter + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { - if (!in_array($baixaAutomatica, [0, 30, 60])) { - throw new \Exception('Baixa automática válida somente 0, 30, 60'); + if (! in_array($baixaAutomatica, [0, 30, 60])) { + throw new ValidationException('Baixa automática válida somente 0, 30, 60'); } $this->diasBaixaAutomatica = $baixaAutomatica >= 0 ? $baixaAutomatica : 0; + return $this; } @@ -138,17 +149,18 @@ public function setDiasBaixaAutomatica($baixaAutomatica) * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => substr($campoLivre, 7, 7), - 'agenciaDv' => null, + 'convenio' => substr($campoLivre, 7, 7), + 'agenciaDv' => null, 'contaCorrenteDv' => null, - 'agencia' => substr($campoLivre, 0, 4), - 'carteira' => substr($campoLivre, 4, 3), - 'nossoNumero' => substr($campoLivre, 14, 10), - 'nossoNumeroDv' => substr($campoLivre, 24, 1), + 'agencia' => substr($campoLivre, 0, 4), + 'carteira' => substr($campoLivre, 4, 3), + 'nossoNumero' => substr($campoLivre, 14, 10), + 'nossoNumeroDv' => substr($campoLivre, 24, 1), 'nossoNumeroFull' => substr($campoLivre, 14, 11), - 'contaCorrente' => null, + 'contaCorrente' => null, ]; } @@ -168,64 +180,65 @@ public function toAPI() $diasBaixaAutomatica = 'ZERO'; } - $enderecoSplit = function($endereco) { + $enderecoSplit = function ($endereco) { $endereco = explode(',', $endereco); + return [ 'endereco' => $endereco[0], - 'numero' => array_key_exists(1, $endereco) + 'numero' => array_key_exists(1, $endereco) ? Util::onlyNumbers(explode(' ', trim($endereco[1]))[0]) - : 0 + : 0, ]; }; $desconto = $descontoDefault = [ 'codigoDesconto' => 'NAOTEMDESCONTO', - 'data' => '', - 'taxa' => 0, - 'valor' => 0, + 'data' => '', + 'taxa' => 0, + 'valor' => 0, ]; if ($this->getDesconto()) { $desconto = [ 'codigoDesconto' => 'VALORFIXODATAINFORMADA', - 'data' => $this->getDataDesconto()->format('Y-m-d'), - 'taxa' => 0, - 'valor' => Util::nFloat($this->getDesconto()), + 'data' => $this->getDataDesconto()->format('Y-m-d'), + 'taxa' => 0, + 'valor' => Util::nFloat($this->getDesconto()), ]; } $multa = [ 'codigoMulta' => 'NAOTEMMULTA', - 'data' => '', - 'taxa' => 0, - 'valor' => 0, + 'data' => '', + 'taxa' => 0, + 'valor' => 0, ]; if ($this->getMulta()) { $multa = [ 'codigoMulta' => 'PERCENTUAL', - 'data' => ($this->getDataVencimento()->copy())->addDay()->format('Y-m-d'), - 'taxa' => Util::nFloat($this->getMulta()), - 'valor' => 0, + 'data' => ($this->getDataVencimento()->copy())->addDay()->format('Y-m-d'), + 'taxa' => Util::nFloat($this->getMulta()), + 'valor' => 0, ]; } $mora = [ 'codigoMora' => 'ISENTO', - 'data' => '', - 'taxa' => 0, - 'valor' => 0, + 'data' => '', + 'taxa' => 0, + 'valor' => 0, ]; if ($this->getJuros()) { $mora = [ 'codigoMora' => 'TAXAMENSAL', - 'data' => ($this->getDataVencimento()->copy())->addDays($this->getJurosApos() > 0 ? $this->getJurosApos() : 1)->format('Y-m-d'), - 'taxa' => Util::nFloat($this->getJuros()), - 'valor' => 0, + 'data' => ($this->getDataVencimento()->copy())->addDays($this->getJurosApos() > 0 ? $this->getJurosApos() : 1)->format('Y-m-d'), + 'taxa' => Util::nFloat($this->getJuros()), + 'valor' => 0, ]; } $mensagem = array_filter($this->getDescricaoDemonstrativo()); foreach ($mensagem as $k => $m) { - $mensagem['linha' . ($k+1)] = $m; + $mensagem['linha' . ($k + 1)] = $m; unset($mensagem[$k]); } @@ -262,31 +275,31 @@ public function toAPI() * @param $appends * * @return Inter - * @throws \Exception + * @throws ValidationException */ public static function fromAPI($boleto, $appends) { - if(!array_key_exists('beneficiario', $appends)) { - throw new \Exception('Informe o beneficiario'); + if (! array_key_exists('beneficiario', $appends)) { + throw new ValidationException('Informe o beneficiario'); } - if(!array_key_exists('conta', $appends)) { - throw new \Exception('Informe a conta'); + if (! array_key_exists('conta', $appends)) { + throw new ValidationException('Informe a conta'); } $ipte = Util::IPTE2Variveis($boleto->linhaDigitavel); $aSituacao = [ - 'PAGO' => AbstractBoleto::SITUACAO_PAGO, - 'BAIXADO' => AbstractBoleto::SITUACAO_BAIXADO, - 'VENCIDO' => AbstractBoleto::SITUACAO_ABERTO, + 'PAGO' => AbstractBoleto::SITUACAO_PAGO, + 'BAIXADO' => AbstractBoleto::SITUACAO_BAIXADO, + 'VENCIDO' => AbstractBoleto::SITUACAO_ABERTO, 'EXPIRADO' => AbstractBoleto::SITUACAO_BAIXADO, ]; $dateUS = preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}.*/', $boleto->dataHoraSituacao); return new self(array_merge(array_filter([ - 'valorRecebido' => isset($boleto->valorTotalRecebimento) ? $boleto->valorTotalRecebimento : null, - 'situacao' => Arr::get($aSituacao, $boleto->situacao, $boleto->situacao), - 'dataSituacao' => $boleto->dataHoraSituacao + 'valorRecebido' => isset($boleto->valorTotalRecebimento) ? $boleto->valorTotalRecebimento : null, + 'situacao' => Arr::get($aSituacao, $boleto->situacao, $boleto->situacao), + 'dataSituacao' => $boleto->dataHoraSituacao ? Carbon::createFromFormat($dateUS ? 'Y-m-d H:i' : 'd/m/Y H:i', $boleto->dataHoraSituacao) : Carbon::now(), 'nossoNumero' => $boleto->nossoNumero, @@ -299,40 +312,45 @@ public static function fromAPI($boleto, $appends) 'pagador' => array_filter([ 'nome' => isset($boleto->pagador) ? $boleto->pagador->nome : $boleto->nomeSacado, 'documento' => isset($boleto->pagador) ? $boleto->pagador->cpfCnpj : $boleto->cnpjCpfSacado, - 'endereco' => isset($boleto->pagador) ? trim($boleto->pagador->endereco . ', ' . $boleto->pagador->endereco . ' ' . $boleto->pagador->complemento) : null, - 'bairro' => isset($boleto->pagador) ? $boleto->pagador->bairro : null, - 'cep' => isset($boleto->pagador) ? $boleto->pagador->cep : null, - 'uf' => isset($boleto->pagador) ? $boleto->pagador->uf : null, - 'cidade' => isset($boleto->pagador) ? $boleto->pagador->cidade : null, + 'endereco' => isset($boleto->pagador) ? trim($boleto->pagador->endereco . ', ' . $boleto->pagador->endereco . ' ' . $boleto->pagador->complemento) : null, + 'bairro' => isset($boleto->pagador) ? $boleto->pagador->bairro : null, + 'cep' => isset($boleto->pagador) ? $boleto->pagador->cep : null, + 'uf' => isset($boleto->pagador) ? $boleto->pagador->uf : null, + 'cidade' => isset($boleto->pagador) ? $boleto->pagador->cidade : null, ]), - 'multa' => Arr::get($boleto, 'multa.valor', 0), - 'juros' => Arr::get($boleto, 'juros.taxa', 0), - 'desconto' => Arr::get($boleto, 'desconto1.taxa', 0), - 'data_desconto' => Arr::get($boleto, 'desconto1.data'), - 'carteira' => $ipte['campo_livre_parsed']['carteira'], - 'operacao' => $ipte['campo_livre_parsed']['convenio'], + 'multa' => Arr::get($boleto, 'multa.valor', 0), + 'juros' => Arr::get($boleto, 'juros.taxa', 0), + 'desconto' => Arr::get($boleto, 'desconto1.taxa', 0), + 'data_desconto' => Arr::get($boleto, 'desconto1.data'), + 'carteira' => $ipte['campo_livre_parsed']['carteira'], + 'operacao' => $ipte['campo_livre_parsed']['convenio'], ]), $appends)); } - /** * DEFAULTS */ public function setCarteira($carteira) { $this->carteira = '112'; + return $this; } + public function setAgencia($agencia) { $this->agencia = '0001'; + return $this; } + public function setEspecieDoc($especieDoc) { $this->especieDoc = 'DM'; + return $this; } + public function setNossoNumero($nossoNumero) { $nnClean = substr(Util::onlyNumbers($nossoNumero), -11); @@ -341,4 +359,49 @@ public function setNossoNumero($nossoNumero) } $this->campoNossoNumero = $nnClean; } + + /** + * @return bool + */ + public function imprimeBoleto() + { + return $this->campoNossoNumero > 0; + } + + /** + * @return mixed + * @throws ValidationException + */ + public function alterarBoleto() + { + throw new ValidationException('Banco Inter só possui comando de registro.'); + } + + /** + * @return mixed + * @throws ValidationException + */ + public function alterarDataDeVencimento() + { + throw new ValidationException('Banco Inter só possui comando de registro.'); + } + + /** + * @param $instrucao + * @return mixed + * @throws ValidationException + */ + public function comandarInstrucao($instrucao) + { + throw new ValidationException('Banco Inter só possui comando de registro.'); + } + + /** + * @return mixed + * @throws ValidationException + */ + public function baixarBoleto() + { + throw new ValidationException('Banco Inter só possui comando de registro.'); + } } diff --git a/src/Boleto/Banco/Itau.php b/src/Boleto/Banco/Itau.php index 021c2dac..b18d9547 100644 --- a/src/Boleto/Banco/Itau.php +++ b/src/Boleto/Banco/Itau.php @@ -1,14 +1,15 @@ '', ]; + /** * Define as carteiras disponíveis para este banco * * @var array */ protected $carteiras = ['112', '115', '188', '109', '121', '180', '110', '111']; + /** * Espécie do documento, coódigo para remessa * * @var string */ protected $especiesCodigo = [ - 'DM' => '01', - 'NP' => '02', - 'NS' => '03', - 'ME' => '04', + 'DM' => '01', + 'NP' => '02', + 'NS' => '03', + 'ME' => '04', 'REC' => '05', - 'CT' => '06', - 'CS' => '07', - 'DS' => '08', - 'LC' => '09', - 'ND' => '13', + 'CT' => '06', + 'CS' => '07', + 'DS' => '08', + 'LC' => '09', + 'ND' => '13', 'CDA' => '15', - 'EC' => '16', + 'EC' => '16', 'CPS' => '17', ]; + /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { if ($this->getDiasProtesto() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } $baixaAutomatica = (int) $baixaAutomatica; $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + return $this; } @@ -78,7 +84,7 @@ public function setDiasBaixaAutomatica($baixaAutomatica) * Gera o Nosso Número. * * @return string - * @throws \Exception + * @throws ValidationException */ protected function gerarNossoNumero() { @@ -87,8 +93,10 @@ protected function gerarNossoNumero() $agencia = Util::numberFormatGeral($this->getAgencia(), 4); $conta = Util::numberFormatGeral($this->getConta(), 5); $dv = CalculoDV::itauNossoNumero($agencia, $conta, $carteira, $numero_boleto); + return $numero_boleto . $dv; } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -98,11 +106,12 @@ public function getNossoNumeroBoleto() { return $this->getCarteira() . '/' . substr_replace($this->getNossoNumero(), '-', -1, 0); } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -114,7 +123,7 @@ protected function getCampoLivre() $campoLivre .= Util::numberFormatGeral($this->getNossoNumero(), 9); $campoLivre .= Util::numberFormatGeral($this->getAgencia(), 4); $campoLivre .= Util::numberFormatGeral($this->getConta(), 5); - $campoLivre .= CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta()); + $campoLivre .= ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta()); $campoLivre .= '000'; return $this->campoLivre = $campoLivre; @@ -127,17 +136,18 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'agenciaDv' => null, - 'codigoCliente' => null, - 'carteira' => substr($campoLivre, 0, 3), - 'nossoNumero' => substr($campoLivre, 3, 8), - 'nossoNumeroDv' => substr($campoLivre, 11, 1), + 'convenio' => null, + 'agenciaDv' => null, + 'codigoCliente' => null, + 'carteira' => substr($campoLivre, 0, 3), + 'nossoNumero' => substr($campoLivre, 3, 8), + 'nossoNumeroDv' => substr($campoLivre, 11, 1), 'nossoNumeroFull' => substr($campoLivre, 3, 9), - 'agencia' => substr($campoLivre, 12, 4), - 'contaCorrente' => substr($campoLivre, 16, 5), + 'agencia' => substr($campoLivre, 12, 4), + 'contaCorrente' => substr($campoLivre, 16, 5), 'contaCorrenteDv' => substr($campoLivre, 21, 1), ]; } diff --git a/src/Boleto/Banco/Ourinvest.php b/src/Boleto/Banco/Ourinvest.php new file mode 100644 index 00000000..2126cce9 --- /dev/null +++ b/src/Boleto/Banco/Ourinvest.php @@ -0,0 +1,145 @@ + '01', //Duplicata Mercantil + 'NP' => '02', //Nota Promissória + 'DS' => '12', //Duplicata de Serviço + 'O' => '99', //Outros, + ]; + + /** + * Emissão do boleto por conta do beneficiário (true) por conta do banco (false) + * @var bool + */ + protected $emissaoPropria = true; + + /** + * Linha de local de pagamento + * + * @var string + */ + protected $localPagamento = 'Canais eletrônicos, agências ou correspondentes bancários de todo o BRASIL'; + + /** + * @return bool + */ + public function isEmissaoPropria() + { + return $this->emissaoPropria; + } + + /** + * @param $emissaoPropria + * + * @return Ourinvest + */ + public function setEmissaoPropria($emissaoPropria) + { + $this->emissaoPropria = $emissaoPropria; + + return $this; + } + + /** + * Gera o Nosso Número. + * + * @return string + */ + protected function gerarNossoNumero() + { + return $this->isEmissaoPropria() + ? Util::numberFormatGeral($this->getNumero(), 11) . CalculoDV::ourinvestNossoNumero($this->getCarteira(), $this->getNumero()) + : Util::numberFormatGeral(0, 12); + } + + /** + * Método para gerar o código da posição de 20 a 44 + * + * @return string + */ + protected function getCampoLivre() + { + if ($this->campoLivre) { + return $this->campoLivre; + } + + $campoLivre = Util::numberFormatGeral($this->getAgencia(), 4); + $campoLivre .= Util::numberFormatGeral($this->getCarteira(), 2); + $campoLivre .= Util::numberFormatGeral($this->getNossoNumero(), 11); + $campoLivre .= Util::numberFormatGeral($this->getConta(), 7); + $campoLivre .= '0'; + + return $this->campoLivre = $campoLivre; + } + + /** + * Método onde qualquer boleto deve extender para gerar o código da posição de 20 a 44 + * + * @param $campoLivre + * + * @return array + */ + public static function parseCampoLivre($campoLivre) + { + return [ + 'convenio' => null, + 'parcela' => null, + 'agenciaDv' => null, + 'contaCorrente' => substr($campoLivre, 16, 7), + 'modalidade' => null, + 'contaCorrenteDv' => null, + 'nossoNumeroDv' => substr($campoLivre, 15, 1), + 'agencia' => substr($campoLivre, 0, 4), + 'nossa_carteira' => substr($campoLivre, 4, 2), + 'codigoCliente' => null, + 'nossoNumero' => substr($campoLivre, 6, 10), + 'nossoNumeroFull' => substr($campoLivre, 6, 11), + ]; + } + + /** + * @return string + */ + public function getAgenciaCodigoBeneficiario() + { + return sprintf( + '%04s-%s / %07s-%s', + $this->getAgencia(), + ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::ourinvestAgencia($this->getAgencia()), + $this->getConta(), + ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::ourinvestConta($this->getConta())); + } + + /** + * @return bool + */ + public function imprimeBoleto() + { + return $this->isEmissaoPropria(); + } +} diff --git a/src/Boleto/Banco/Pine.php b/src/Boleto/Banco/Pine.php index 5150b7ae..5f26cb62 100644 --- a/src/Boleto/Banco/Pine.php +++ b/src/Boleto/Banco/Pine.php @@ -1,10 +1,12 @@ '31', //Cartão de crédito 'O' => '99', //Outros, ]; + /** * Linha de local de pagamento * * @var string */ protected $localPagamento = 'Canais eletrônicos, agências ou correspondentes bancários de todo o BRASIL'; + /** * Código de range de composição do nosso numero. * * @var int */ protected $range = 0; + /** * @var string */ protected $codigoCliente; + /** * Modalidade da carteira * * @var string */ protected $modalidadeCarteira; + /** * @return int */ @@ -68,6 +77,7 @@ public function getRange() { return $this->range; } + /** * @param int $range * @@ -79,17 +89,20 @@ public function setRange($range) return $this; } + /** * Define o número do codigo do Cliente * - * @param string $codigoCliente + * @param string $codigoCliente * @return Pine */ public function setCodigoCliente($codigoCliente) { $this->codigoCliente = $codigoCliente; + return $this; } + /** * Retorna o número do codigo Cliente * @@ -99,6 +112,7 @@ public function getCodigoCliente() { return $this->codigoCliente; } + /** * Retorna a modalidade da carteira * @@ -115,23 +129,24 @@ public function getModalidadeCarteira() * @param mixed $modalidadeCarteira * * @return Pine - * @throws \Exception + * @throws ValidationException */ public function setModalidadeCarteira($modalidadeCarteira) { $modalidadeCarteira = Util::upper($modalidadeCarteira); - if (!in_array($modalidadeCarteira, ['1', '2', '5', '6', 'D'])) { - throw new \Exception('Modalidade da carteira inválida'); + if (! in_array($modalidadeCarteira, ['1', '2', '5', '6', 'D'])) { + throw new ValidationException('Modalidade da carteira inválida'); } $this->modalidadeCarteira = $modalidadeCarteira; return $this; } + /** * Gera o Nosso Número. * - * @throws \Exception * @return string + * @throws ValidationException */ protected function gerarNossoNumero() { @@ -140,13 +155,15 @@ protected function gerarNossoNumero() $nn = ((int) $this->getRange()) + ((int) $this->getNumero()); $nn .= CalculoDV::pineNossoNumero($this->getAgencia(), $this->getCarteira(), $nn); } + return Util::numberFormatGeral($nn, 11); } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -171,19 +188,20 @@ protected function getCampoLivre() * * @return array */ - static public function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'parcela' => null, - 'agenciaDv' => null, - 'contaCorrente' => null, - 'modalidade' => null, + 'convenio' => null, + 'parcela' => null, + 'agenciaDv' => null, + 'contaCorrente' => null, + 'modalidade' => null, 'contaCorrenteDv' => null, - 'nossoNumeroDv' => null, - 'agencia' => substr($campoLivre, 0, 4), - 'nossa_carteira' => substr($campoLivre, 4, 3), - 'codigoCliente' => substr($campoLivre, 7, 7), - 'nossoNumero' => substr($campoLivre, 14, 11), + 'nossoNumeroDv' => null, + 'agencia' => substr($campoLivre, 0, 4), + 'nossa_carteira' => substr($campoLivre, 4, 3), + 'codigoCliente' => substr($campoLivre, 7, 7), + 'nossoNumero' => substr($campoLivre, 14, 11), 'nossoNumeroFull' => substr($campoLivre, 14, 11), ]; } @@ -191,7 +209,22 @@ static public function parseCampoLivre($campoLivre) { /** * @return string */ - public function getAgenciaCodigoBeneficiario(){ - return sprintf('%s%s / %s%s',$this->getAgencia(), CalculoDV::pineAgencia($this->getAgencia()), $this->getConta(), CalculoDV::pineConta($this->getConta())); + public function getAgenciaCodigoBeneficiario() + { + return sprintf( + '%s%s / %s%s', + $this->getAgencia(), + ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::pineAgencia($this->getAgencia()), + $this->getConta(), + ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::pineConta($this->getConta()) + ); + } + + /** + * @return bool + */ + public function imprimeBoleto() + { + return Util::upper($this->getModalidadeCarteira()) == 'D'; } } diff --git a/src/Boleto/Banco/Rendimento.php b/src/Boleto/Banco/Rendimento.php new file mode 100644 index 00000000..4b842813 --- /dev/null +++ b/src/Boleto/Banco/Rendimento.php @@ -0,0 +1,231 @@ +setCamposObrigatorios('numero', 'agencia', 'carteira', 'modalidadeCarteira', 'codigoCliente'); + } + + /** + * Moeda + * + * @var int + */ + protected $moeda = 0; + + /** + * Código do banco + * @var string + */ + protected $codigoBanco = self::COD_BANCO_RENDIMENTO; + + /** + * Define as carteiras disponíveis para este banco + * @var array + */ + protected $carteiras = [121, 112]; + + /** + * Espécie do documento, código para remessa do CNAB240 + * @var string + */ + protected $especiesCodigo = [ + 'DM' => '01', //Duplicata Mercantil + 'NP' => '02', //Nota Promissória + 'CH' => '03', //Cheque + 'LC' => '04', //Letra de Câmbio + 'RC' => '05', //Recibo + 'AP' => '08', //Apólice de Seguro + 'DS' => '12', //Duplicata de Serviço + 'CAR' => '31', //Cartão de crédito + 'O' => '99', //Outros, + ]; + + /** + * Linha de local de pagamento + * + * @var string + */ + protected $localPagamento = 'Canais eletrônicos, agências ou correspondentes bancários de todo o BRASIL'; + + /** + * Código de range de composição do nosso número. + * + * @var int + */ + protected $range = 0; + + /** + * @var string + */ + protected $codigoCliente; + + /** + * Modalidade da carteira + * + * @var string + */ + protected $modalidadeCarteira; + + /** + * @return int + */ + public function getRange() + { + return $this->range; + } + + /** + * @param int $range + * + * @return Rendimento + */ + public function setRange($range) + { + $this->range = (int) $range; + + return $this; + } + + /** + * Define o número do codigo do Cliente + * + * @param string $codigoCliente + * @return Rendimento + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * Retorna o número do codigo Cliente + * + * @return string + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Retorna a modalidade da carteira + * + * @return mixed + */ + public function getModalidadeCarteira() + { + return $this->modalidadeCarteira; + } + + /** + * Seta a modalidade da carteira. + * + * @param mixed $modalidadeCarteira + * + * @return Rendimento + * @throws ValidationException + */ + public function setModalidadeCarteira($modalidadeCarteira) + { + $modalidadeCarteira = Util::upper($modalidadeCarteira); + if (! in_array($modalidadeCarteira, ['1', '2', '3', '4', '6'])) { + throw new ValidationException('Modalidade da carteira inválida'); + } + $this->modalidadeCarteira = $modalidadeCarteira; + + return $this; + } + + /** + * Gera o Nosso Número. + * + * @return string + * @throws ValidationException + */ + protected function gerarNossoNumero() + { + $nn = 0; + if ($this->getModalidadeCarteira() == 6) { + $nn = ((int) $this->getRange()) + ((int) $this->getNumero()); + $nn .= CalculoDV::rendimentoNossoNumero($this->getAgencia(), $this->getCarteira(), $nn); + } + + return Util::numberFormatGeral($nn, 11); + } + + /** + * Método para gerar o código da posição de 20 a 44 + * + * @return string + * @throws ValidationException + */ + protected function getCampoLivre() + { + if ($this->campoLivre) { + return $this->campoLivre; + } + + $nossoNumero = $this->getNossoNumero(); + + $campoLivre = Util::numberFormatGeral($this->getAgencia(), 4); + $campoLivre .= Util::numberFormatGeral($this->getCarteira(), 3); + $campoLivre .= Util::numberFormatGeral($this->getCodigoCliente(), 7); + $campoLivre .= Util::numberFormatGeral($nossoNumero, 11); + + return $this->campoLivre = $campoLivre; + } + + /** + * Método onde qualquer boleto deve extender para gerar o código da posição de 20 a 44 + * + * @param $campoLivre + * + * @return array + */ + public static function parseCampoLivre($campoLivre) + { + return [ + 'convenio' => null, + 'parcela' => null, + 'agenciaDv' => null, + 'contaCorrente' => null, + 'modalidade' => null, + 'contaCorrenteDv' => null, + 'nossoNumeroDv' => null, + 'agencia' => substr($campoLivre, 0, 4), + 'nossa_carteira' => substr($campoLivre, 4, 3), + 'codigoCliente' => substr($campoLivre, 7, 7), + 'nossoNumero' => substr($campoLivre, 14, 11), + 'nossoNumeroFull' => substr($campoLivre, 14, 11), + ]; + } + + /** + * @return string + */ + public function getAgenciaCodigoBeneficiario() + { + return sprintf('%s / %s', $this->getAgencia(), $this->getCodigoCliente()); + } + + /** + * @return bool + */ + public function imprimeBoleto() + { + return $this->getModalidadeCarteira() == 6; + } +} diff --git a/src/Boleto/Banco/Santander.php b/src/Boleto/Banco/Santander.php index 5bb0f618..e43e444c 100644 --- a/src/Boleto/Banco/Santander.php +++ b/src/Boleto/Banco/Santander.php @@ -2,10 +2,11 @@ namespace VinicciusGuedes\LaravelCnab\Boleto\Banco; -use VinicciusGuedes\LaravelCnab\Boleto\AbstractBoleto; +use VinicciusGuedes\LaravelCnab\Util; use VinicciusGuedes\LaravelCnab\CalculoDV; +use VinicciusGuedes\LaravelCnab\Boleto\AbstractBoleto; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Util; class Santander extends AbstractBoleto implements BoletoContract { @@ -21,12 +22,14 @@ public function __construct(array $params = []) * @var string */ protected $codigoBanco = self::COD_BANCO_SANTANDER; + /** * Define as carteiras disponíveis para este banco * * @var array */ protected $carteiras = ['101', '201']; + /** * Espécie do documento, código para remessa 240 * @@ -43,8 +46,9 @@ public function __construct(array $params = []) 'BCC' => '31', 'BDP' => '32', 'CH' => '97', - 'ND' => '98' + 'ND' => '98', ]; + /** * Espécie do documento, código para remessa 400 * @@ -60,12 +64,14 @@ public function __construct(array $params = []) 'BDP' => '08', 'BCC' => '19', ]; + /** * Mostrar o endereço do beneficiário abaixo da razão e CNPJ na ficha de compensação * - * @var boolean + * @var bool */ protected $mostrarEnderecoFichaCompensacao = true; + /** * Define os nomes das carteiras para exibição no boleto * @@ -74,14 +80,16 @@ public function __construct(array $params = []) protected $carteirasNomes = [ '101' => 'Cobrança Simples ECR', '102' => 'Cobrança Simples CSR', - '201' => 'Penhor' + '201' => 'Penhor', ]; + /** * Define o valor do IOS - Seguradoras (Se 7% informar 7. Limitado a 9%) - Demais clientes usar 0 (zero) * * @var int */ protected $ios = 0; + /** * Variaveis adicionais. * @@ -106,7 +114,8 @@ public function __construct(array $params = []) public function getAgenciaCodigoBeneficiario() { $agencia = rtrim(sprintf('%s-%s', $this->getAgencia(), $this->getAgenciaDv()), '-'); - return sprintf('%s / %s',$agencia, $this->getCodigoCliente()); + + return sprintf('%s / %s', $agencia, $this->getCodigoCliente()); } /** @@ -159,7 +168,7 @@ public function setCodigoCliente($codigoCliente) * * @param string $carteira * @return AbstractBoleto - * @throws \Exception + * @throws ValidationException */ public function setCarteira($carteira) { @@ -172,6 +181,7 @@ public function setCarteira($carteira) $carteira = '102'; break; } + return parent::setCarteira($carteira); } @@ -196,23 +206,24 @@ public function getIos() } /** - * Seta dias para baixa automática + * Seta dia para baixa automática * * @param int $baixaAutomatica * - * @return $this - * @throws \Exception + * @return Santander + * @throws ValidationException */ public function setDiasBaixaAutomatica($baixaAutomatica) { if ($this->getDiasProtesto() > 0) { - throw new \Exception('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); + throw new ValidationException('Você deve usar dias de protesto ou dias de baixa, nunca os 2'); } - if (!in_array($baixaAutomatica, [15, 30])) { - throw new \Exception('O Banco Santander so aceita 15 ou 30 dias após o vencimento para baixa automática'); + if (! in_array($baixaAutomatica, [15, 30])) { + throw new ValidationException('O Banco Santander so aceita 15 ou 30 dias após o vencimento para baixa automática'); } - $baixaAutomatica = (int)$baixaAutomatica; + $baixaAutomatica = (int) $baixaAutomatica; $this->diasBaixaAutomatica = $baixaAutomatica > 0 ? $baixaAutomatica : 0; + return $this; } @@ -223,9 +234,32 @@ public function setDiasBaixaAutomatica($baixaAutomatica) */ protected function gerarNossoNumero() { - $numero_boleto = $this->getNumero(); - return Util::numberFormatGeral($numero_boleto, 12) - . CalculoDV::santanderNossoNumero($numero_boleto); + return Util::numberFormatGeral($this->getNumero(), 12) + . CalculoDV::santanderNossoNumero($this->getNumero()); + } + + /** + * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. + * + * @return string + */ + public function getNossoNumeroBoleto() + { + return substr($this->getNossoNumero(), 0, -1) . '-' . substr($this->getNossoNumero(), -1); + } + + /** + * @param $id + * @return string + * @throws ValidationException + */ + protected function validateId($id) + { + if (! preg_match('/^[a-zA-Z0-9]{25,36}$/', $id)) { + throw new ValidationException('ID/TXID do boleto é inválido, Os caracteres aceitos neste contexto são: A-Z, a-z, 0-9, não pode conter brancos e nulos, com o mínimo de 26 caracteres e no máximo 35 caracteres'); + } + + return $id; } /** @@ -238,6 +272,7 @@ protected function getCampoLivre() if ($this->campoLivre) { return $this->campoLivre; } + return $this->campoLivre = '9' . Util::numberFormatGeral($this->getCodigoCliente(), 7) . Util::numberFormatGeral($this->getNossoNumero(), 13) . Util::numberFormatGeral($this->getIos(), 1) diff --git a/src/Boleto/Banco/Sicredi.php b/src/Boleto/Banco/Sicredi.php index c66d9ee8..dbab182c 100644 --- a/src/Boleto/Banco/Sicredi.php +++ b/src/Boleto/Banco/Sicredi.php @@ -1,10 +1,12 @@ '03', // Duplicata Mercantil por Indicação - 'DM' => '05', // Duplicata Mercantil por Indicação - 'DR' => '06', // Duplicata Rural - 'NP' => '12', // Nota Promissória - 'NR' => '13', // Nota Promissória Rural - 'NS' => '16', // Nota de Seguros - 'RC' => '17', // Recibo - 'LC' => '07', // Letra de Câmbio - 'ND' => '19', // Nota de Débito + 'DM' => '05', // Duplicata Mercantil por Indicação + 'DR' => '06', // Duplicata Rural + 'NP' => '12', // Nota Promissória + 'NR' => '13', // Nota Promissória Rural + 'NS' => '16', // Nota de Seguros + 'RC' => '17', // Recibo + 'LC' => '07', // Letra de Câmbio + 'ND' => '19', // Nota de Débito 'DSI' => '99', // Duplicata de Serviço por Indicação - 'OS' => '99', // Outros + 'OS' => '99', // Outros ]; + /** * Espécie do documento, coódigo para remessa * @@ -57,35 +63,39 @@ public function __construct(array $params = []) */ protected $especiesCodigo400 = [ 'DMI' => 'A', // Duplicata Mercantil por Indicação - 'DM' => 'A', // Duplicata Mercantil por Indicação - 'DR' => 'B', // Duplicata Rural - 'NP' => 'C', // Nota Promissória - 'NR' => 'D', // Nota Promissória Rural - 'NS' => 'E', // Nota de Seguros - 'RC' => 'G', // Recibo - 'LC' => 'H', // Letra de Câmbio - 'ND' => 'I', // Nota de Débito + 'DM' => 'A', // Duplicata Mercantil por Indicação + 'DR' => 'B', // Duplicata Rural + 'NP' => 'C', // Nota Promissória + 'NR' => 'D', // Nota Promissória Rural + 'NS' => 'E', // Nota de Seguros + 'RC' => 'G', // Recibo + 'LC' => 'H', // Letra de Câmbio + 'ND' => 'I', // Nota de Débito 'DSI' => 'J', // Duplicata de Serviço por Indicação - 'OS' => 'K', // Outros + 'OS' => 'K', // Outros ]; + /** * Se possui registro o boleto (tipo = 1 com registro e 3 sem registro) * * @var bool */ protected $registro = true; + /** * Código do posto do cliente no banco. * * @var int */ protected $posto; + /** * Byte que compoe o nosso número. * * @var int */ protected $byte = 2; + /** * Código do cliente (é código do cedente, também chamado de código do beneficiário) é o código do emissor junto ao banco, geralmente é o próprio número da conta sem o dígito verificador. * O código do cliente/cedente/beneficiário será diferente desse padrão em casos como quando um cliente bancário faz a migração da sua conta entre agências. @@ -97,14 +107,16 @@ public function __construct(array $params = []) /** * Define se possui ou não registro * - * @param bool $registro - * @return $this + * @param bool $registro + * @return Sicredi */ public function setComRegistro($registro) { $this->registro = $registro; + return $this; } + /** * Retorna se é com registro. * @@ -114,17 +126,20 @@ public function isComRegistro() { return $this->registro; } + /** * Define o posto do cliente * - * @param int $posto - * @return $this + * @param int $posto + * @return Sicredi */ public function setPosto($posto) { $this->posto = $posto; + return $this; } + /** * Retorna o posto do cliente * @@ -138,19 +153,21 @@ public function getPosto() /** * Define o byte * - * @param int $byte + * @param int $byte * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ public function setByte($byte) { if ($byte > 9) { - throw new \Exception('O byte deve ser compreendido entre 1 e 9'); + throw new ValidationException('O byte deve ser compreendido entre 1 e 9'); } $this->byte = $byte; + return $this; } + /** * Retorna o byte * @@ -160,12 +177,13 @@ public function getByte() { return $this->byte; } + /** - * Seta o codigo do cliente. + * Seta o código do cliente. * * @param mixed $codigoCliente * - * @return $this + * @return Sicredi */ public function setCodigoCliente($codigoCliente) { @@ -173,6 +191,7 @@ public function setCodigoCliente($codigoCliente) return $this; } + /** * Retorna o codigo do cliente. * @@ -182,6 +201,7 @@ public function getCodigoCliente() { return $this->codigoCliente; } + /** * Retorna o campo Agência/Beneficiário do boleto * @@ -191,6 +211,7 @@ public function getAgenciaCodigoBeneficiario() { return sprintf('%04s.%02s.%05s', $this->getAgencia(), $this->getPosto(), $this->getCodigoCliente()); } + /** * Gera o Nosso Número. * @@ -201,9 +222,11 @@ protected function gerarNossoNumero() $ano = $this->getDataDocumento()->format('y'); $byte = $this->getByte(); $numero_boleto = Util::numberFormatGeral($this->getNumero(), 5); - return $ano . $byte . $numero_boleto + + return $ano . $byte . $numero_boleto . CalculoDV::sicrediNossoNumero($this->getAgencia(), $this->getPosto(), $this->getCodigoCliente(), $ano, $byte, $numero_boleto); } + /** * Método que retorna o nosso numero usado no boleto. alguns bancos possuem algumas diferenças. * @@ -213,11 +236,12 @@ public function getNossoNumeroBoleto() { return Util::maskString($this->getNossoNumero(), '##/######-#'); } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception + * @throws ValidationException */ protected function getCampoLivre() { @@ -244,17 +268,18 @@ protected function getCampoLivre() * * @return array */ - public static function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ - 'convenio' => null, - 'agenciaDv' => null, + 'convenio' => null, + 'agenciaDv' => null, 'contaCorrenteDv' => null, - 'codigoCliente' => substr($campoLivre, 17, 5), - 'carteira' => substr($campoLivre, 1, 1), - 'nossoNumero' => substr($campoLivre, 2, 8), - 'nossoNumeroDv' => substr($campoLivre, 10, 1), + 'codigoCliente' => substr($campoLivre, 17, 5), + 'carteira' => substr($campoLivre, 1, 1), + 'nossoNumero' => substr($campoLivre, 2, 8), + 'nossoNumeroDv' => substr($campoLivre, 10, 1), 'nossoNumeroFull' => substr($campoLivre, 2, 9), - 'agencia' => substr($campoLivre, 11, 4), + 'agencia' => substr($campoLivre, 11, 4), //'contaCorrente' => substr($campoLivre, 17, 5), ]; } diff --git a/src/Boleto/Banco/Unicred.php b/src/Boleto/Banco/Unicred.php index bb89f959..baf2ccac 100644 --- a/src/Boleto/Banco/Unicred.php +++ b/src/Boleto/Banco/Unicred.php @@ -1,10 +1,11 @@ 'DM', //'Duplicata Mercantil', - 'NP' => 'NP', //'Nota Promissória', - 'NS' => 'NS',//'Nota de Seguro', - 'CS' => 'CS',//'Cobrança Seriada', - 'REC' => 'REC',//'Recibo', - 'LC' => 'LC',//'Letras de Câmbio', - 'ND' => 'ND',//'Nota de Débito', - 'DS' => 'DS',//'Duplicata de Serviços', - 'Outros' => 'Outros', + 'DM' => 'DM', //'Duplicata Mercantil', + 'NP' => 'NP', //'Nota Promissória', + 'NS' => 'NS', //'Nota de Seguro', + 'CS' => 'CS', //'Cobrança Seriada', + 'REC' => 'REC', //'Recibo', + 'LC' => 'LC', //'Letras de Câmbio', + 'ND' => 'ND', //'Nota de Débito', + 'DS' => 'DS', //'Duplicata de Serviços', + 'Outros' => 'Outros', ]; /** @@ -48,13 +52,14 @@ class Unicred extends AbstractBoleto implements BoletoContract * @var int */ protected $cip = '000'; + /** * Variaveis adicionais. * * @var array */ public $variaveis_adicionais = [ - 'cip' => '000', + 'cip' => '000', 'mostra_cip' => true, ]; @@ -65,19 +70,17 @@ class Unicred extends AbstractBoleto implements BoletoContract */ protected $codigoCliente; - /** * Gera o Nosso Número. Formado com 11(onze) caracteres, sendo 10 dígitos * para o nosso número é um digito para o digito verificador. Ex.: 9999999999-D. * Obs.: O Nosso Número é um identificador do boleto, devendo ser atribuído * Nosso Número diferenciado para cada um. * - * @throws \Exception * @return string */ protected function gerarNossoNumero() { - return Util::numberFormatGeral($this->getNumero(), 10). CalculoDV::unicredNossoNumero($this->getNumero()); + return Util::numberFormatGeral($this->getNumero(), 10) . CalculoDV::unicredNossoNumero($this->getNumero()); } /** @@ -89,11 +92,11 @@ public function getNossoNumeroBoleto() { return substr_replace($this->getNossoNumero(), '-', -1, 0); } + /** * Método para gerar o código da posição de 20 a 44 * * @return string - * @throws \Exception */ protected function getCampoLivre() { @@ -104,11 +107,10 @@ protected function getCampoLivre() $nossoNumero = $this->getNossoNumero(); $campoLivre = Util::numberFormatGeral($this->getAgencia(), 4); //Agência BENEFICIÁRIO (Sem o dígito verificador, completar com zeros à esquerda quando necessário) - $campoLivre .= Util::numberFormatGeral($this->getConta().$this->getContaDv(), 10); //Conta do BENEFICIÁRIO (Com o dígito verificador - Completar com zeros à esquerda quando necessário) + $campoLivre .= Util::numberFormatGeral($this->getConta() . $this->getContaDv(), 10); //Conta do BENEFICIÁRIO (Com o dígito verificador - Completar com zeros à esquerda quando necessário) $campoLivre .= Util::numberFormatGeral($nossoNumero, 11); //Nosso Número (Com o dígito verificador) return $this->campoLivre = $campoLivre; - } /** @@ -118,40 +120,42 @@ protected function getCampoLivre() * * @return array */ - static public function parseCampoLivre($campoLivre) { + public static function parseCampoLivre($campoLivre) + { return [ // 'convenio' => null, - 'agenciaDv' => null, + 'agenciaDv' => null, 'contaCorrenteDv' => null, - 'agencia' => substr($campoLivre, 0, 4), - 'nossoNumero' => substr($campoLivre, 14, 10), - 'nossoNumeroDv' => substr($campoLivre, 24, 1), + 'agencia' => substr($campoLivre, 0, 4), + 'nossoNumero' => substr($campoLivre, 14, 10), + 'nossoNumeroDv' => substr($campoLivre, 24, 1), 'nossoNumeroFull' => substr($campoLivre, 14, 11), - 'contaCorrente' => substr($campoLivre, 4, 10), + 'contaCorrente' => substr($campoLivre, 4, 10), ]; } - /** * AGÊNCIA / CÓDIGO DO BENEFICIÁRIO: deverá ser preenchido com o código da agência, * contendo 4 (quatro) caracteres / Conta Corrente com 10 (dez) caracteres. Ex. * 9999/999999999-9. Obs.: Preencher com zeros à direita quando necessário. * @return string */ - public function getAgenciaCodigoBeneficiario(){ - return $this->getAgencia() . ' / ' . Util::numberFormatGeral($this->getConta(), 9) .'-'. $this->getContaDv(); + public function getAgenciaCodigoBeneficiario() + { + return $this->getAgencia() . ' / ' . Util::numberFormatGeral($this->getConta(), 9) . '-' . $this->getContaDv(); } /** * Define o campo CIP do boleto * - * @param int $cip + * @param int $cip * @return Unicred */ public function setCip($cip) { $this->cip = $cip; $this->variaveis_adicionais['cip'] = $this->getCip(); + return $this; } @@ -166,11 +170,11 @@ public function getCip() } /** - * Seta o codigo do cliente. + * Seta o código do cliente. * * @param mixed $codigoCliente * - * @return $this + * @return Unicred */ public function setCodigoCliente($codigoCliente) { @@ -178,6 +182,7 @@ public function setCodigoCliente($codigoCliente) return $this; } + /** * Retorna o codigo do cliente. * @@ -187,5 +192,4 @@ public function getCodigoCliente() { return $this->codigoCliente; } - } diff --git a/src/Boleto/LaravelBoletoMailer.php b/src/Boleto/LaravelBoletoMailer.php new file mode 100644 index 00000000..460eb1a6 --- /dev/null +++ b/src/Boleto/LaravelBoletoMailer.php @@ -0,0 +1,41 @@ +bound(EmbedImages::class)) { + try { + (new SymfonyEmbedImages(config()->get('mail-auto-embed')))->handle($message); + } + catch (Exception $e){} + } + + return parent::shouldSendMessage($message, $data); + } + + /** + * @return bool|int + */ + public static function isLaravel9Plus() + { + return version_compare(Application::VERSION, '9.0.0', '>='); + } +} diff --git a/src/Boleto/Mail.php b/src/Boleto/Mail.php new file mode 100644 index 00000000..d43572e7 --- /dev/null +++ b/src/Boleto/Mail.php @@ -0,0 +1,402 @@ +makeBlade(); + $this->makeMailer($mailerConfigs); + } + + /** + * @return string|null + * @throws ValidationException + */ + private function getPdf() + { + $pdf = new Pdf(); + $pdf->addBoleto($this->getBoleto()); + + return $pdf->gerarBoleto($pdf::OUTPUT_STRING); + } + + /** + * @return Boleto + */ + private function getBoleto() + { + return $this->boleto; + } + + /** + * @return array + */ + #[ArrayShape([ + 'address' => 'string', + 'name' => 'string', + ])] + private function getTo() + { + return $this->to; + } + + /** + * @return array + */ + #[ArrayShape([ + 'address' => 'string', + 'name' => 'string', + ])] + private function getFrom() + { + return $this->from; + } + + /** + * @return BladeCompiler + */ + private function getBlade() + { + return $this->blade; + } + + /** + * @return LaravelBoletoMailer + */ + private function getMailer() + { + return $this->mailer; + } + + /** + * @return void + */ + private function makeBlade() + { + $instance = Container::getInstance(); + if (! is_null($instance) && $instance->bound(ViewFactory::class)) { + $this->blade = $this->view = view(); + } else { + $blade = new Blade(realpath(__DIR__ . '/Render/view/'), realpath(__DIR__ . '/Render/cache/')); + $this->blade = $this->view = $blade->view(); + $instance->bind(ViewFactory::class, function () { + return $this->view; + }); + $instance->bind('view', function () { + return $this->view; + }); + $instance->bind('config', function () { + return new Repository([ + 'view' => ['compiled' => realpath(__DIR__ . '/Render/compiled/')], + 'mail-auto-embed' => [ + 'enabled' => true, + 'method' => 'attachment', + 'curl' => [ + 'connect_timeout' => 5, + 'timeout' => 10, + ], + ], + ]); + }); + } + $this->blade = $this->blade->getEngineResolver()->resolve('blade')->getCompiler(); + } + + /** + * @param $config + * @return void + * @throws ValidationException + */ + private function makeMailer($config) + { + $instance = Container::getInstance(); + if (! is_null($instance) && $instance->bound(MailFactory::class)) { + $this->mailer = app(MailFactory::class); + } else { + $configs = ['host', 'port', 'username', 'password', 'from']; + if (count(array_intersect_key(array_flip($configs), $config)) !== count($configs)) { + throw new ValidationException('Mailer não existe, para configurar um é necessário informar ' . implode(', ', $configs)); + } + + $scheme = Arr::get($config, 'scheme'); + if (! $scheme) { + $scheme = ! empty($config['encryption']) && $config['encryption'] === 'tls' + ? (($config['port'] == 465) ? 'smtps' : 'smtp') + : ''; + } + + $this->setFrom($config['from']); + if (LaravelBoletoMailer::isLaravel9Plus()) { + $factory = new EsmtpTransportFactory(); + $transport = $factory->create(new Dsn( + $scheme, + $config['host'], + $config['username'] ?? null, + $config['password'] ?? null, + ((int) $config['port']) ?? null, + $config + )); + $this->mailer = new LaravelBoletoMailer('default', $this->view, $transport); + } else { + $transport = new Swift_SmtpTransport( + $config['host'], + $config['port'] + ); + + if (! empty($config['encryption'])) { + $transport->setEncryption($config['encryption']); + } + if (isset($config['username'])) { + $transport->setUsername($config['username']); + + $transport->setPassword($config['password']); + } + $this->mailer = new LaravelBoletoMailer('default', $this->view, new Swift_Mailer($transport)); + } + } + } + + /** + * @param array|string $from + * @return Mail + * @throws ValidationException + */ + private function setFrom($from) + { + if (is_string($from)) { + $this->from = ['address' => $from, 'name' => $from]; + } elseif (is_array($from) && isset($from['address'])) { + $this->from = ['address' => $from['address'], 'name' => Arr::get($from, 'name', $from['address'])]; + } elseif (is_array($from) && isset($from[0])) { + if (filter_var($from[0], FILTER_VALIDATE_EMAIL)) { + $this->from['address'] = $from[0]; + $this->from['name'] = Arr::get($from, 1, $from[0]); + } elseif (filter_var($from[1], FILTER_VALIDATE_EMAIL)) { + $this->from['address'] = $from[1]; + $this->from['name'] = Arr::get($from, 0, $from[1]); + } + } else { + throw new ValidationException('Email do Sender informado não é válido'); + } + + if (! $this->from['address'] || ! filter_var($this->from['address'], FILTER_VALIDATE_EMAIL)) { + throw new ValidationException('Email do Sender informado não é válido'); + } + + return $this; + } + + /** + * @param $template + * @return string + * @throws ValidationException + */ + private function build($template) + { + if (is_string($template)) { + return $template; + } + + if (is_array($template)) { + $view = Arr::get($template, 'view', Arr::get($template, 'template', Arr::get($template, 0))); + $data = Arr::get($template, 'data', Arr::get($template, 'vars', Arr::get($template, 1, []))); + + if (is_null($view)) { + throw new ValidationException("View não informada, Utilizar ['view' => 'template.blade.php', 'data'=> []]"); + } + + if (is_null($data)) { + throw new ValidationException("Data não informada, Utilizar ['view' => 'template.blade.php', 'data'=> []]"); + } + + $data['boleto'] = $this->getBoleto()->toArray(); + + if (file_exists($view)) { + return $this->getBlade()->render(file_get_contents($view), $data); + } + + if (file_exists(resource_path("views.$view"))) { + return $this->getBlade()->render(file_get_contents(resource_path("views.$view")), $data); + } + + return $this->getBlade()->render($view, $data); + } + + throw new ValidationException("Formato de texto inválido utilize o html completo ou ['view' => 'template.blade.php', 'data'=> []]"); + } + + /** + * @param array|string $to + * @return Mail + * @throws ValidationException + */ + public function setTo($to) + { + if (is_string($to)) { + $this->to = ['address' => $to, 'name' => $to]; + } elseif (is_array($to) && isset($to['address'])) { + $this->to = ['address' => $to['address'], 'name' => Arr::get($to, 'name', $to['address'])]; + } elseif (is_array($to) && isset($to[0])) { + if (filter_var($to[0], FILTER_VALIDATE_EMAIL)) { + $this->to['address'] = $to[0]; + $this->to['name'] = Arr::get($to, 1, $to[0]); + } elseif (filter_var($to[1], FILTER_VALIDATE_EMAIL)) { + $this->to['address'] = $to[1]; + $this->to['name'] = Arr::get($to, 0, $to[1]); + } + } else { + throw new ValidationException('Email do destinatário informado não é válido'); + } + + if (! $this->to['address'] || ! filter_var($this->to['address'], FILTER_VALIDATE_EMAIL)) { + throw new ValidationException('Email do destinatário informado não é válido'); + } + + return $this; + } + + /** + * @param $boleto + * @return Mail + * @throws ValidationException + */ + public function setBoleto($boleto) + { + if (! $boleto instanceof Boleto) { + throw new ValidationException('Boleto não é uma instancia válida de Boleto'); + } + $this->boleto = $boleto; + + return $this; + } + + /** + * @param $template + * @param $subject + * @param Boleto|null $boleto + * @param null $to + * @return bool + * @throws ValidationException + */ + public function send($template, $subject, Boleto $boleto = null, $to = null) + { + if ($to) { + $this->setTo($to); + } + if ($boleto) { + $this->setBoleto($boleto); + } + + if (! $this->getBoleto()) { + throw new ValidationException('Informe o boleto a ser enviado utilizando o método ->setBoleto ou passando #3 parâmetro no método ->send'); + } + if (! $this->getTo()) { + throw new ValidationException('Informe o destinatário utilizando o método ->setTo ou passando #4 parâmetro no método ->send'); + } + + try { + $html = $this->build($template); + + if (! LaravelBoletoMailer::isLaravel9Plus() && ! app()->bound(EmbedImages::class)) { + $this->getMailer()->getSwiftMailer()->registerPlugin(new SwiftEmbedImages(config()->get('mail-auto-embed'))); + } + + $this->getMailer()->html($html, function (Message $message) use ($subject) { + if (LaravelBoletoMailer::isLaravel9Plus()) { + $message + ->attachData($this->getPdf(), 'boleto.pdf', [ + 'mime' => 'application/pdf', + ]) + ->from($this->getFrom()['address'], $this->getFrom()['name']) + ->subject($subject) + ->to($this->getTo()['address'], $this->getTo()['name']); + } else { + $message + ->attachData($this->getPdf(), 'boleto.pdf', [ + 'mime' => 'application/pdf', + ]) + ->setFrom($this->getFrom()['address'], $this->getFrom()['name']) + ->setSubject($subject) + ->setTo($this->getTo()['address'], $this->getTo()['name']); + } + }); + + return true; + } catch (Throwable $e) { + return false; + } + } + + /** + * @param $template + * @param $subject + * @param $boletos + * @return array + * @throws ValidationException + */ + public function sendLote($template, $subject, $boletos) + { + $aRet = []; + foreach ($boletos as $email => $boleto) { + $aRet[$email] = $this->send($template, $subject, $boleto, $email); + } + + return $aRet; + } +} diff --git a/src/Boleto/Render/AbstractPdf.php b/src/Boleto/Render/AbstractPdf.php index 6989422a..7fc968cb 100644 --- a/src/Boleto/Render/AbstractPdf.php +++ b/src/Boleto/Render/AbstractPdf.php @@ -1,20 +1,43 @@ javascript = $script; + parent::__construct($orientation, $unit, $size); + $this->AliasNbPages('{1}'); } public function Footer() @@ -25,134 +48,28 @@ public function Footer() } } - protected function _putjavascript() - { - $this->_newobj(); - $this->n_js = $this->n; - $this->_out('<<'); - $this->_out('/Names [(EmbeddedJS) ' . ($this->n + 1) . ' 0 R]'); - $this->_out('>>'); - $this->_out('endobj'); - $this->_newobj(); - $this->_out('<<'); - $this->_out('/S /JavaScript'); - $this->_out('/JS ' . $this->_textstring($this->javascript)); - $this->_out('>>'); - $this->_out('endobj'); - } - - public function _putresources() - { - parent::_putresources(); - if (!empty($this->javascript)) { - $this->_putjavascript(); - } - } - - public function _putcatalog() - { - parent::_putcatalog(); - if (!empty($this->javascript)) { - $this->_out('/Names <n_js) . ' 0 R>>'); - } - } - - // create a new page group; call this before calling AddPage() public function StartPageGroup() { $this->NewPageGroup = true; } - // current page in the group public function GroupPageNo() { return $this->PageGroups[$this->CurrPageGroup]; } - // alias of the current page group -- will be replaced by the total number of pages in this group public function PageGroupAlias() { return $this->CurrPageGroup; } - public function _beginpage($orientation, $size, $rotation) - { - parent::_beginpage($orientation, $size, $rotation); - if ($this->NewPageGroup) { - // start a new group - if (!is_array($this->PageGroups)) { - $this->PageGroups = []; - } - $n = sizeof($this->PageGroups) + 1; - $alias = '{' . $n . '}'; - $this->PageGroups[$alias] = 1; - $this->CurrPageGroup = $alias; - $this->NewPageGroup = false; - } elseif ($this->CurrPageGroup) { - $this->PageGroups[$this->CurrPageGroup]++; - } - } - - public function _putpages() - { - $nb = $this->page; - if (!empty($this->PageGroups)) { - // do page number replacement - foreach ($this->PageGroups as $k => $v) { - for ($n = 1; $n <= $nb; $n++) { - $this->pages[$n] = str_replace($k, $v, $this->pages[$n]); - } - } - } - parent::_putpages(); - } - - protected function _() - { - $args = func_get_args(); - $var = utf8_decode(array_shift($args)); - $s = vsprintf($var, $args); - return $s; - } - - /** - * @param $w - * @param $h - * @param $txt - * @param $border - * @param $ln - * @param $align - * @param float $dec - */ - protected function textFitCell($w, $h, $txt, $border, $ln, $align, $dec = 0.1) - { - $fsize = $this->FontSizePt; - $size = $fsize; - while ($this->GetStringWidth($txt) > ($w - 2)) { - $this->SetFontSize($size -= $dec); - } - $this->Cell($w, $h, $txt, $border, $ln, $align); - $this->SetFontSize($fsize); - } - - /** - * BarCode - * - * @param $xpos - * @param $ypos - * @param $code - * @param int $basewidth - * @param int $height - * - * @throws \Exception - */ public function i25($xpos, $ypos, $code, $basewidth = 1, $height = 10) { $code = (strlen($code)%2 != 0 ? '0' : '') . $code; $wide = $basewidth; $narrow = $basewidth/3; - $barChar = array(); + $barChar = []; // wide/narrow codes for the digits $barChar['0'] = 'nnwwn'; $barChar['1'] = 'wnnnw'; @@ -205,11 +122,23 @@ public function i25($xpos, $ypos, $code, $basewidth = 1, $height = 10) } } - - public function __construct($orientation = 'P', $unit = 'mm', $size = 'A4') + public function SetProtection($user_pass = '', $permissions = [], $owner_pass = null) { - parent::__construct($orientation, $unit, $size); - $this->AliasNbPages('{1}'); + $options = ['print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32]; + $protection = 192; + foreach ($permissions as $permission) { + if (! isset($options[$permission])) { + $this->Error('Incorrect permission: ' . $permission); + } + $protection += $options[$permission]; + } + if ($owner_pass === null) { + $owner_pass = uniqid(rand()); + } + $this->encrypted = true; + $this->padding = "\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08" . + "\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A"; + $this->_generateencryptionkey($user_pass, $owner_pass, $protection); } /** @@ -219,14 +148,225 @@ public function __construct($orientation = 'P', $unit = 'mm', $size = 'A4') * D: send to the browser and force download.
* F: save to a local
* S: return as a string. name is ignored. - * @param bool $print 1 imprime 0 nao imprime * @return string */ - public function Output($name = '', $dest = 'I', $print = false) + public function Output($name = '', $dest = 'I', $isUTF8 = false) + { + return parent::Output($name, $dest, $isUTF8); + } + + protected function IncludeJS($script) + { + $this->javascript = $script; + } + + protected function _putresources() + { + parent::_putresources(); + if (! empty($this->javascript)) { + $this->_putjavascript(); + } + + if ($this->encrypted) { + $this->_newobj(); + $this->enc_obj_id = $this->n; + $this->_put('<<'); + $this->_putencryption(); + $this->_put('>>'); + $this->_put('endobj'); + } + } + + protected function _putjavascript() + { + $this->_newobj(); + $this->n_js = $this->n; + $this->_put('<<'); + $this->_put('/Names [(EmbeddedJS) ' . ($this->n + 1) . ' 0 R]'); + $this->_put('>>'); + $this->_put('endobj'); + $this->_newobj(); + $this->_put('<<'); + $this->_put('/S /JavaScript'); + $this->_put('/JS ' . $this->_textstring($this->javascript)); + $this->_put('>>'); + $this->_put('endobj'); + } + + protected function _putcatalog() + { + parent::_putcatalog(); + if (! empty($this->javascript)) { + $this->_put('/Names <n_js) . ' 0 R>>'); + } + } + + protected function _putencryption() + { + $this->_put('/Filter /Standard'); + $this->_put('/V 1'); + $this->_put('/R 2'); + $this->_put('/O (' . $this->_escape($this->Ovalue) . ')'); + $this->_put('/U (' . $this->_escape($this->Uvalue) . ')'); + $this->_put('/P ' . $this->Pvalue); + } + + protected function _beginpage($orientation, $size, $rotation) + { + parent::_beginpage($orientation, $size, $rotation); + if ($this->NewPageGroup) { + // start a new group + if (! is_array($this->PageGroups)) { + $this->PageGroups = []; + } + $n = sizeof($this->PageGroups) + 1; + $alias = '{' . $n . '}'; + $this->PageGroups[$alias] = 1; + $this->CurrPageGroup = $alias; + $this->NewPageGroup = false; + } elseif ($this->CurrPageGroup) { + $this->PageGroups[$this->CurrPageGroup]++; + } + } + + protected function _putpages() + { + $nb = $this->page; + if (! empty($this->PageGroups)) { + // do page number replacement + foreach ($this->PageGroups as $k => $v) { + for ($n = 1; $n <= $nb; $n++) { + $this->pages[$n] = str_replace($k, $v, $this->pages[$n]); + } + } + } + parent::_putpages(); + } + + protected function _putstream($s) + { + if ($this->encrypted) { + $s = $this->RC4($this->_objectkey($this->n), $s); + } + parent::_putstream($s); + } + + protected function _puttrailer() + { + parent::_puttrailer(); + if ($this->encrypted) { + $this->_put('/Encrypt ' . $this->enc_obj_id . ' 0 R'); + $this->_put('/ID [()()]'); + } + } + + protected function _textstring($s) + { + if (! $this->_isascii($s)) { + $s = $this->_UTF8toUTF16($s); + } + if ($this->encrypted) { + $s = $this->RC4($this->_objectkey($this->n), $s); + } + + return '(' . $this->_escape($s) . ')'; + } + + protected function _() + { + $args = func_get_args(); + $var = utf8_decode(array_shift($args)); + $s = vsprintf($var, $args); + + return $s; + } + + protected function textFitCell($w, $h, $txt, $border, $ln, $align, $dec = 0.1) { - if ($print) { - $this->IncludeJS("print('true');"); + $fsize = $this->FontSizePt; + $size = $fsize; + while ($this->GetStringWidth($txt) > ($w - 2)) { + $this->SetFontSize($size -= $dec); } - return parent::Output($name, $dest); + $this->Cell($w, $h, $txt, $border, $ln, $align); + $this->SetFontSize($fsize); + } + + protected function _generateencryptionkey($user_pass, $owner_pass, $protection) + { + // Pad passwords + $user_pass = substr($user_pass . $this->padding, 0, 32); + $owner_pass = substr($owner_pass . $this->padding, 0, 32); + // Compute O value + $this->Ovalue = $this->_Ovalue($user_pass, $owner_pass); + // Compute encyption key + $tmp = $this->_md5_16($user_pass . $this->Ovalue . chr($protection) . "\xFF\xFF\xFF"); + $this->encryption_key = substr($tmp, 0, 5); + // Compute U value + $this->Uvalue = $this->_Uvalue(); + // Compute P value + $this->Pvalue = -(($protection ^ 255) + 1); + } + + protected function _Ovalue($user_pass, $owner_pass) + { + $tmp = $this->_md5_16($owner_pass); + $owner_RC4_key = substr($tmp, 0, 5); + + return $this->RC4($owner_RC4_key, $user_pass); + } + + protected function _Uvalue() + { + return $this->RC4($this->encryption_key, $this->padding); + } + + protected function _md5_16($string) + { + return pack('H*', md5($string)); + } + + protected function _objectkey($n) + { + return substr($this->_md5_16($this->encryption_key . pack('VXxx', $n)), 0, 10); + } + + protected function RC4($key, $data) + { + if (function_exists('mcrypt_encrypt')) { + return mcrypt_encrypt(MCRYPT_ARCFOUR, $key, $data, MCRYPT_MODE_STREAM, ''); + } + + if ($key != $this->last_key) { + $k = str_repeat($key, 256 / strlen($key) + 1); + $state = range(0, 255); + $j = 0; + for ($i = 0; $i < 256; $i++) { + $t = $state[$i]; + $j = ($j + $t + ord($k[$i])) % 256; + $state[$i] = $state[$j]; + $state[$j] = $t; + } + $this->last_key = $key; + $this->last_state = $state; + } else { + $state = $this->last_state; + } + + $len = strlen($data); + $a = 0; + $b = 0; + $out = ''; + for ($i = 0; $i < $len; $i++) { + $a = ($a + 1) % 256; + $t = $state[$a]; + $b = ($b + $t) % 256; + $state[$a] = $state[$b]; + $state[$b] = $t; + $k = $state[($state[$a] + $state[$b]) % 256]; + $out .= chr(ord($data[$i]) ^ $k); + } + + return $out; } } diff --git a/src/Boleto/Render/Html.php b/src/Boleto/Render/Html.php index c695b03e..7f980973 100644 --- a/src/Boleto/Render/Html.php +++ b/src/Boleto/Render/Html.php @@ -1,16 +1,23 @@ localizacao_pix = $localizacao; + + return $this; + } + /** * @return \Illuminate\View\Factory - * @throws \Exception + * @throws ValidationException */ - private function getBlade() { + private function getBlade() + { if (!is_null($this->blade)) { return $this->blade; } - $instance = \Illuminate\Container\Container::getInstance(); - if (!is_null($instance) && $instance->resolved(\Illuminate\Contracts\View\Factory::class)) { + $instance = Container::getInstance(); + if (! is_null($instance) && $instance->resolved(Factory::class)) { view()->addNamespace('BoletoHtmlRender', realpath(__DIR__ . '/view/')); $this->blade = view(); } else { @@ -51,50 +80,64 @@ private function getBlade() { $blade->directive('endphp', function($expression) { return ' ?>'; }); + return $this->blade; } /** - * Addiciona o boletos + * Adiciona o boletos * * @param array $boletos * - * @return $this + * @return Html + * @throws ValidationException */ public function addBoletos(array $boletos) { foreach ($boletos as $boleto) { $this->addBoleto($boleto); } + return $this; } /** - * Addiciona o boleto + * Adiciona o boleto * * @param BoletoContract $boleto * - * @return $this + * @return Html + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { + if (! $boleto->imprimeBoleto()) { + throw new ValidationException('Boleto com modalidade/carteira não disponível para impressão'); + } $dados = $boleto->toArray(); $dados['codigo_barras'] = $this->getImagemCodigoDeBarras($dados['codigo_barras']); $this->boleto[] = $dados; + return $this; } + /** - * @return $this + * @return Html */ - public function hideInstrucoes() { + public function hideInstrucoes() + { $this->showInstrucoes = false; + return $this; } + /** - * @return $this + * @return Html */ - public function showPrint() { + public function showPrint() + { $this->print = true; + return $this; } @@ -103,7 +146,9 @@ public function showPrint() { */ protected function writeCss() { - return "@media print{.noprint{display:none}}body{background-color:#fff;margin-right:0}.wrapper{width:666px;}.table-boleto{font:9px Arial;width:666px}.table-boleto td.top-2{border-top-width: 2px;}.table-boleto td{border-left:1px solid #000;border-top:1px solid #000;padding:1px 4px}.table-boleto td:last-child{border-right:1px solid #000}.table-boleto .titulo{color:#003}.linha-pontilhada{height:15px;color:#003;font:9px Arial;width:100%;border-bottom:1px dashed #000;text-align:right;margin-bottom:10px}.table-boleto .conteudo{font:700 10px Arial;height:13px}.table-boleto .sacador{display:inline;margin-left:5px}.table-boleto .noleftborder{border-left:none!important}.table-boleto .notopborder{border-top:none!important}.table-boleto .norightborder{border-right:none!important}.table-boleto .noborder{border:none!important}.table-boleto .bottomborder{border-bottom:1px solid #000!important}.table-boleto .rtl{text-align:right}.table-boleto .logobanco{display:inline-block;max-width:150px}.table-boleto .logocontainer{width:257px;display:inline-block}.table-boleto .logobanco img{margin-bottom:-5px}.table-boleto .codbanco{font:700 20px Arial;padding:1px 5px;display:inline;border-left:2px solid #000;border-right:2px solid #000;width:51px;margin-left:0px}.table-boleto .linha-digitavel{font:700 14px Arial;display:inline-block;width:406px;text-align:right}.table-boleto .nopadding{padding:0!important}.table-boleto .caixa-gray-bg{font-weight:700;background:#ccc}.info,.info-empresa{font:11px Arial}.header{font:700 13px Arial;display:block;margin:4px}.barcode{height:50px}.barcode div{display:inline-block;height:100%}.barcode .black{border-color:#000;border-left-style:solid;width:0}.barcode .white{background:#fff}.barcode .thin.black{border-left-width:1px}.barcode .large.black{border-left-width:3px}.barcode .thin.white{width:1px}.barcode .large.white{width:3px}.table-boleto tr.duas-linhas{vertical-align:top}"; + $black = $this->localizacao_pix == self::PIX_COD_BARRAS ? 2 : 3; + + return "@media print{.noprint{display:none}}body{background-color:#fff;margin-right:0}.wrapper{width:666px;}.table-boleto{font:9px Arial;width:666px}.table-boleto td.top-2{border-top-width: 2px;}.table-boleto td{border-left:1px solid #000;border-top:1px solid #000;padding:1px 4px}.table-boleto td:last-child{border-right:1px solid #000}.table-boleto .titulo{color:#003}.linha-pontilhada{height:15px;color:#003;font:9px Arial;width:100%;border-bottom:1px dashed #000;text-align:right;margin-bottom:10px}.table-boleto .conteudo{font:700 10px Arial;height:13px}.table-boleto .sacador{display:inline;margin-left:5px}.table-boleto .noleftborder{border-left:none!important}.table-boleto .notopborder{border-top:none!important}.table-boleto .norightborder{border-right:none!important}.table-boleto .noborder{border:none!important}.table-boleto .bottomborder{border-bottom:1px solid #000!important}.table-boleto .rtl{text-align:right}.table-boleto .logobanco{display:inline-block;max-width:150px}.table-boleto .logocontainer{width:257px;display:inline-block}.table-boleto .logobanco img{margin-bottom:-5px}.table-boleto .codbanco{font:700 20px Arial;padding:1px 5px;display:inline;border-left:2px solid #000;border-right:2px solid #000;width:51px;margin-left:0px}.table-boleto .linha-digitavel{font:700 14px Arial;display:inline-block;width:406px;text-align:right}.table-boleto .nopadding{padding:0!important}.table-boleto .caixa-gray-bg{font-weight:700;background:#ccc}.info,.info-empresa{font:11px Arial}.header{font:700 13px Arial;display:block;margin:4px}.barcode{height:50px; display:inline-block}.barcode div{display:inline-block;height:100%}.barcode .black{border-color:#000;border-left-style:solid;width:0}.barcode .white{background:#fff}.barcode .thin.black{border-left-width:1px}.barcode .large.black{border-left-width:{$black}px}.barcode .thin.white{width:1px}.barcode .large.white{width:3px}.table-boleto tr.duas-linhas{vertical-align:top}"; } /** @@ -120,7 +165,7 @@ public function getImagemCodigoDeBarras($codigo_barras) for ($f1 = 9; $f1 >= 0; $f1--) { for ($f2 = 9; $f2 >= 0; $f2--) { $f = ($f1*10) + $f2; - $texto = ""; + $texto = ''; for ($i = 1; $i < 6; $i++) { $texto .= substr($barcodes[$f1], ($i - 1), 1) . substr($barcodes[$f2], ($i - 1), 1); } @@ -141,13 +186,13 @@ public function getImagemCodigoDeBarras($codigo_barras) $codigo_barras = substr($codigo_barras, strlen($codigo_barras) - (strlen($codigo_barras) - 2), strlen($codigo_barras) - 2); $f = $barcodes[$i]; for ($i = 1; $i < 11; $i += 2) { - if (substr($f, ($i - 1), 1) == "0") { + if (substr($f, ($i - 1), 1) == '0') { $f1 = 'thin'; } else { $f1 = 'large'; } $retorno .= "
"; - if (substr($f, $i, 1) == "0") { + if (substr($f, $i, 1) == '0') { $f2 = 'thin'; } else { $f2 = 'large'; @@ -167,15 +212,16 @@ public function getImagemCodigoDeBarras($codigo_barras) * função para gerar o boleto * * @return string - * @throws \Exception + * @throws ValidationException */ public function gerarBoleto() { if (count($this->boleto) == 0) { - throw new \Exception('Nenhum Boleto adicionado'); + throw new ValidationException('Nenhum Boleto adicionado'); } return $this->getBlade()->make('BoletoHtmlRender::boleto', [ + 'localizacao_pix' => $this->localizacao_pix, 'boletos' => $this->boleto, 'css' => $this->writeCss(), 'imprimir_carregamento' => (bool) $this->print, @@ -187,15 +233,16 @@ public function gerarBoleto() * função para gerar o carne * * @return string - * @throws \Exception + * @throws ValidationException */ public function gerarCarne() { if (count($this->boleto) == 0) { - throw new \Exception('Nenhum Boleto adicionado'); + throw new ValidationException('Nenhum Boleto adicionado'); } return $this->getBlade()->make('BoletoHtmlRender::carne', [ + 'localizacao_pix' => $this->localizacao_pix, 'boletos' => $this->boleto, 'css' => $this->writeCss(), 'imprimir_carregamento' => (bool) $this->print, diff --git a/src/Boleto/Render/Pdf.php b/src/Boleto/Render/Pdf.php index e0657df1..e1a1b3be 100644 --- a/src/Boleto/Render/Pdf.php +++ b/src/Boleto/Render/Pdf.php @@ -2,10 +2,11 @@ namespace VinicciusGuedes\LaravelCnab\Boleto\Render; +use Illuminate\Support\Str; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Render\Pdf as PdfContract; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Str; class Pdf extends AbstractPdf implements PdfContract { @@ -13,8 +14,11 @@ class Pdf extends AbstractPdf implements PdfContract const OUTPUT_DOWNLOAD = 'D'; const OUTPUT_SAVE = 'F'; const OUTPUT_STRING = 'S'; + const PIX_INSTRUCAO = 'instrucao'; + const PIX_COD_BARRAS = 'barras'; protected $PadraoFont = 'Arial'; + /** * @var BoletoContract[] */ @@ -31,12 +35,19 @@ class Pdf extends AbstractPdf implements PdfContract protected $showInstrucoes = true; protected $desc = 3; // tamanho célula descrição + protected $cell = 4; // tamanho célula dado + protected $fdes = 6; // tamanho fonte descrição + protected $fcel = 8; // tamanho fonte célula + protected $small = 0.2; // tamanho barra fina + protected $totalBoletos = 0; + protected $localizacao_pix = self::PIX_INSTRUCAO; + public function __construct() { parent::__construct('P', 'mm', 'A4'); @@ -48,9 +59,25 @@ public function __construct() } /** - * @param integer $i + * @param $localizacao + * @return Pdf + * @throws ValidationException + */ + public function setLocalizacaoPix($localizacao) + { + if (! in_array($localizacao, [self::PIX_COD_BARRAS, self::PIX_INSTRUCAO])) { + throw new ValidationException('Pix deve ser Pdf::PIX_COD_BARRAS ou Pdf::PIX_INSTRUCAO'); + } + + $this->localizacao_pix = $localizacao; + + return $this; + } + + /** + * @param int $i * - * @return $this + * @return Pdf */ protected function instrucoes($i) { @@ -59,7 +86,7 @@ protected function instrucoes($i) $this->SetAutoPageBreak(true); $this->SetY(5); $this->Cell(30, 10, date('d/m/Y H:i:s')); - $this->Cell(0, 10, "Boleto " . ($i + 1) . " de " . $this->totalBoletos, 0, 1, 'R'); + $this->Cell(0, 10, 'Boleto ' . ($i + 1) . ' de ' . $this->totalBoletos, 0, 1, 'R'); } $this->SetFont($this->PadraoFont, 'B', 8); @@ -93,15 +120,15 @@ protected function instrucoes($i) $this->SetFont($this->PadraoFont, '', $this->fcel); } - $this->traco('Recibo do Pagador', 4); + return $this; } /** - * @param integer $i + * @param int $i * - * @return $this + * @return Pdf */ protected function logoEmpresa($i) { @@ -128,9 +155,9 @@ protected function logoEmpresa($i) } /** - * @param integer $i + * @param int $i * - * @return $this + * @return Pdf */ protected function Topo($i) { @@ -207,9 +234,9 @@ protected function Topo($i) } /** - * @param integer $i + * @param int $i * - * @return $this + * @return Pdf */ protected function Bottom($i) { @@ -242,7 +269,7 @@ protected function Bottom($i) $this->Ln(4); $this->SetFont($this->PadraoFont, 'B', $this->fcel); $this->Cell(120, $this->cell, $this->_($this->boleto[$i]->getBeneficiario()->getEnderecoCompleto()), 'LR'); - $this->Cell(50, $this->cell, "", 'R', 1, 'R'); + $this->Cell(50, $this->cell, '', 'R', 1, 'R'); } $this->SetFont($this->PadraoFont, '', $this->fdes); @@ -277,7 +304,7 @@ protected function Bottom($i) $this->Cell(12, $this->desc, $this->_('Espécie'), 'TR'); $this->Cell(28, $this->desc, $this->_('Quantidade'), 'TR'); - $this->Cell(25, $this->desc, $this->_(($this->boleto[$i]->getCodigoBanco() == '104') ? 'xValor' : 'Valor Documento'), 'TR'); + $this->Cell(25, $this->desc, $this->_('Valor Documento'), 'TR'); $this->Cell(50, $this->desc, $this->_('Valor Documento'), 'TR', 1); $this->SetFont($this->PadraoFont, 'B', $this->fcel); @@ -298,17 +325,20 @@ protected function Bottom($i) $this->Cell(25, $this->cell, $this->_(($this->boleto[$i]->getCodigoBanco() == '001') ? Util::nReal($this->boleto[$i]->getValor()) : ''), 'R'); $this->Cell(50, $this->cell, $this->_(Util::nReal($this->boleto[$i]->getValor())), 'R', 1, 'R'); + $yStartPix = $this->GetY(); $this->SetFont($this->PadraoFont, '', $this->fdes); - $this->Cell(120, $this->desc, $this->_("Instruções de responsabilidade do beneficiário. Qualquer dúvida sobre este boleto, contate o beneficiário"), 'TLR'); + $this->Cell(95, $this->desc, $this->_('Instruções de responsabilidade do beneficiário. '), 'TL'); + $xStartPix = $this->GetX(); + $this->Cell(25, $this->desc, '', 'TR'); $this->Cell(50, $this->desc, $this->_('(-) Desconto / Abatimentos)'), 'TR', 1); - $xInstrucoes = $this->GetX(); - $yInstrucoes = $this->GetY(); - $this->SetFont($this->PadraoFont, '', $this->fdes); - $this->Cell(120, $this->cell, $this->_(''), 'LR'); + $this->Cell(120, $this->cell, $this->_('Qualquer dúvida sobre este boleto, contate o beneficiário'), 'LR'); $this->Cell(50, $this->cell, $this->_(''), 'R', 1); + $xInstrucoes = $this->GetX(); + $yInstrucoes = $this->GetY(); + $this->Cell(120, $this->desc, $this->_(''), 'LR'); $this->Cell(50, $this->desc, $this->_('(-) Outras deduções'), 'TR', 1); @@ -333,6 +363,8 @@ protected function Bottom($i) $this->Cell(120, $this->cell, $this->_(''), 'BLR'); $this->Cell(50, $this->cell, $this->_(''), 'BR', 1); + $yEndPix = $this->GetY(); + $this->SetFont($this->PadraoFont, '', $this->fdes); $this->Cell(0, $this->desc, $this->_('Pagador'), 'LR', 1); @@ -348,7 +380,7 @@ protected function Bottom($i) $this->Cell(38, $this->cell, $this->_(''), 'BR', 1); $this->SetFont($this->PadraoFont, '', $this->fdes); - $this->Cell(20, $this->desc, $this->_('Sacador/Avalista'), 0); + $this->Cell(20, $this->desc, $this->_('Beneficiário Final'), 0); $this->Cell(98, $this->desc, $this->_($this->boleto[$i]->getSacadorAvalista() ? $this->boleto[$i]->getSacadorAvalista()->getNomeDocumento() : ''), 0); $this->Cell(52, $this->desc, $this->_('Autenticação mecânica - Ficha de Compensação'), 0, 1); @@ -365,14 +397,13 @@ protected function Bottom($i) $this->SetXY($xOriginal, $yOriginal); } - if ($this->boleto[$i]->getPixQrCode() !== null){ - $img = explode(',',$this->boleto[$i]->getPixQrCode(),2)[1]; - $pic = 'data://text/plain;base64,'. $img; - - $this->SetXY(112, 216); - $this->SetFont($this->PadraoFont, '', 6); - $this->Cell(60, $this->cell, "Pague via PIX", "", "", "L"); - $this->Image($pic, 110,220,20,20,'png'); + if ($this->boleto[$i]->getPixQrCode() !== null && $this->localizacao_pix == self::PIX_INSTRUCAO) { + $this->SetXY($xStartPix, $yStartPix); + $this->SetFont($this->PadraoFont, 'B', $this->fcel); + $this->Cell(25, 6, 'Pague com PIX', '', '', 'C'); + $this->SetFont($this->PadraoFont, '', $this->fdes); + $this->Image($this->boleto[$i]->getPixQrCodeBase64(), $xStartPix + 1, $yStartPix + 8, 23, 23, 'png'); + $this->Line($xStartPix, $yStartPix, $xStartPix, $yEndPix); $this->SetXY($xOriginal, $yOriginal); } @@ -382,8 +413,8 @@ protected function Bottom($i) /** * @param string $texto - * @param integer $ln - * @param integer $ln2 + * @param int $ln + * @param int $ln2 * @param $posicaoTexto * @param $alinhamentoTexto * @param $tamanho @@ -407,22 +438,48 @@ protected function traco($texto, $ln = null, $ln2 = null, $posicaoTexto = 1, $al } /** - * @param integer $i + * @param int $i */ protected function codigoBarras($i) { + $yOriginal = $this->GetY(); + $xOriginal = $this->GetX(); $this->Ln(3); $this->Cell(0, 15, '', 0, 1, 'L'); - $this->i25($this->GetX(), $this->GetY() - 15, $this->boleto[$i]->getCodigoBarras(), 1, 17); + $this->i25($this->GetX(), $this->GetY() - 15, $this->boleto[$i]->getCodigoBarras(), .9, 17); + + if ($this->boleto[$i]->getPixQrCode() !== null && $this->localizacao_pix == self::PIX_COD_BARRAS) { + $this->SetXY(142, $yOriginal + 2); + $this->SetFont($this->PadraoFont, 'B', $this->fcel); + $this->Cell(0, 6, 'Pague com PIX', '', 1, 'L'); + $this->SetX(142); + $this->SetFont($this->PadraoFont, 'B', $this->fdes); + $this->Cell(13, 6, 'Vencimento:', '', 0, 'L'); + $this->SetFont($this->PadraoFont, '', $this->fdes); + $this->Cell(0, 6, $this->boleto[$i]->getDataVencimento()->format('d/m/Y'), '', 1, 'L'); + $this->SetX(142); + $this->SetFont($this->PadraoFont, 'B', $this->fdes); + $this->Cell(13, 6, 'Valor:', '', 0, 'L'); + $this->SetFont($this->PadraoFont, '', $this->fdes); + $this->Cell(0, 6, Util::nReal($this->boleto[$i]->getValor()), '', 1, 'L'); +// $this->Cell(0, $this->cell, 'Pague com PIX', '', 1, 'C'); +// $this->Image($this->boleto[$i]->getPixQrCodeBase64(), $xStartPix + 1, $yStartPix + 5, 23, 23, 'png'); +// $this->Line($xStartPix, $yStartPix, $xStartPix, $yEndPix); + + $this->Image($this->boleto[$i]->getPixQrCodeBase64(), 170, $yOriginal + 1, 20, 20, 'png'); + + $this->SetXY($xOriginal, $yOriginal); + } } /** - * Addiciona o boletos + * Adiciona o boletos * * @param array $boletos * @param bool $withGroup * - * @return $this + * @return Pdf + * @throws ValidationException */ public function addBoletos(array $boletos, $withGroup = true) { @@ -438,50 +495,57 @@ public function addBoletos(array $boletos, $withGroup = true) } /** - * Addiciona o boleto + * Adiciona o boleto * * @param BoletoContract $boleto * - * @return $this + * @return Pdf + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { + if (! $boleto->imprimeBoleto()) { + throw new ValidationException('Boleto com modalidade/carteira não disponível para impressão'); + } $this->totalBoletos += 1; $this->boleto[] = $boleto; + return $this; } /** - * @return $this + * @return Pdf */ public function hideInstrucoes() { $this->showInstrucoes = false; + return $this; } /** - * @return $this + * @return Pdf */ public function showPrint() { $this->print = true; + return $this; } /** - * função para gerar o boleto + * Função para gerar o boleto * * @param string $dest tipo de destino const BOLETOPDF_DEST_STANDARD | BOLETOPDF_DEST_DOWNLOAD | BOLETOPDF_DEST_SAVE | BOLETOPDF_DEST_STRING * @param null $save_path * * @return string - * @throws \Exception + * @throws ValidationException */ public function gerarBoleto($dest = self::OUTPUT_STANDARD, $save_path = null, $nameFile = null) { if ($this->totalBoletos == 0) { - throw new \Exception('Nenhum Boleto adicionado'); + throw new ValidationException('Nenhum Boleto adicionado'); } for ($i = 0; $i < $this->totalBoletos; $i++) { @@ -489,20 +553,26 @@ public function gerarBoleto($dest = self::OUTPUT_STANDARD, $save_path = null, $n $this->AddPage(); $this->instrucoes($i)->logoEmpresa($i)->Topo($i)->Bottom($i)->codigoBarras($i); } + + if ($this->print) { + $this->IncludeJS("print('true');"); + } + if ($dest == self::OUTPUT_SAVE) { - $this->Output($save_path, $dest, $this->print); + $this->Output($save_path, $dest); + return $save_path; } if ($nameFile == null) { $nameFile = Str::random(32); } - - return $this->Output($nameFile . '.pdf', $dest, $this->print); + + return $this->Output($nameFile . '.pdf', $dest); } /** * @param $lista - * @param integer $pulaLinha + * @param int $pulaLinha * * @return int */ @@ -510,9 +580,9 @@ protected function listaLinhas($lista, $pulaLinha) { foreach ($lista as $d) { $pulaLinha -= 2; - $this->MultiCell(0, $this->cell - 0.2, $this->_(preg_replace('/(%)/', '%$1', $d)), 0, 1); + $this->MultiCell(0, $this->cell - 0.2, $this->_(preg_replace('/(%)/', '%$1', $d ?? '')), 0, 1); } return $pulaLinha; } -} \ No newline at end of file +} diff --git a/src/Boleto/Render/PdfCaixa.php b/src/Boleto/Render/PdfCaixa.php index fe7c48b0..7bf541e8 100644 --- a/src/Boleto/Render/PdfCaixa.php +++ b/src/Boleto/Render/PdfCaixa.php @@ -2,24 +2,27 @@ namespace VinicciusGuedes\LaravelCnab\Boleto\Render; +use Illuminate\Support\Str; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Render\Pdf as PdfContract; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Str; class PdfCaixa extends AbstractPdf implements PdfContract { - const OUTPUT_STANDARD = 'I'; const OUTPUT_DOWNLOAD = 'D'; const OUTPUT_SAVE = 'F'; const OUTPUT_STRING = 'S'; + const PIX_INSTRUCAO = 'instrucao'; + const PIX_COD_BARRAS = 'barras'; private $PadraoFont = 'Arial'; + /** * @var BoletoContract[] */ - private $boleto = array(); + private $boleto = []; /** * @var bool @@ -31,14 +34,20 @@ class PdfCaixa extends AbstractPdf implements PdfContract */ private $showInstrucoes = true; - private $desc = 3; // tamanho célula descrição + private $cell = 4; // tamanho célula dado + private $fdes = 6; // tamanho fonte descrição + private $fcel = 8; // tamanho fonte célula + private $small = 0.2; // tamanho barra fina + private $totalBoletos = 0; + protected $localizacao_pix = self::PIX_INSTRUCAO; + public function __construct() { parent::__construct('P', 'mm', 'A4'); @@ -50,9 +59,25 @@ public function __construct() } /** - * @param integer $i + * @param $localizacao + * @return PdfCaixa + * @throws ValidationException + */ + public function setLocalizacaoPix($localizacao) + { + if (! in_array($localizacao, [self::PIX_COD_BARRAS, self::PIX_INSTRUCAO])) { + throw new ValidationException('Pix deve ser Pdf::PIX_COD_BARRAS ou Pdf::PIX_INSTRUCAO'); + } + + $this->localizacao_pix = $localizacao; + + return $this; + } + + /** + * @param int $i * - * @return $this + * @return PdfCaixa */ protected function instrucoes($i) { @@ -61,7 +86,7 @@ protected function instrucoes($i) $this->SetAutoPageBreak(true); $this->SetY(5); $this->Cell(30, 10, date('d/m/Y H:i:s')); - $this->Cell(0, 10, "Boleto " . ($i + 1) . " de " . $this->totalBoletos, 0, 1, 'R'); + $this->Cell(0, 10, 'Boleto ' . ($i + 1) . ' de ' . $this->totalBoletos, 0, 1, 'R'); } $this->SetFont($this->PadraoFont, 'B', 8); @@ -96,13 +121,14 @@ protected function instrucoes($i) } $this->traco('Recibo do Pagador', 4); + return $this; } /** - * @param integer $i + * @param int $i * - * @return $this + * @return PdfCaixa */ protected function logoEmpresa($i) { @@ -129,9 +155,9 @@ protected function logoEmpresa($i) } /** - * @param integer $i + * @param int $i * - * @return $this + * @return PdfCaixa */ protected function Topo($i) { @@ -165,7 +191,7 @@ protected function Topo($i) $this->Cell(34, $this->cell, $this->_($this->boleto[$i]->getBeneficiario()->getDocumento(), '##.###.###/####-##'), 'R'); //algoritmo que calcula digito verificador beneficiario - $codBenefCaixa = strVal($this->boleto[$i]->getConta()); + $codBenefCaixa = strval($this->boleto[$i]->getConta()); if(!empty($codBenefCaixa)){ $j = 2; $aux = -1; @@ -217,7 +243,7 @@ protected function Topo($i) //quinta linha $this->SetFont($this->PadraoFont, '', $this->fdes); - $this->Cell(0, $this->desc, $this->_("Instruções (Texto de responsabilidade do Beneficiário):"), 'TLR'); + $this->Cell(0, $this->desc, $this->_('Instruções (Texto de responsabilidade do Beneficiário):'), 'TLR'); $this->SetFont($this->PadraoFont, 'B', $this->fcel); $xInstrucoes = $this->GetX(); @@ -237,7 +263,6 @@ protected function Topo($i) $this->Cell(0, 20, $this->_(''), 'LR',1); } - //sexta linha $this->SetFont($this->PadraoFont, '', $this->fdes); $this->Cell(100, $this->desc, $this->_('Pagador: '), 'TL'); @@ -288,9 +313,9 @@ protected function Topo($i) } /** - * @param integer $i + * @param int $i * - * @return $this + * @return PdfCaixa */ protected function Bottom($i) { @@ -317,7 +342,7 @@ protected function Bottom($i) $this->Cell(120, $this->cell, $this->_($this->boleto[$i]->getBeneficiario()->getNome() . ' ' .$this->boleto[$i]->getBeneficiario()->getDocumento()),'LR'); //algoritmo que calcula digito verificador beneficiario - $codBenefCaixa = strVal($this->boleto[$i]->getConta()); + $codBenefCaixa = strval($this->boleto[$i]->getConta()); if(!empty($codBenefCaixa)){ $j = 2; $aux = -1; @@ -343,7 +368,6 @@ protected function Bottom($i) $this->Cell(120, $this->desc, $this->_($this->boleto[$i]->getBeneficiario()->getEndereco() . ' - '. $this->boleto[$i]->getBeneficiario()->getBairro()), 'LR'); $this->Cell(50, $this->desc, $this->_(''), 'LR', 1); - $this->SetFont($this->PadraoFont, '', $this->fdes); $this->Cell(30, $this->desc, $this->_('Data do documento'), 'TLR'); $this->Cell(25, $this->desc, $this->_('Nr. do documento'), 'TR'); @@ -376,7 +400,7 @@ protected function Bottom($i) $this->Cell(20, $this->desc, $this->_('Espécie Moeda'), 'TR'); $this->Cell(20, $this->desc, $this->_('Qtde Moeda'), 'TR'); - $this->Cell(25, $this->desc, $this->_(($this->boleto[$i]->getCodigoBanco() == '104') ? 'xValor' : 'Valor Documento'), 'TR'); + $this->Cell(25, $this->desc, $this->_(($this->boleto[$i]->getCodigoBanco() == '104') ? 'Valor' : 'Valor Documento'), 'TR'); $this->Cell(50, $this->desc, $this->_('(=) Valor Documento'), 'TR', 1); $this->SetFont($this->PadraoFont, 'B', $this->fcel); @@ -397,9 +421,16 @@ protected function Bottom($i) $this->Cell(25, $this->cell, $this->_(''), 'R'); $this->Cell(50, $this->cell, $this->_(Util::nReal($this->boleto[$i]->getValor())), 'R', 1, 'R'); + $yStartPix = $this->GetY(); + $this->SetFont($this->PadraoFont, '', $this->fdes); + $this->Cell(95, $this->desc, $this->_('Instruções de responsabilidade do beneficiário. '), 'TL'); + $xStartPix = $this->GetX(); + $this->Cell(25, $this->desc, '', 'TR'); + $this->Cell(50, $this->desc, $this->_('(-) Desconto)'), 'TR', 1); + $this->SetFont($this->PadraoFont, '', $this->fdes); - $this->Cell(120, $this->desc, $this->_("Instruções de responsabilidade do beneficiário. Qualquer dúvida sobre este boleto, contate o beneficiário"), 'TLR'); - $this->Cell(50, $this->desc, $this->_('(-) Desconto'), 'TR', 1); + $this->Cell(120, $this->cell, $this->_('Qualquer dúvida sobre este boleto, contate o beneficiário'), 'LR'); + $this->Cell(50, $this->cell, $this->_(''), 'R', 1); $xInstrucoes = $this->GetX(); $yInstrucoes = $this->GetY(); @@ -448,13 +479,12 @@ protected function Bottom($i) $this->Cell(170, $this->desc, $this->_($this->boleto[$i]->getPagador()->getEndereco()), 'L',1); $this->SetFont($this->PadraoFont, '', $this->fdes); - $this->Cell(110, $this->desc, $this->_('Sacador/Avalista:'), 'L'); + $this->Cell(110, $this->desc, $this->_('Beneficiário Final:'), 'L'); $this->Cell(60, $this->desc, $this->_('CPF/CNPJ:'), 'R',1); $this->SetFont($this->PadraoFont, 'B', $this->fcel); $this->Cell(110, $this->cell, $this->_($this->boleto[$i]->getSacadorAvalista() ? $this->boleto[$i]->getSacadorAvalista()->getNome() : ''), 'BL'); $this->Cell(60, $this->cell, $this->_($this->boleto[$i]->getSacadorAvalista() ? $this->boleto[$i]->getSacadorAvalista()->getDocumento(): ''), 'BR', 1); - $xOriginal = $this->GetX(); $yOriginal = $this->GetY(); @@ -467,11 +497,21 @@ protected function Bottom($i) $this->SetXY($xOriginal, $yOriginal); } + + if ($this->boleto[$i]->getPixQrCode() !== null) { + $this->SetXY($xStartPix, $yStartPix); + $this->SetFont($this->PadraoFont, '', $this->fdes); + $this->Cell(25, $this->cell, 'Pague via PIX', '', '', 'C'); + $this->Image($this->boleto[$i]->getPixQrCodeBase64(), $xStartPix + 1, $yStartPix + 5, 23, 23, 'png'); + $this->Line($xStartPix, $yStartPix, $xStartPix, $yEndPix); + + $this->SetXY($xOriginal, $yOriginal); + } + $this->SetFont($this->PadraoFont, '', $this->fdes); $this->Cell(120, $this->desc, $this->_('')); $this->Cell(50, $this->desc, $this->_('Autenticação Mecânica - Ficha de Compensação'), 'LR',1); - $this->Cell(120, 15, '', 0, 1, 'LR'); $this->i25($this->GetX(), $this->GetY() - 15, $this->boleto[$i]->getCodigoBarras(), 0.8, 17); //$this->Cell(170, $this->desc, $this->_(''), 'LR',1,'R'); @@ -479,13 +519,14 @@ protected function Bottom($i) $msgSac = 'SAC CAIXA: 0800 726 0101 (informações, reclamações, sugestões e elogios) Para pessoas com deficiência auditiva ou de fala: 0800 726 2492 Ouvidoria: 0800 725 7474 caixa.gov.br'; $this->SetFont($this->PadraoFont, '', $this->fdes); $this->Cell(0, 10, $this->_($msgSac)); + return $this; } /** * @param string $texto - * @param integer $ln - * @param integer $ln2 + * @param int $ln + * @param int $ln2 */ protected function traco($texto, $ln = null, $ln2 = null) { @@ -503,7 +544,7 @@ protected function traco($texto, $ln = null, $ln2 = null) } /** - * @param integer $i + * @param int $i */ protected function codigoBarras($i) { @@ -518,7 +559,8 @@ protected function codigoBarras($i) * @param array $boletos * @param bool $withGroup * - * @return $this + * @return PdfCaixa + * @throws ValidationException */ public function addBoletos(array $boletos, $withGroup = true) { @@ -538,30 +580,36 @@ public function addBoletos(array $boletos, $withGroup = true) * * @param BoletoContract $boleto * - * @return $this + * @return PdfCaixa */ public function addBoleto(BoletoContract $boleto) { + if (! $boleto->imprimeBoleto()) { + throw new ValidationException('Boleto com modalidade/carteira não disponível para impressão'); + } $this->totalBoletos += 1; $this->boleto[] = $boleto; + return $this; } /** - * @return $this + * @return PdfCaixa */ public function hideInstrucoes() { $this->showInstrucoes = false; + return $this; } /** - * @return $this + * @return PdfCaixa */ public function showPrint() { $this->print = true; + return $this; } @@ -572,12 +620,12 @@ public function showPrint() * @param null $save_path * * @return string - * @throws \Exception + * @throws ValidationException */ public function gerarBoleto($dest = self::OUTPUT_STANDARD, $save_path = null, $nameFile = null) { if ($this->totalBoletos == 0) { - throw new \Exception('Nenhum Boleto adicionado'); + throw new ValidationException('Nenhum Boleto adicionado'); } for ($i = 0; $i < $this->totalBoletos; $i++) { @@ -587,6 +635,7 @@ public function gerarBoleto($dest = self::OUTPUT_STANDARD, $save_path = null, $n } if ($dest == self::OUTPUT_SAVE) { $this->Output($save_path, $dest, $this->print); + return $save_path; } if ($nameFile == null) { @@ -598,7 +647,7 @@ public function gerarBoleto($dest = self::OUTPUT_STANDARD, $save_path = null, $n /** * @param $lista - * @param integer $pulaLinha + * @param int $pulaLinha * * @return int */ diff --git a/src/Boleto/Render/compiled/.gitignore b/src/Boleto/Render/compiled/.gitignore new file mode 100644 index 00000000..c96a04f0 --- /dev/null +++ b/src/Boleto/Render/compiled/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/src/Boleto/Render/view/boleto.blade.php b/src/Boleto/Render/view/boleto.blade.php index a1ac9fa6..1669df9f 100644 --- a/src/Boleto/Render/view/boleto.blade.php +++ b/src/Boleto/Render/view/boleto.blade.php @@ -33,7 +33,7 @@ @endif -
Recibo do pagador
+
Recibo do pagador
@if ($logo) @@ -56,7 +56,8 @@
- logo do banco + logo do banco
{{ $codigo_banco_com_dv }}
diff --git a/src/Boleto/Render/view/caixa.blade.php b/src/Boleto/Render/view/caixa.blade.php index e1461aa5..e3923400 100644 --- a/src/Boleto/Render/view/caixa.blade.php +++ b/src/Boleto/Render/view/caixa.blade.php @@ -6,11 +6,19 @@

Instruções de Impressão

Linha Digitável: {{ $linha_digitavel }} Número: {{ $numero }} @@ -23,7 +31,7 @@
@if ($logo)
- logo + logo
@endif
@@ -41,7 +49,8 @@
- logo do banco + logo do banco
{{ $codigo_banco_com_dv }}
@@ -134,7 +143,9 @@ caixa.gov.br -
Autenticação Mecânica - Recibo do Pagador
+
+
Autenticação Mecânica - Recibo do Pagador
+
diff --git a/src/Boleto/Render/view/carne.blade.php b/src/Boleto/Render/view/carne.blade.php index 55b55d8a..789d1708 100644 --- a/src/Boleto/Render/view/carne.blade.php +++ b/src/Boleto/Render/view/carne.blade.php @@ -4,9 +4,19 @@ .table-boleto .conteudo { height: 11px; } - .barcode{height:45px!important;} - .logocontainer{width:253px!important} - .logobanco img{max-height: 30px!important;height: 30px!important;} + + .barcode { + height: 45px !important; + } + + .logocontainer { + width: 253px !important + } + + .logobanco img { + max-height: 30px !important; + height: 30px !important; + } @foreach($boletos as $i => $boleto) @php extract($boleto, EXTR_OVERWRITE); @endphp @@ -14,8 +24,10 @@
@if (isset($logo))
- logo -
{{ $codigo_banco_com_dv }}
+ logo +
{{ $codigo_banco_com_dv }}
@endif @@ -117,7 +129,7 @@ @include('BoletoHtmlRender::partials/ficha-compensacao')
-
Corte na linha pontilhada
+
Corte na linha pontilhada
@if(count($boletos) > 3 && $i > 0 && ($i+1) % 3 === 0) diff --git a/src/Boleto/Render/view/layout.blade.php b/src/Boleto/Render/view/layout.blade.php index 44fb0dad..d726418c 100644 --- a/src/Boleto/Render/view/layout.blade.php +++ b/src/Boleto/Render/view/layout.blade.php @@ -15,7 +15,9 @@ @if(isset($imprimir_carregamento) && $imprimir_carregamento === true) @endif diff --git a/src/Boleto/Render/view/partials/ficha-compensacao.blade.php b/src/Boleto/Render/view/partials/ficha-compensacao.blade.php index 74d50051..8042a5a6 100644 --- a/src/Boleto/Render/view/partials/ficha-compensacao.blade.php +++ b/src/Boleto/Render/view/partials/ficha-compensacao.blade.php @@ -4,7 +4,8 @@
- logo do banco + logo do banco
{{ $codigo_banco_com_dv }}
@@ -25,7 +26,9 @@
Beneficiário
{{ $beneficiario['nome_documento'] }}
- @if($mostrar_endereco_ficha_compensacao)
{{ $beneficiario['endereco_completo'] }}
@endif + @if($mostrar_endereco_ficha_compensacao) +
{{ $beneficiario['endereco_completo'] }}
+ @endif
Agência/Código beneficiário
@@ -64,9 +67,9 @@
Uso do banco
{{ $uso_banco }}
- @endif - @if (isset($mostra_cip) && $mostra_cip) - + @endif + @if (isset($mostra_cip) && $mostra_cip) +
CIP
{{ $cip }}
@@ -95,13 +98,15 @@ - -
Instruções de responsabilidade do beneficiário. Qualquer dúvida sobre este boleto, contate o beneficiário
+ +
Instruções de responsabilidade do beneficiário. Qualquer dúvida sobre este boleto, + contate o beneficiário +
- @if(isset($pix_qrcode)) + @if(isset($pix_qrcode) && $localizacao_pix == \VinicciusGuedes\LaravelCnab\Boleto\Render\Html::PIX_INSTRUCAO) -

Pague via PIX

- +

Pague com PIX

+ QR Code PIX @endif @@ -110,7 +115,7 @@ - +
{{ $instrucoes[0] }}
{{ $instrucoes[1] }}
@@ -120,7 +125,7 @@ - +
{{ $instrucoes[2] }}
{{ $instrucoes[3] }}
@@ -130,7 +135,7 @@ - +
{{ $instrucoes[4] }}
{{ $instrucoes[5] }}
@@ -140,7 +145,7 @@ - +
{{ $instrucoes[6] }}
{{ $instrucoes[7] }}
@@ -164,7 +169,7 @@ -
Sacador/Avalista +
Beneficiário Final
{{ $sacador_avalista ? $sacador_avalista['nome_documento'] : '' }}
@@ -176,8 +181,23 @@ {!! $codigo_barras !!} + @if(isset($pix_qrcode) && $localizacao_pix == \VinicciusGuedes\LaravelCnab\Boleto\Render\Html::PIX_COD_BARRAS) + + + + + + + + + + + + + +
Pague com PIX
QR Code PIX
Vencimento:
{{ $data_vencimento->format('d/m/Y') }}
Valor:
{{ $valor }}
+ @endif - \ No newline at end of file diff --git a/src/CalculoDV.php b/src/CalculoDV.php index 58641387..051c920d 100644 --- a/src/CalculoDV.php +++ b/src/CalculoDV.php @@ -1,11 +1,11 @@ 1) { return 11-$dv; } + return 0; } @@ -52,7 +54,8 @@ public static function bnbNossoNumero($nossoNumero) return Util::modulo11(Util::numberFormatGeral($nossoNumero, 7)); } - private static function bnbAgenciaReal($agencia) { + private static function bnbAgenciaReal($agencia) + { $agenciaAntiga = [ '1' => '99', '2' => '44', '3' => '74', '4' => '73', '5' => '81', '6' => '1', '7' => '2', '8' => '53', '9' => '46', '10' => '20', '11' => '82', '12' => '47', @@ -75,6 +78,7 @@ private static function bnbAgenciaReal($agencia) { '112' => '36', '113' => '37', '114' => '114', '115' => '100', '116' => '116', '117' => '56', '118' => '65', '119' => '109', ]; + return array_key_exists($agencia, $agenciaAntiga) ? $agenciaAntiga[$agencia] : $agencia; } @@ -83,18 +87,19 @@ private static function bnbAgenciaReal($agencia) { | 033 - Santander |-------------------------------------------------------------------------- */ - public static function santanderContaCorrente($agencia, $contaCorrente) + public static function santanderContaCorrente($agencia, $conta) { $n = Util::numberFormatGeral($agencia, 4) . '00' - . Util::numberFormatGeral($contaCorrente, 8); + . Util::numberFormatGeral($conta, 8); $chars = array_reverse(str_split($n, 1)); $sums = array_reverse(str_split('97310097131973', 1)); $sum = 0; foreach ($chars as $i => $char) { - $sum += substr($char*$sums[$i], -1); + $sum += (int) substr($char * $sums[$i], -1); } $unidade = substr($sum, -1); + return $unidade == 0 ? $unidade : 10 - $unidade; } @@ -128,9 +133,9 @@ public static function banrisulAgencia($agencia) return $dv1.$dv2; } - public static function banrisulContaCorrente($contaCorrente) + public static function banrisulContaCorrente($conta) { - $chars = array_reverse(str_split($contaCorrente, 1)); + $chars = array_reverse(str_split($conta, 1)); $sums = str_split('234567423', 1); $sum = 0; @@ -186,10 +191,11 @@ public static function cefAgencia($agencia) return Util::modulo11(Util::numberFormatGeral($agencia, 5)); } - public static function cefContaCorrente($agencia, $contaCorrente) + public static function cefContaCorrente($agencia, $conta) { $n = Util::numberFormatGeral($agencia, 5) - . Util::numberFormatGeral($contaCorrente, 11); + . Util::numberFormatGeral($conta, 11); + return Util::modulo11($n); } @@ -198,6 +204,21 @@ public static function cefNossoNumero($nossoNumero) return Util::modulo11($nossoNumero); } + /* + |-------------------------------------------------------------------------- + | 133 - Cresol + |-------------------------------------------------------------------------- + */ + public static function cresolContaCorrente($conta) + { + return Util::modulo11($conta, 2, 9, 0, 'P'); + } + + public static function cresolNossoNumero($carteira, $nossoNumero) + { + return Util::modulo11($carteira . Util::numberFormatGeral($nossoNumero, 11), 2, 7, 0, 'P'); + } + /* |-------------------------------------------------------------------------- | 136 - Unicred @@ -206,12 +227,13 @@ public static function cefNossoNumero($nossoNumero) public static function unicredAgencia($agencia) { $dv = Util::modulo11($agencia); + return $dv == 11 ? 0 : $dv; } - public static function unicredContaCorrente($contaCorrente) + public static function unicredContaCorrente($conta) { - return Util::modulo11($contaCorrente); + return Util::modulo11($conta); } public static function unicredNossoNumero($nossoNumero) @@ -219,6 +241,32 @@ public static function unicredNossoNumero($nossoNumero) return Util::modulo11( Util::numberFormatGeral($nossoNumero, 10) ); } + /* + |-------------------------------------------------------------------------- + | 208 - BTG + |-------------------------------------------------------------------------- + */ + + public static function btgNossoNumero($carteira, $numero_boleto) + { + if (strlen($numero_boleto) < 11) { + $numero_boleto = Util::numberFormatGeral($numero_boleto, 11); + } + $n = '0' . Util::numberFormatGeral($carteira, 2) . $numero_boleto; + + return Util::modulo11($n, 2, 7, 0, 'P'); + } + + public static function btgAgencia($agencia) + { + return Util::modulo11($agencia); + } + + public static function btgContaCorrente($conta) + { + return Util::modulo11($conta); + } + /* |-------------------------------------------------------------------------- | 237 - Bradesco @@ -227,12 +275,13 @@ public static function unicredNossoNumero($nossoNumero) public static function bradescoAgencia($agencia) { $dv = Util::modulo11($agencia, 2, 9, 0, 'P'); + return $dv == 11 ? 0 : $dv; } - public static function bradescoContaCorrente($contaCorrente) + public static function bradescoContaCorrente($conta) { - return Util::modulo11($contaCorrente, 2, 9, 0, 'P'); + return Util::modulo11($conta, 2, 9, 0, 'P'); } public static function bradescoNossoNumero($carteira, $nossoNumero) @@ -275,6 +324,7 @@ public static function fibraNossoNumero($agencia, $nossaCarteira, $numero_boleto } $factor++; } + return 10 - $sum%10; } @@ -286,10 +336,23 @@ public static function fibraNossoNumero($agencia, $nossaCarteira, $numero_boleto public static function delcredNossoNumero($carteira, $nossoNumero) { - $agencia = "0019"; + $agencia = '0019'; $numeroFormatado = Util::numberFormatGeral($nossoNumero, 10); - $digitoVerificador = Util::modulo10($agencia.$carteira.$numeroFormatado); - return $digitoVerificador; + + return Util::modulo10($agencia . $carteira . $numeroFormatado); + } + + /* + |-------------------------------------------------------------------------- + | 336 - C6 + |-------------------------------------------------------------------------- + */ + + public static function c6NossoNumero($carteira, $numero_boleto) + { + $n = '0' . Util::numberFormatGeral($carteira, 2) . Util::numberFormatGeral($numero_boleto, 10); + + return Util::modulo11($n, 2, 7, 0, 'P'); } /* @@ -297,10 +360,11 @@ public static function delcredNossoNumero($carteira, $nossoNumero) | 341 - Itau |-------------------------------------------------------------------------- */ - public static function itauContaCorrente($agencia, $contaCorrente) + public static function itauContaCorrente($agencia, $conta) { $n = Util::numberFormatGeral($agencia, 4) - . Util::numberFormatGeral($contaCorrente, 5); + . Util::numberFormatGeral($conta, 5); + return Util::modulo10($n); } @@ -310,9 +374,51 @@ public static function itauNossoNumero($agencia, $conta, $carteira, $numero_bole . Util::numberFormatGeral($conta, 5) . Util::numberFormatGeral($carteira, 3) . Util::numberFormatGeral($numero_boleto, 8); + return Util::modulo10($n); } + /* + |-------------------------------------------------------------------------- + | 633 - Rendimento + |-------------------------------------------------------------------------- + */ + public static function rendimentoAgencia($agencia) + { + return Util::modulo11($agencia); + } + + public static function rendimentoConta($conta) + { + return Util::modulo11($conta); + } + + public static function rendimentoNossoNumero($agencia, $nossaCarteira, $numero_boleto) + { + $n = Util::numberFormatGeral($agencia, 4) + . Util::numberFormatGeral($nossaCarteira, 3) + . Util::numberFormatGeral($numero_boleto, 10); + + $n = strrev($n); + $factor = 2; + $sum = 0; + + for ($i = mb_strlen($n); $i > 0; $i--) { + $x = ((int) mb_substr($n, $i - 1, 1)); + $parcial = $x * $factor; + if ($parcial > 9) { + $parcial = (int) mb_substr($parcial, 0, 1) + (int) mb_substr($parcial, 1, 1); + } + $sum += $parcial; + if ($factor == 2) { + $factor = 0; + } + $factor++; + } + + return 10 - $sum % 10; + } + /* |-------------------------------------------------------------------------- | 643 - Pine @@ -348,6 +454,7 @@ public static function pineNossoNumero($agencia, $nossaCarteira, $numero_boleto) } $factor++; } + return 10 - $sum%10; } @@ -364,9 +471,31 @@ public static function sicrediNossoNumero($agencia, $posto, $codigoCliente, $ano . Util::numberFormatGeral($ano, 2) . Util::numberFormatGeral($byte, 1) . Util::numberFormatGeral($numero_boleto, 5); + return Util::modulo11($n); } + /* + |-------------------------------------------------------------------------- + | 712 - Ourinvest + |-------------------------------------------------------------------------- + */ + + public static function ourinvestNossoNumero($carteira, $nossoNumero) + { + return Util::modulo11(Util::numberFormatGeral($carteira, 2) . Util::numberFormatGeral($nossoNumero, 11), 2, 7, 0, 'P'); + } + + public static function ourinvestAgencia($agencia) + { + return null; + } + + public static function ourinvestConta($conta, $agencia = '0001') + { + return Util::modulo10(Util::numberFormatGeral($agencia, 4) . Util::numberFormatGeral($conta, 7)); + } + /* |-------------------------------------------------------------------------- | 756 - Bancoob - Falta o calculo conta e confirmar agencia @@ -377,9 +506,9 @@ public static function bancoobAgencia($agencia) return Util::modulo11($agencia); } - public static function bancoobContaCorrente($contaCorrente) + public static function bancoobContaCorrente($conta) { - return Util::modulo11($contaCorrente); + return Util::modulo11($conta); } public static function bancoobNossoNumero($agencia, $convenio, $numero_boleto) @@ -400,6 +529,7 @@ public static function bancoobNossoNumero($agencia, $convenio, $numero_boleto) if (($resto != 0) && ($resto != 1)) { $dv = 11 - $resto; } + return $dv; } } diff --git a/src/Cnab/Remessa/AbstractRemessa.php b/src/Cnab/Remessa/AbstractRemessa.php index 9887dc21..09866eea 100644 --- a/src/Cnab/Remessa/AbstractRemessa.php +++ b/src/Cnab/Remessa/AbstractRemessa.php @@ -3,14 +3,15 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Remessa; use Carbon\Carbon; +use Illuminate\Support\Str; use VinicciusGuedes\LaravelCnab\Util; +use Illuminate\Support\Collection; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Pessoa as PessoaContract; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use Illuminate\Support\Str; abstract class AbstractRemessa { - const HEADER = 'header'; const HEADER_LOTE = 'header_lote'; const DETALHE = 'detalhe'; @@ -20,7 +21,7 @@ abstract class AbstractRemessa protected $tamanho_linha = false; /** - * Campos que são necessários para a remessa + * Campos necessários para a remessa * * @var array */ @@ -62,21 +63,21 @@ abstract class AbstractRemessa ]; /** - * Variavel com ponteiro para linha que esta sendo editada. + * Variável com ponteiro para linha que esta sendo editada. * * @var */ protected $atual; /** - * Caracter de fim de linha + * Caractere de fim de linha * * @var string */ protected $fimLinha = "\n"; /** - * Caracter de fim de arquivo + * Caractere de fim de arquivo * * @var null */ @@ -88,12 +89,14 @@ abstract class AbstractRemessa * @var */ protected $idremessa; + /** * A data que será informada no header da remessa * * @var Carbon; */ protected $dataRemessa = null; + /** * A hora que será informada no header da remessa * @@ -106,30 +109,35 @@ abstract class AbstractRemessa * @var int */ protected $agencia; + /** * Dígito da conta * * @var int */ protected $agenciaDv; + /** * Conta * * @var int */ protected $conta; + /** * Dígito da conta * * @var int */ protected $contaDv; + /** * Carteira de cobrança. * * @var */ protected $carteira; + /** * Define as carteiras disponíveis para cada banco * @@ -138,7 +146,7 @@ abstract class AbstractRemessa protected $carteiras = []; /** - * Entidade beneficiario (quem esta gerando a remessa) + * Entidade beneficiária (quem está gerando a remessa) * * @var PessoaContract */ @@ -191,6 +199,7 @@ public function getDataRemessa($format) if (is_null($this->dataRemessa)) { return Carbon::now()->format($format); } + return $this->dataRemessa->format($format); } @@ -293,7 +302,7 @@ public function getBeneficiario() * @param $beneficiario * * @return AbstractRemessa - * @throws \Exception + * @throws ValidationException */ public function setBeneficiario($beneficiario) { @@ -425,12 +434,12 @@ public function getContaDv() * @param string $carteira * * @return AbstractRemessa - * @throws \Exception + * @throws ValidationException */ public function setCarteira($carteira) { if ($this->getCarteiras() !== false && !in_array($carteira, $this->getCarteiras())) { - throw new \Exception("Carteira não disponível!"); + throw new ValidationException('Carteira não disponível!'); } $this->carteira = $carteira; @@ -468,11 +477,11 @@ public function getCarteiras() } /** - * Método que valida se o banco tem todos os campos obrigadotorios preenchidos + * Método que valida se o banco tem todos os campos obrigatórios preenchidos * * @param $messages * - * @return boolean + * @return bool */ public function isValid(&$messages) { @@ -480,6 +489,7 @@ public function isValid(&$messages) $test = call_user_func([$this, 'get' . Str::camel($campo)]); if ($test === '' || is_null($test)) { $messages .= "Campo $campo está em branco"; + return false; } } @@ -497,11 +507,11 @@ abstract protected function header(); /** * Função para adicionar detalhe ao arquivo. * - * @param BoletoContract $detalhe + * @param BoletoContract $boleto * * @return mixed */ - abstract public function addBoleto(BoletoContract $detalhe); + abstract public function addBoleto(BoletoContract $boleto); /** * Função que gera o trailer (footer) do arquivo. @@ -511,7 +521,7 @@ abstract public function addBoleto(BoletoContract $detalhe); abstract protected function trailer(); /** - * Função para adicionar multiplos boletos. + * Função para adicionar múltiplos boletos. * * @param array $boletos * @@ -529,12 +539,12 @@ public function addBoletos(array $boletos) /** * Função para add valor a linha nas posições informadas. * - * @param integer $i - * @param integer $f + * @param int $i + * @param int $f * @param $value * * @return array - * @throws \Exception + * @throws ValidationException */ protected function add($i, $f, $value) { @@ -554,7 +564,7 @@ protected function getHeader() /** * Retorna os detalhes do arquivo * - * @return \Illuminate\Support\Collection + * @return Collection */ protected function getDetalhes() { @@ -578,17 +588,17 @@ protected function getTrailer() * @param int $extendido * * @return string - * @throws \Exception + * @throws ValidationException */ protected function valida(array $a, $extendido = 0) { if ($this->tamanho_linha === false) { - throw new \Exception('Classe remessa deve informar o tamanho da linha'); + throw new ValidationException('Classe remessa deve informar o tamanho da linha'); } $a = array_filter($a, 'mb_strlen'); if (count($a) != $this->tamanho_linha + $extendido) { - throw new \Exception(sprintf('$a não possui %s posições, possui: %s', $this->tamanho_linha, count($a))); + throw new ValidationException(sprintf('$a não possui %s posições, possui: %s', $this->tamanho_linha, count($a))); } return implode('', $a); @@ -598,7 +608,7 @@ protected function valida(array $a, $extendido = 0) * Gera o arquivo, retorna a string. * * @return string - * @throws \Exception + * @throws ValidationException */ abstract public function gerar(); @@ -609,7 +619,7 @@ abstract public function gerar(); * @param bool $suggestName * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function save($path, $suggestName = false) { @@ -619,7 +629,7 @@ public function save($path, $suggestName = false) } if (!is_writable(dirname($path))) { - throw new \Exception('Path ' . $folder . ' não possui permissao de escrita'); + throw new ValidationException('Path ' . $folder . ' não possui permissao de escrita'); } if ($suggestName) { @@ -641,11 +651,11 @@ public function nomeSugerido() } /** - * Realiza o download da string retornada do metodo gerar + * Realiza o download da string retornada do método gerar * * @param null $filename * - * @throws \Exception + * @throws ValidationException */ public function download($filename = null) { diff --git a/src/Cnab/Remessa/Cnab240/AbstractRemessa.php b/src/Cnab/Remessa/Cnab240/AbstractRemessa.php index 15849326..adb60dfd 100644 --- a/src/Cnab/Remessa/Cnab240/AbstractRemessa.php +++ b/src/Cnab/Remessa/Cnab240/AbstractRemessa.php @@ -1,22 +1,24 @@ isValid($messages)) { - throw new \Exception('Campos requeridos pelo banco, aparentam estar ausentes ' . $messages); + throw new ValidationException('Campos requeridos pelo banco, aparentam estar ausentes ' . $messages); } $stringRemessa = ''; if ($this->iRegistros < 1) { - throw new \Exception('Nenhuma linha detalhe foi adicionada'); + throw new ValidationException('Nenhuma linha detalhe foi adicionada'); } $this->header(); diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Ailos.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Ailos.php new file mode 100644 index 00000000..99ce1e33 --- /dev/null +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Ailos.php @@ -0,0 +1,492 @@ +setCarteira('1'); //Carteira única + $this->addCampoObrigatorio('convenio', 'agencia', 'agenciaDV'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_AILOS; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = ['1']; + + /** + * Convenio com o banco + * + * @var string + */ + protected $convenio; + + /** + * Nome da cooperativa + * + * @var string + */ + protected $cooperativa; + + /** + * Agência + * + * @var int + */ + protected $agenciaDv; + + /** + * Define o código da carteira (Com ou sem registro) + * + * @param string $carteira + * + * @return Ailos + */ + public function setCarteira($carteira) + { + $this->carteira = 1; + return $this; + } + + /** + * @return mixed + */ + public function getConvenio() + { + return $this->convenio; + } + + /** + * @param mixed $convenio + * + * @return Ailos + */ + public function setConvenio($convenio) + { + $this->convenio = ltrim($convenio, 0); + + return $this; + } + + /** + * Retorna a agência dígito verificador + * + * @return int + */ + public function getAgenciaDv() + { + return $this->agenciaDv; + } + + /** + * Define a agência dígito verificador + * + * @param int $agenciaDv + * + * @return Ailos + */ + public function setAgenciaDv($agenciaDv) + { + $this->agenciaDv = (string) $agenciaDv; + + return $this; + } + + /** + * Retorna nome cooperativa + * + * @return int + */ + public function getCooperativa() + { + return $this->cooperativa; + } + + /** + * Define nome cooperativa + * + * @param int $cooperativa + * + * @return Ailos + */ + public function setCooperativa($cooperativa) + { + $this->cooperativa = strtoupper($cooperativa); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->segmentoP($boleto); + $this->segmentoQ($boleto); + $this->segmentoR($boleto); + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + protected function segmentoP(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'P'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(23, 23, $this->getAgenciaDv()); + $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(36, 36, $this->getContaDv()); + $this->add(37, 37, ''); + $this->add(38, 57, Util::formatCnab('X', $boleto->getNossoNumero(), 20)); + $this->add(58, 58, '1'); //'1' = Cobrança Simples + $this->add(59, 59, '1'); //'1' = Com cadastramento (cobrança registrada) + $this->add(60, 60, '1'); //'1' = Tradicional + $this->add(61, 61, '2'); //'2' = Beneficiário/Cooperado emite + $this->add(62, 62, '2'); //'2' = Beneficiário/Cooperado distribui + $this->add(63, 77, Util::formatCnab('9', $boleto->getNumeroDocumento(), 15)); + $this->add(78, 85, $boleto->getDataVencimento()->format('dmY')); + $this->add(86, 100, Util::formatCnab('9', $boleto->getValor(), 15, 2)); + $this->add(101, 105, '00000'); + $this->add(106, 106, ''); + $this->add(107, 108, Util::formatCnab('9', $boleto->getEspecieDocCodigo(), 2)); + $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); + $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); + $this->add(118, 118, $boleto->getJuros() ? '2' : '3'); //'1' = Valor por Dia, 2 = Taxa mensal '3' = Isento + $this->add(119, 126, $boleto->getJurosApos() == 0 ? '00000000' : + $boleto->getDataVencimentoApos()->copy()->addDays((int) $boleto->getJurosApos())->format('dmY')); + $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 2)); //Valor da mora/dia ou Taxa mensal + $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); + $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); + $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); + $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); + $this->add(181, 195, Util::formatCnab('9', 0, 15, 2)); + $this->add(196, 220, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); + $this->add(221, 221, self::PROTESTO_SEM); + if ($boleto->getDiasProtesto() > 0) { + $this->add(221, 221, self::PROTESTO_DIAS_CORRIDOS); + } + $this->add(222, 223, Util::formatCnab('9', $boleto->getDiasProtesto(), 2)); + $this->add(224, 224, '2'); // Deverá ser informado o código ‘2’, visto que o sistema respeita o decurso de prazo cadastrado no convênio do cooperado.. + $this->add(225, 227, ''); // Utilizar sempre, nesse campo, 60 dias para baixa/devolução. + $this->add(228, 229, Util::formatCnab('9', $boleto->getMoeda(), 2)); + $this->add(230, 239, '0000000000'); + $this->add(240, 240, ''); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + protected function segmentoR(BoletoContract $boleto) + { + if (!$boleto->getMulta() > 0 && !$boleto->getDesconto() > 0) { + return $this; + } + + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'R'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + + $this->add(18, 18, '0'); + $this->add(19, 26, '00000000'); + $this->add(27, 41, Util::formatCnab('9', 0, 15, 2)); + if ($boleto->getDesconto() > 0) { + $this->add(18, 18, '1'); // '1' = Valor fixo até a data informada + $this->add(19, 26, $boleto->getDataDesconto() ? $boleto->getDataDesconto()->format('dmY') : $boleto->getDataVencimento()->format('dmY')); + $this->add(27, 41, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); + } + + $this->add(42, 42, '0'); + $this->add(43, 50, Util::formatCnab('9', 0, 8)); + $this->add(51, 65, Util::formatCnab('9', 0, 15)); + $this->add(66, 66, '0'); + $this->add(67, 74, '00000000'); + $this->add(75, 89, Util::formatCnab('9', 0, 15, 2)); + if ($boleto->getMulta() > 0.01) { + $this->add(66, 66, '2'); // '2' = Percentual + $this->add(67, 74, $boleto->getDataVencimento()->format('dmY')); + $this->add(75, 89, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); + } + $this->add(90, 99, Util::formatCnab('X', '', 10)); + $this->add(100, 139, Util::formatCnab('X', '', 40)); + $this->add(140, 179, Util::formatCnab('X', '', 40)); + $this->add(180, 199, Util::formatCnab('X', '', 20)); + $this->add(200, 207, Util::formatCnab('9', 0, 8)); + $this->add(208, 210, Util::formatCnab('9', Util::onlyNumbers($this->getCodigoBanco()), 3)); + $this->add(211, 215, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(216, 216, $this->getAgenciaDv()); + $this->add(217, 228, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(229, 229, $this->getContaDv()); + $this->add(230, 230, ''); + $this->add(231, 231, ''); + $this->add(232, 240, Util::formatCnab('X', '', 9)); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + public function segmentoQ(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'Q'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(18, 18, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 15)); + $this->add(34, 73, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getNome())), 40)); + $this->add(74, 113, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getEndereco())), 40)); + $this->add(114, 128, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getBairro())), 15)); + $this->add(129, 133, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 5)); + $this->add(134, 136, Util::formatCnab('9', Util::onlyNumbers(substr($boleto->getPagador()->getCep(), 6, 9)), 3)); + $this->add(137, 151, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getCidade())), 15)); + $this->add(152, 153, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(154, 154, '0'); + $this->add(155, 169, '000000000000000'); + $this->add(170, 209, ''); + $this->add(210, 212, '000'); + $this->add(213, 232, ''); + $this->add(233, 240, ''); + + if ($boleto->getSacadorAvalista()) { + $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); + $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); + $this->add(170, 209, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getSacadorAvalista()->getNome())), 30)); + } + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + /** + * HEADER DE ARQUIVO + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0000'); + $this->add(8, 8, '0'); + $this->add(9, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); + $this->add(33, 52, Util::formatCnab('X', Util::formatCnab('9', Util::onlyNumbers($this->getConvenio()), 6), 20)); + $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(58, 58, $this->getAgenciaDv()); + $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(71, 71, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(72, 72, ''); + $this->add(73, 102, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($this->getBeneficiario()->getNome())), 30)); + $this->add(103, 132, Util::formatCnab('X', $this->getCooperativa() ?? 'AILOS', 30)); + $this->add(133, 142, ''); + $this->add(143, 143, 1); + $this->add(144, 151, $this->getDataRemessa('dmY')); + $this->add(152, 157, date('His')); + $this->add(158, 163, Util::formatCnab('9', $this->getIdremessa(), 6)); + $this->add(164, 166, '087'); + $this->add(167, 171, '01600'); + $this->add(172, 191, ''); + $this->add(192, 211, ''); + $this->add(212, 240, ''); + + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function headerLote() + { + $this->iniciaHeaderLote(); + + /** + * HEADER DE LOTE + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '1'); + $this->add(9, 9, 'R'); + $this->add(10, 11, '01'); + $this->add(12, 13, ''); + $this->add(14, 16, '045'); + $this->add(17, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); + $this->add(34, 53, Util::formatCnab('X', Util::formatCnab('9', Util::onlyNumbers($this->getConvenio()), 6), 20)); + $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(59, 59, $this->getAgenciaDv()); + $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(72, 72, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(73, 73, ''); + $this->add(74, 103, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($this->getBeneficiario()->getNome())), 30)); + $this->add(104, 183, Util::formatCnab('X', $this->getCooperativa(), 30)); + $this->add(184, 191, Util::formatCnab('9', $this->getIdremessa(), 8)); + $this->add(192, 199, date('dmY')); + $this->add(200, 207, '00000000'); + $this->add(208, 240, ''); + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function trailerLote() + { + $this->iniciaTrailerLote(); + + $valor = array_reduce($this->boletos, function ($valor, $boleto) { + return $valor + $boleto->getValor(); + }, 0); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '5'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', $this->getCountDetalhes() + 2, 6)); + $this->add(24, 29, Util::formatCnab('9', 0, 6)); + $this->add(30, 46, Util::formatCnab('9', 0, 17, 2)); + $this->add(47, 52, Util::formatCnab('9', 0, 6)); + $this->add(53, 69, Util::formatCnab('9', 0, 17, 2)); + $this->add(70, 75, Util::formatCnab('9', 0, 6)); + $this->add(76, 92, Util::formatCnab('9', 0, 17, 2)); + $this->add(93, 98, Util::formatCnab('9', 0, 6)); + $this->add(99, 115, Util::formatCnab('9', 0, 17, 2)); + $this->add(116, 123, '00000000'); + $this->add(124, 240, ''); + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '9999'); + $this->add(8, 8, '9'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', 1, 6)); + $this->add(24, 29, Util::formatCnab('9', $this->getCount(), 6)); + $this->add(30, 35, '000000'); + $this->add(36, 240, ''); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bancoob.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bancoob.php index 9f6077c4..cd8621e5 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bancoob.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bancoob.php @@ -9,11 +9,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab240\Cobranca\Banco; +use VinicciusGuedes\LaravelCnab\Util; use VinicciusGuedes\LaravelCnab\CalculoDV; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab240\AbstractRemessa; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Remessa as RemessaContract; -use VinicciusGuedes\LaravelCnab\Util; class Bancoob extends AbstractRemessa implements RemessaContract { @@ -34,7 +35,6 @@ class Bancoob extends AbstractRemessa implements RemessaContract const OCORRENCIA_EXC_NEGATIVACAO = '68'; const OCORRENCIA_CANC_NEGATIVACAO = '69'; const OCORRENCIA_DESCONTAR_TITULOS_DIA = '93'; - const PROTESTO_DIAS_CORRIDOS = '1'; const PROTESTO_DIAS_UTEIS = '2'; const PROTESTO_NAO_PROTESTAR = '3'; @@ -54,7 +54,6 @@ public function __construct(array $params = []) */ protected $codigoBanco = BoletoContract::COD_BANCO_BANCOOB; - /** * Define as carteiras disponíveis para cada banco * @@ -74,13 +73,12 @@ public function __construct(array $params = []) * * @var null */ - protected $fimArquivo = ""; + protected $fimArquivo = ''; /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob */ public function addBoleto(BoletoContract $boleto) { @@ -88,14 +86,15 @@ public function addBoleto(BoletoContract $boleto) $this->segmentoP($boleto); $this->segmentoQ($boleto); $this->segmentoR($boleto); + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -120,9 +119,9 @@ protected function segmentoP(BoletoContract $boleto) $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); } $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(23, 23, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(23, 23, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(36, 36, Util::formatCnab('X', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(36, 36, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(37, 37, ''); $this->add(38, 47, Util::formatCnab('9', $boleto->getNossoNumero(), 10)); $this->add(48, 49, '01'); //Parcela Única @@ -145,7 +144,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(118, 118, ($boleto->getJuros() !== null && $boleto->getJuros() > 0) ? '2' : '0'); //0 = ISENTO | 1 = R$ ao dia | 2 = % ao mês $this->add(119, 126, ($boleto->getJuros() !== null && $boleto->getJuros() > 0) ? $boleto->getDataVencimento()->copy()->addDays($boleto->getJurosApos() ?: 1)->format('dmY') : '00000000'); $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 2)); //Taxa mensal - $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL + $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); @@ -168,8 +167,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -202,7 +201,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, Util::formatCnab('X', '', 28)); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 40)); @@ -214,8 +213,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { @@ -240,7 +239,7 @@ public function segmentoR(BoletoContract $boleto) $this->add(43, 50, '00000000'); $this->add(51, 65, '000000000000000'); $this->add(66, 66, $boleto->getMulta() > 0 ? '2' : '0'); //0 = ISENTO | 1 = VALOR FIXO | 2 = PERCENTUAL - $this->add(67, 74, $boleto->getMulta() > 0 ? $boleto->getDataVencimento()->copy()->addDay()->format('dmY') : '00000000'); + $this->add(67, 74, $boleto->getMulta() > 0 ? $boleto->getDataVencimento()->copy()->addDay()->format('dmY') : '00000000'); $this->add(75, 89, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); //2,20 = 0000000000220 $this->add(90, 199, ''); $this->add(200, 207, '00000000'); @@ -256,8 +255,8 @@ public function segmentoR(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function header() { @@ -274,9 +273,9 @@ protected function header() $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); $this->add(33, 52, ''); $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(58, 58, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(58, 58, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(71, 71, Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(71, 71, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(72, 72, '0'); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'SICOOB', 30)); @@ -290,12 +289,13 @@ protected function header() $this->add(172, 191, ''); $this->add(192, 211, ''); $this->add(212, 240, ''); + return $this; } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function headerLote() { @@ -316,9 +316,9 @@ protected function headerLote() $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); $this->add(34, 53, ''); $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(59, 59, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(59, 59, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(72, 72, Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(73, 73, ''); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); @@ -331,14 +331,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -358,8 +358,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Banrisul.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Banrisul.php index 8b5217b6..b4642890 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Banrisul.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Banrisul.php @@ -1,22 +1,16 @@ Cobrança Simples @@ -69,7 +61,7 @@ public function __construct(array $params = []) * U -> CSB e CCB sem registro * @var array */ - protected $carteiras = ['1','2', '3', 'B', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'N', 'P', 'R', 'S', 'T', 'U']; + protected $carteiras = ['1', '2', '3', 'B', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'N', 'P', 'R', 'S', 'T', 'U']; /** * Codigo do cliente junto ao banco. @@ -105,25 +97,26 @@ public function setCodigoCliente($codigoCliente) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { $this->boletos[] = $boleto; $this->segmentoP($boleto); $this->segmentoQ($boleto); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->segmentoY01($boleto); } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -150,7 +143,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); $this->add(23, 23, ''); $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(36, 36, CalculoDV::banrisulContaCorrente($this->getConta())); + $this->add(36, 36, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::banrisulContaCorrente($this->getConta())); $this->add(37, 37, ''); $this->add(38, 57, Util::formatCnab('9', $boleto->getNossoNumero(), 20)); $this->add(58, 58, $this->getCarteira()); @@ -192,8 +185,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -226,7 +219,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -238,8 +231,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ public function segmentoY01(BoletoContract $boleto) { @@ -272,8 +265,8 @@ public function segmentoY01(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function header() { @@ -293,7 +286,7 @@ protected function header() $this->add(58, 58, ''); $this->add(59, 63, '000EE'); $this->add(64, 70, Util::formatCnab('9', $this->getConta(), 7)); - $this->add(71, 71, CalculoDV::banrisulContaCorrente($this->getConta())); + $this->add(71, 71, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::banrisulContaCorrente($this->getConta())); $this->add(72, 72, ''); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'BANRISUL', 30)); @@ -318,8 +311,8 @@ protected function header() } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function headerLote() { @@ -342,7 +335,7 @@ protected function headerLote() $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); $this->add(59, 59, ''); $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(72, 72, CalculoDV::banrisulContaCorrente($this->getConta())); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::banrisulContaCorrente($this->getConta())); $this->add(73, 73, ''); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); @@ -355,14 +348,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -386,8 +379,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bb.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bb.php index 952c237a..da65942e 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bb.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bb.php @@ -1,22 +1,16 @@ boletos[] = $boleto; $this->segmentoP($boleto); $this->segmentoQ($boleto); - if($boleto->getStatus() == $boleto::STATUS_REGISTRO) { - $this->segmentoR($boleto); - } + if ($boleto->getStatus() == $boleto::STATUS_REGISTRO) { + $this->segmentoR($boleto); + } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -187,9 +181,9 @@ protected function segmentoP(BoletoContract $boleto) $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); } $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(23, 23, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(23, 23, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(36, 36, CalculoDV::bbContaCorrente($this->getConta())); + $this->add(36, 36, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(37, 37, ''); $this->add(38, 57, Util::formatCnab('X', $this->nossoNumero($boleto), 20)); $this->add(58, 58, '1'); //'1' = Cobrança Simples @@ -201,7 +195,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(78, 85, $boleto->getDataVencimento()->format('dmY')); $this->add(86, 100, Util::formatCnab('9', $boleto->getValor(), 15, 2)); $this->add(101, 105, '00000'); - $this->add(106, 106, '0'); + $this->add(106, 106, ''); $this->add(107, 108, Util::formatCnab('9', $boleto->getEspecieDocCodigo(), 2)); $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); @@ -231,8 +225,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -271,7 +265,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -283,8 +277,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { @@ -331,8 +325,8 @@ public function segmentoR(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function header() { @@ -353,9 +347,9 @@ protected function header() $this->add(48, 50, Util::formatCnab('9', $this->getVariacaoCarteira(), 3)); $this->add(51, 52, ''); $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(58, 58, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(58, 58, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(71, 71, CalculoDV::bbContaCorrente($this->getConta())); + $this->add(71, 71, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(72, 72, ''); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'BANCO DO BRASIL S.A.', 30)); @@ -373,8 +367,8 @@ protected function header() } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function headerLote() { @@ -389,7 +383,7 @@ protected function headerLote() $this->add(9, 9, 'R'); $this->add(10, 11, '01'); $this->add(12, 13, ''); - $this->add(14, 16, '042'); + $this->add(14, 16, '043'); $this->add(17, 17, ''); $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); @@ -399,9 +393,9 @@ protected function headerLote() $this->add(49, 51, Util::formatCnab('9', $this->getVariacaoCarteira(), 3)); $this->add(52, 53, ''); $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(59, 59, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(59, 59, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(72, 72, CalculoDV::bbContaCorrente($this->getConta())); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(73, 73, ''); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); @@ -414,8 +408,8 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function trailerLote() { @@ -432,8 +426,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function trailer() { @@ -456,11 +450,13 @@ protected function trailer() * * @return mixed|string */ - private function nossoNumero(BoletoContract $boleto) { + private function nossoNumero(BoletoContract $boleto) + { $convenio = (int) Util::onlyNumbers($this->getConvenio()); if ($convenio > 1000000) { return $boleto->getNossoNumero(); } + return $boleto->getNossoNumero() . CalculoDV::bbNossoNumero($boleto->getNossoNumero()); } } diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bradesco.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bradesco.php index 9b667725..1695a5a4 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bradesco.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Bradesco.php @@ -1,22 +1,16 @@ codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . Util::formatCnab('9', $this->getAgencia(), 5) . Util::formatCnab('9', $this->getConta(), 7) . - Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bradescoContaCorrente($this->getConta()), 1); + Util::formatCnab('9', ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bradescoContaCorrente($this->getConta()), 1); } return $this->codigoCliente; @@ -128,8 +118,8 @@ public function setCodigoCliente($codigoCliente) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -137,17 +127,18 @@ public function addBoleto(BoletoContract $boleto) $this->segmentoP($boleto); $this->segmentoQ($boleto); $this->segmentoR($boleto); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->segmentoY01($boleto); } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -166,9 +157,9 @@ protected function segmentoP(BoletoContract $boleto) $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); } $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(23, 23, CalculoDV::bradescoAgencia($this->getAgencia())); + $this->add(23, 23, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bradescoAgencia($this->getAgencia())); $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(36, 36, CalculoDV::bradescoContaCorrente($this->getConta())); + $this->add(36, 36, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bradescoContaCorrente($this->getConta())); $this->add(37, 37, ''); $this->add(38, 40, Util::formatCnab('9', $this->getCarteira(), 3)); $this->add(41, 45, '00000'); @@ -189,7 +180,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(118, 118, $boleto->getJuros() ? '2' : '3'); //'2' = Taxa Mensal, '3' = Isento $this->add(119, 126, $boleto->getDataVencimento()->format('dmY')); $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 2)); //Taxa de Juros Mensal - $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL + $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); @@ -212,8 +203,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -252,7 +243,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -261,11 +252,11 @@ public function segmentoQ(BoletoContract $boleto) return $this; } - /** + /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { @@ -308,8 +299,8 @@ public function segmentoR(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function segmentoY01(BoletoContract $boleto) { @@ -342,8 +333,8 @@ public function segmentoY01(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function header() { @@ -360,9 +351,9 @@ protected function header() $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); $this->add(33, 52, Util::formatCnab('9', Util::onlyNumbers($this->getCodigoCliente()), 20)); $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(58, 58, CalculoDV::bradescoAgencia($this->getAgencia())); + $this->add(58, 58, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bradescoAgencia($this->getAgencia())); $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(71, 71, CalculoDV::bradescoContaCorrente($this->getConta())); + $this->add(71, 71, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bradescoContaCorrente($this->getConta())); $this->add(72, 72, ''); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'Bradesco', 30)); @@ -375,12 +366,13 @@ protected function header() $this->add(167, 171, '01600'); $this->add(172, 211, ''); $this->add(212, 240, ''); + return $this; } /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function headerLote() { @@ -401,9 +393,9 @@ protected function headerLote() $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); $this->add(34, 53, Util::formatCnab('9', Util::onlyNumbers($this->getCodigoCliente()), 20)); $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(59, 59, CalculoDV::bradescoAgencia($this->getAgencia())); + $this->add(59, 59, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bradescoAgencia($this->getAgencia())); $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(72, 72, CalculoDV::bradescoContaCorrente($this->getConta())); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bradescoContaCorrente($this->getConta())); $this->add(73, 73, ''); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); @@ -416,14 +408,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -447,8 +439,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Btg.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Btg.php new file mode 100644 index 00000000..5a195219 --- /dev/null +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Btg.php @@ -0,0 +1,408 @@ +addCampoObrigatorio('codigoCliente'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_BTG; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = [1, 2, 3, 4, 5, 6]; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return Btg + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->segmentoP($boleto); + $this->segmentoQ($boleto); + $this->segmentoR($boleto); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + protected function segmentoP(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'P'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(23, 23, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(36, 36, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(37, 37, ''); + $this->add(38, 57, Util::formatCnab('X', $boleto->getNossoNumero(), 20)); + $this->add(58, 58, $this->getCarteira()); + $this->add(59, 59, '1'); //'1' = Com cadastramento (cobrança registrada) + $this->add(60, 60, '1'); //'1' = Tradicional + $this->add(61, 61, '2'); //'2' = Beneficiário emite + $this->add(62, 62, '2'); //'2' = Beneficiário distribui + $this->add(63, 77, Util::formatCnab('9', $boleto->getNumeroDocumento(), 15)); + $this->add(78, 85, $boleto->getDataVencimento()->format('dmY')); + $this->add(86, 100, Util::formatCnab('9', $boleto->getValor(), 15, 2)); + $this->add(101, 105, '00000'); + $this->add(106, 106, ''); + $this->add(107, 108, Util::formatCnab('9', $boleto->getEspecieDocCodigo(), 2)); + $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); + $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); + $this->add(118, 118, $boleto->getJuros() ? '1' : '3'); //'1' = Valor por Dia, '3' = Isento + $this->add(119, 126, $boleto->getJurosApos() == 0 ? '00000000' : + $boleto->getDataVencimentoApos()->format('dmY')); + $this->add(127, 141, Util::formatCnab('9', $boleto->getMoraDia(), 15, 2)); //Valor da mora/dia ou Taxa mensal + $this->add(142, 142, $boleto->getDesconto() > 0 ? 2 : 0); // '2' = Percentual Até a Data Informada + $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); + $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); + $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); + $this->add(181, 195, Util::formatCnab('9', 0, 15, 2)); + $this->add(196, 220, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); + $this->add(221, 221, self::PROTESTO_SEM); + if ($boleto->getDiasProtesto() > 0) { + $this->add(221, 221, self::PROTESTO_DIAS_CORRIDOS); + } + $this->add(222, 223, Util::formatCnab('9', $boleto->getDiasProtesto(), 2)); + $this->add(224, 224, $boleto->getDiasBaixaAutomatica() > 0 ? 1 : 2); // '1' = Baixar / Devolver; '2' = Não Baixar / Não Devolver + $this->add(225, 227, Util::formatCnab('9', $boleto->getDiasBaixaAutomatica(), 3)); // Utilizar sempre, nesse campo, 60 dias para baixa/devolução. + $this->add(228, 229, Util::formatCnab('9', $boleto->getMoeda(), 2)); + $this->add(230, 239, '0000000000'); + $this->add(240, 240, ''); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + public function segmentoQ(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'Q'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(18, 18, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 15)); + $this->add(34, 73, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(74, 113, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(114, 128, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 15)); + $this->add(129, 133, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 5)); + $this->add(134, 136, Util::formatCnab('9', Util::onlyNumbers(substr($boleto->getPagador()->getCep(), 6, 9)), 3)); + $this->add(137, 151, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); + $this->add(152, 153, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(154, 154, '0'); + $this->add(155, 169, '000000000000000'); + $this->add(170, 209, ''); + $this->add(210, 212, '000'); + $this->add(213, 232, ''); + $this->add(233, 240, ''); + + if ($boleto->getSacadorAvalista()) { + $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); + $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); + $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 40)); + } + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + protected function segmentoR(BoletoContract $boleto) + { + if (! $boleto->getMulta() > 0 && ! $boleto->getDesconto() > 0) { + return $this; + } + + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'R'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + + $this->add(18, 18, '0'); + $this->add(19, 26, '00000000'); + $this->add(27, 41, Util::formatCnab('9', 0, 15, 2)); + $this->add(42, 42, '0'); + $this->add(43, 50, '00000000'); + $this->add(51, 65, Util::formatCnab('9', 0, 15, 2)); + $this->add(66, 66, '0'); + $this->add(67, 74, '00000000'); + $this->add(75, 89, Util::formatCnab('9', 0, 15, 2)); + if ($boleto->getMulta() > 0) { + $this->add(66, 66, '2'); // '2' = Percentual + $this->add(67, 74, $boleto->getDataVencimento()->format('dmY')); + $this->add(75, 89, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); + } + $this->add(90, 99, Util::formatCnab('X', '', 10)); + $this->add(100, 139, Util::formatCnab('X', '', 40)); + $this->add(140, 179, Util::formatCnab('X', '', 40)); + $this->add(180, 199, Util::formatCnab('X', '', 20)); + $this->add(200, 207, Util::formatCnab('9', 0, 8)); + $this->add(208, 210, Util::formatCnab('9', Util::onlyNumbers($this->getCodigoBanco()), 3)); + $this->add(211, 215, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(216, 216, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(217, 228, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(229, 229, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(230, 230, ''); + $this->add(231, 231, ''); + $this->add(232, 240, Util::formatCnab('X', '', 9)); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + /** + * HEADER DE ARQUIVO + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0000'); + $this->add(8, 8, '0'); + $this->add(9, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); + $this->add(33, 52, Util::formatCnab('X', $this->getCodigoCliente(), 20)); + $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(58, 58, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(71, 71, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(72, 72, ''); + $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(103, 132, Util::formatCnab('X', 'BANCO BTG PACTUAL S.A.', 30)); + $this->add(133, 142, ''); + $this->add(143, 143, 1); + $this->add(144, 151, $this->getDataRemessa('dmY')); + $this->add(152, 157, date('His')); + $this->add(158, 163, Util::formatCnab('9', $this->getIdremessa(), 6)); + $this->add(164, 166, '083'); + $this->add(167, 171, '00000'); + $this->add(172, 191, ''); + $this->add(192, 211, ''); + $this->add(212, 240, ''); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function headerLote() + { + $this->iniciaHeaderLote(); + + /** + * HEADER DE LOTE + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '1'); + $this->add(9, 9, 'R'); + $this->add(10, 11, '01'); + $this->add(12, 13, ''); + $this->add(14, 16, '060'); + $this->add(17, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); + $this->add(34, 53, Util::formatCnab('X', '', 20)); + $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(59, 59, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(72, 72, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(73, 73, ''); + $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(104, 183, ''); + $this->add(184, 191, Util::formatCnab('9', $this->getIdremessa(), 8)); + $this->add(192, 199, date('dmY')); + $this->add(200, 207, '00000000'); + $this->add(208, 240, ''); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function trailerLote() + { + $this->iniciaTrailerLote(); + + $valor = array_reduce($this->boletos, function ($valor, $boleto) { + return $valor + $boleto->getValor(); + }, 0); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '5'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', $this->getCountDetalhes() + 2, 6)); + $this->add(24, 29, Util::formatCnab('9', 0, 6)); + $this->add(30, 46, Util::formatCnab('9', 0, 17, 2)); + $this->add(47, 52, Util::formatCnab('9', 0, 6)); + $this->add(53, 69, Util::formatCnab('9', 0, 17, 2)); + $this->add(70, 75, Util::formatCnab('9', 0, 6)); + $this->add(76, 92, Util::formatCnab('9', 0, 17, 2)); + $this->add(93, 98, Util::formatCnab('9', 0, 6)); + $this->add(99, 115, Util::formatCnab('9', 0, 17, 2)); + $this->add(116, 123, '00000000'); + $this->add(124, 240, ''); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '9999'); + $this->add(8, 8, '9'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', 1, 6)); + $this->add(24, 29, Util::formatCnab('9', $this->getCount(), 6)); + $this->add(30, 35, '000000'); + $this->add(36, 240, ''); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Caixa.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Caixa.php index f0db00a0..3ef66499 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Caixa.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Caixa.php @@ -1,23 +1,16 @@ segmentoP($boleto); $this->segmentoQ($boleto); $this->segmentoR($boleto); + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -140,7 +132,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); } $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(23, 23, CalculoDV::cefAgencia($this->getAgencia())); + $this->add(23, 23, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::cefAgencia($this->getAgencia())); if (strlen($this->getCodigoCliente()) == 7) { $this->add(24, 30, Util::formatCnab('9', $this->getCodigoCliente(), 7)); $this->add(31, 37, '0000000'); @@ -165,7 +157,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); $this->add(118, 118, $boleto->getJuros() ? '2' : '3'); //'2' = Percentual Mensal '3' = Isento - $this->add(119, 126, $boleto->getDataVencimento()->copy()->addDays($boleto->getJurosApos() === false ? 1 : (int)$boleto->getJurosApos())->format('dmY')); + $this->add(119, 126, $boleto->getDataVencimento()->copy()->addDays($boleto->getJurosApos() === false ? 1 : (int) $boleto->getJurosApos())->format('dmY')); $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 2)); //Taxa mensal $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); // 0 = Sem Desconto, 1 = Valor Fixo até a data informada, 2 = Percentual até a data informada $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); @@ -190,8 +182,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -243,8 +235,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { @@ -277,8 +269,8 @@ public function segmentoR(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function header() { @@ -295,7 +287,7 @@ protected function header() $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); $this->add(33, 52, Util::formatCnab('9', 0, 20)); $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(58, 58, CalculoDV::cefAgencia($this->getAgencia())); + $this->add(58, 58, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::cefAgencia($this->getAgencia())); if (strlen($this->getCodigoCliente()) == 7) { $this->add(59, 65, Util::formatCnab('9', $this->getCodigoCliente(), 7)); $this->add(66, 72, '0000000'); @@ -316,12 +308,13 @@ protected function header() $this->add(192, 211, Util::formatCnab('X', 'REMESSA-PRODUCAO', 20)); $this->add(212, 215, ''); $this->add(216, 240, ''); + return $this; } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function headerLote() { @@ -348,7 +341,7 @@ protected function headerLote() $this->add(40, 53, Util::formatCnab('9', 0, 14)); } $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(59, 59, CalculoDV::cefAgencia($this->getAgencia())); + $this->add(59, 59, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::cefAgencia($this->getAgencia())); if (strlen($this->getCodigoCliente()) == 7) { $this->add(60, 65, '000000'); } else { @@ -367,8 +360,8 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function trailerLote() { @@ -396,8 +389,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Itau.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Itau.php index cfadc8b4..d5f61d3d 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Itau.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Itau.php @@ -1,18 +1,13 @@ boletos[] = $boleto; $this->segmentoP($boleto); $this->segmentoQ($boleto); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->segmentoY($boleto); } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -107,7 +101,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(24, 30, '0000000'); $this->add(31, 35, Util::formatCnab('9', $this->getConta(), 5)); $this->add(36, 36, ''); - $this->add(37, 37, CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(37, 37, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); $this->add(38, 40, Util::formatCnab('9', $this->getCarteira(), 3)); $this->add(41, 49, Util::formatCnab('9', $boleto->getNossoNumero(), 9)); $this->add(50, 57, ''); @@ -146,8 +140,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -188,7 +182,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 199, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -200,8 +194,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ public function segmentoY(BoletoContract $boleto) { @@ -234,8 +228,8 @@ public function segmentoY(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function header() { @@ -257,7 +251,7 @@ protected function header() $this->add(59, 65, '0000000'); $this->add(66, 70, Util::formatCnab('9', $this->getConta(), 5)); $this->add(71, 71, ''); - $this->add(72, 72, CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'BANCO ITAU SA', 30)); $this->add(133, 142, ''); @@ -270,12 +264,13 @@ protected function header() $this->add(172, 225, ''); $this->add(226, 228, '000'); $this->add(229, 240, ''); + return $this; } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function headerLote() { @@ -301,7 +296,7 @@ protected function headerLote() $this->add(60, 66, '0000000'); $this->add(67, 71, Util::formatCnab('9', $this->getConta(), 5)); $this->add(72, 72, ''); - $this->add(73, 73, CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(73, 73, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); $this->add(184, 191, Util::formatCnab('9', 0, 8)); @@ -313,14 +308,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -341,8 +336,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Santander.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Santander.php index 8c04ccd1..05705287 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Santander.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Santander.php @@ -1,25 +1,13 @@ iniciaDetalhe(); $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); - $this->add(4, 7, sprintf("%04d", $this->getIdremessa())); + $this->add(4, 7, sprintf('%04d', $this->getIdremessa())); $this->add(8, 8, '3'); $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); $this->add(14, 14, 'P'); @@ -140,9 +127,9 @@ protected function segmentoP(BoletoContract $boleto) $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(22, 22, $this->getAgenciaDv() ?: Util::formatCnab('9', '', 1)); $this->add(23, 31, Util::formatCnab('9', $this->getConta(), 9)); - $this->add(32, 32, $this->getContaDv() ?: CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(32, 32, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta())); $this->add(33, 41, Util::formatCnab('9', $this->getConta(), 9)); - $this->add(42, 42, $this->getContaDv() ?: CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(42, 42, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta())); $this->add(43, 44, ''); $this->add(45, 57, Util::formatCnab('9', $boleto->getNossoNumero(), 13)); $this->add(58, 58, Util::formatCnab('9', $this->getCarteiraNumero() > 200 ? '1' : '5', 1)); @@ -153,8 +140,8 @@ protected function segmentoP(BoletoContract $boleto) $this->add(63, 77, Util::formatCnab('9', $boleto->getNumeroDocumento(), 15)); $this->add(78, 85, $boleto->getDataVencimento()->format('dmY')); $this->add(86, 100, Util::formatCnab('9', $boleto->getValor(), 15, 2)); - $this->add(101, 104, Util::formatCnab('9', $this->getConta(), 4)); - $this->add(105, 105, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(101, 104, Util::formatCnab('9', 0, 4)); + $this->add(105, 105, Util::formatCnab('9', 0, 1)); $this->add(106, 106, ''); $this->add(107, 108, Util::formatCnab('9', $boleto->getEspecieDocCodigo('02', 240), 2)); $this->add(109, 109, Util::formatCnab('9', 'N', 1)); @@ -162,12 +149,12 @@ protected function segmentoP(BoletoContract $boleto) $this->add(118, 118, ($boleto->getJuros() !== null && $boleto->getJuros() > 0) ? '2' : '3'); //3 = ISENTO | 1 = R$ ao dia | 2 = % ao mês $this->add(119, 126, Util::formatCnab('9', ($boleto->getJuros() !== null && $boleto->getJuros() > 0) ? $boleto->getDataVencimento()->format('dmY') : 0, 8)); $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 5)); - $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL + $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); $this->add(181, 195, Util::formatCnab('9', 0, 15, 2)); - $this->add(196, 220, ''); + $this->add(196, 220, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); $this->add(221, 221, self::PROTESTO_SEM); if ($boleto->getDiasProtesto() > 0) { $this->add(221, 221, self::PROTESTO_DIAS_UTEIS); @@ -185,15 +172,15 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Santander + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { $this->iniciaDetalhe(); $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); - $this->add(4, 7, sprintf("%04d", $this->getIdremessa())); + $this->add(4, 7, sprintf('%04d', $this->getIdremessa())); $this->add(8, 8, '3'); $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); $this->add(14, 14, 'Q'); @@ -235,14 +222,14 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Santander + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { $this->iniciaDetalhe(); $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); - $this->add(4, 7, sprintf("%04d", $this->getIdremessa())); + $this->add(4, 7, sprintf('%04d', $this->getIdremessa())); $this->add(8, 8, '3'); $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); $this->add(14, 14, 'R'); @@ -267,8 +254,8 @@ public function segmentoR(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Santander + * @throws ValidationException */ protected function header() { @@ -303,7 +290,7 @@ protected function header() * Retorna o codigo de transmissão. * * @return string - * @throws \Exception + * @throws ValidationException */ public function getCodigoTransmissao() { @@ -313,8 +300,8 @@ public function getCodigoTransmissao() } /** - * @return $this - * @throws \Exception + * @return Santander + * @throws ValidationException */ protected function headerLote() { @@ -324,7 +311,7 @@ protected function headerLote() * HEADER DE LOTE */ $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); - $this->add(4, 7, sprintf("%04d", $this->getIdremessa())); + $this->add(4, 7, sprintf('%04d', $this->getIdremessa())); $this->add(8, 8, '1'); $this->add(9, 9, 'R'); $this->add(10, 11, '01'); @@ -339,7 +326,7 @@ protected function headerLote() $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 143, ''); $this->add(144, 183, ''); - $this->add(184, 191, sprintf("%08d", $this->getIdremessa())); + $this->add(184, 191, sprintf('%08d', $this->getIdremessa())); $this->add(192, 199, date('dmY')); $this->add(200, 240, ''); @@ -347,15 +334,15 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Santander + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); - $this->add(4, 7, sprintf("%04d", $this->getIdremessa())); + $this->add(4, 7, sprintf('%04d', $this->getIdremessa())); $this->add(8, 8, '5'); $this->add(9, 17, ''); $this->add(18, 23, Util::formatCnab('9', $this->getCountDetalhes() + 2, 6)); @@ -365,8 +352,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Santander + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Sicredi.php b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Sicredi.php index db9f5eda..e13acdca 100644 --- a/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Sicredi.php +++ b/src/Cnab/Remessa/Cnab240/Cobranca/Banco/Sicredi.php @@ -1,22 +1,15 @@ carteira = 'A'; + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -91,17 +84,18 @@ public function addBoleto(BoletoContract $boleto) $this->segmentoP($boleto); $this->segmentoQ($boleto); $this->segmentoR($boleto); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->segmentoY01($boleto); } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -140,7 +134,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); $this->add(118, 118, $boleto->getJuros() ? '1' : '3'); //'1' = Valor por Dia, '3' = Isento $this->add(119, 126, $boleto->getJurosApos() == 0 ? '00000000' : - $boleto->getDataVencimentoApos()->format('dmY')); + $boleto->getDataVencimentoApos()->format('dmY')); $this->add(127, 141, Util::formatCnab('9', $boleto->getMoraDia(), 15, 2)); //Valor da mora/dia ou Taxa mensal $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); @@ -165,12 +159,12 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function segmentoR(BoletoContract $boleto) { - if (!$boleto->getMulta() > 0 && !$boleto->getDesconto() > 0) { + if (! $boleto->getMulta() > 0 && ! $boleto->getDesconto() > 0) { return $this; } @@ -225,7 +219,7 @@ protected function segmentoR(BoletoContract $boleto) $this->add(211, 215, Util::formatCnab('9', $this->getAgencia(), 5)); $this->add(216, 216, ''); $this->add(217, 228, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(229, 229, Util::modulo11($this->getConta())); + $this->add(229, 229, Util::formatCnab('9', $this->getContaDv(), 1)); $this->add(230, 230, ''); $this->add(231, 231, ''); $this->add(232, 240, Util::formatCnab('X', '', 9)); @@ -236,8 +230,8 @@ protected function segmentoR(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -277,7 +271,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(213, 232, ''); $this->add(233, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -289,8 +283,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ public function segmentoY01(BoletoContract $boleto) { @@ -323,8 +317,8 @@ public function segmentoY01(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function header() { @@ -358,13 +352,12 @@ protected function header() $this->add(192, 211, ''); $this->add(212, 240, ''); - return $this; } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function headerLote() { @@ -400,14 +393,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -431,8 +424,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Ailos.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Ailos.php new file mode 100644 index 00000000..c3d11bf4 --- /dev/null +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Ailos.php @@ -0,0 +1,492 @@ +setCarteira('1'); //Carteira única + $this->addCampoObrigatorio('convenio', 'agencia', 'agenciaDV'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_AILOS; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = ['1']; + + /** + * Convenio com o banco + * + * @var string + */ + protected $convenio; + + /** + * Nome da cooperativa + * + * @var string + */ + protected $cooperativa; + + /** + * Agência + * + * @var int + */ + protected $agenciaDv; + + /** + * Define o código da carteira (Com ou sem registro) + * + * @param string $carteira + * + * @return Ailos + */ + public function setCarteira($carteira) + { + $this->carteira = 1; + return $this; + } + + /** + * @return mixed + */ + public function getConvenio() + { + return $this->convenio; + } + + /** + * @param mixed $convenio + * + * @return Ailos + */ + public function setConvenio($convenio) + { + $this->convenio = ltrim($convenio, 0); + + return $this; + } + + /** + * Retorna a agência dígito verificador + * + * @return int + */ + public function getAgenciaDv() + { + return $this->agenciaDv; + } + + /** + * Define a agência dígito verificador + * + * @param int $agenciaDv + * + * @return Ailos + */ + public function setAgenciaDv($agenciaDv) + { + $this->agenciaDv = (string) $agenciaDv; + + return $this; + } + + /** + * Retorna nome cooperativa + * + * @return int + */ + public function getCooperativa() + { + return $this->cooperativa; + } + + /** + * Define nome cooperativa + * + * @param int $cooperativa + * + * @return Ailos + */ + public function setCooperativa($cooperativa) + { + $this->cooperativa = strtoupper($cooperativa); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->segmentoP($boleto); + $this->segmentoQ($boleto); + $this->segmentoR($boleto); + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + protected function segmentoP(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'P'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(23, 23, $this->getAgenciaDv()); + $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(36, 36, $this->getContaDv()); + $this->add(37, 37, ''); + $this->add(38, 57, Util::formatCnab('X', $boleto->getNossoNumero(), 20)); + $this->add(58, 58, '1'); //'1' = Cobrança Simples + $this->add(59, 59, '1'); //'1' = Com cadastramento (cobrança registrada) + $this->add(60, 60, '1'); //'1' = Tradicional + $this->add(61, 61, '2'); //'2' = Beneficiário/Cooperado emite + $this->add(62, 62, '2'); //'2' = Beneficiário/Cooperado distribui + $this->add(63, 77, Util::formatCnab('9', $boleto->getNumeroDocumento(), 15)); + $this->add(78, 85, $boleto->getDataVencimento()->format('dmY')); + $this->add(86, 100, Util::formatCnab('9', $boleto->getValor(), 15, 2)); + $this->add(101, 105, '00000'); + $this->add(106, 106, ''); + $this->add(107, 108, Util::formatCnab('9', $boleto->getEspecieDocCodigo(), 2)); + $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); + $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); + $this->add(118, 118, $boleto->getJuros() ? '2' : '3'); //'1' = Valor por Dia, 2 = Taxa mensal '3' = Isento + $this->add(119, 126, $boleto->getJurosApos() == 0 ? '00000000' : + $boleto->getDataVencimentoApos()->copy()->addDays((int) $boleto->getJurosApos())->format('dmY')); + $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 2)); //Valor da mora/dia ou Taxa mensal + $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); + $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); + $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); + $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); + $this->add(181, 195, Util::formatCnab('9', 0, 15, 2)); + $this->add(196, 220, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); + $this->add(221, 221, self::PROTESTO_SEM); + if ($boleto->getDiasProtesto() > 0) { + $this->add(221, 221, self::PROTESTO_DIAS_CORRIDOS); + } + $this->add(222, 223, Util::formatCnab('9', $boleto->getDiasProtesto(), 2)); + $this->add(224, 224, '2'); // Deverá ser informado o código ‘2’, visto que o sistema respeita o decurso de prazo cadastrado no convênio do cooperado.. + $this->add(225, 227, ''); // Utilizar sempre, nesse campo, 60 dias para baixa/devolução. + $this->add(228, 229, Util::formatCnab('9', $boleto->getMoeda(), 2)); + $this->add(230, 239, '0000000000'); + $this->add(240, 240, ''); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + protected function segmentoR(BoletoContract $boleto) + { + if (!$boleto->getMulta() > 0 && !$boleto->getDesconto() > 0) { + return $this; + } + + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'R'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + + $this->add(18, 18, '0'); + $this->add(19, 26, '00000000'); + $this->add(27, 41, Util::formatCnab('9', 0, 15, 2)); + if ($boleto->getDesconto() > 0) { + $this->add(18, 18, '1'); // '1' = Valor fixo até a data informada + $this->add(19, 26, $boleto->getDataDesconto() ? $boleto->getDataDesconto()->format('dmY') : $boleto->getDataVencimento()->format('dmY')); + $this->add(27, 41, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); + } + + $this->add(42, 42, '0'); + $this->add(43, 50, Util::formatCnab('9', 0, 8)); + $this->add(51, 65, Util::formatCnab('9', 0, 15)); + $this->add(66, 66, '0'); + $this->add(67, 74, '00000000'); + $this->add(75, 89, Util::formatCnab('9', 0, 15, 2)); + if ($boleto->getMulta() > 0.01) { + $this->add(66, 66, '2'); // '2' = Percentual + $this->add(67, 74, $boleto->getDataVencimento()->format('dmY')); + $this->add(75, 89, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); + } + $this->add(90, 99, Util::formatCnab('X', '', 10)); + $this->add(100, 139, Util::formatCnab('X', '', 40)); + $this->add(140, 179, Util::formatCnab('X', '', 40)); + $this->add(180, 199, Util::formatCnab('X', '', 20)); + $this->add(200, 207, Util::formatCnab('9', 0, 8)); + $this->add(208, 210, Util::formatCnab('9', Util::onlyNumbers($this->getCodigoBanco()), 3)); + $this->add(211, 215, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(216, 216, $this->getAgenciaDv()); + $this->add(217, 228, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(229, 229, $this->getContaDv()); + $this->add(230, 230, ''); + $this->add(231, 231, ''); + $this->add(232, 240, Util::formatCnab('X', '', 9)); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Ailos + * @throws ValidationException + */ + public function segmentoQ(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'Q'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(18, 18, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 15)); + $this->add(34, 73, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getNome())), 40)); + $this->add(74, 113, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getEndereco())), 40)); + $this->add(114, 128, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getBairro())), 15)); + $this->add(129, 133, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 5)); + $this->add(134, 136, Util::formatCnab('9', Util::onlyNumbers(substr($boleto->getPagador()->getCep(), 6, 9)), 3)); + $this->add(137, 151, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getPagador()->getCidade())), 15)); + $this->add(152, 153, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(154, 154, '0'); + $this->add(155, 169, '000000000000000'); + $this->add(170, 209, ''); + $this->add(210, 212, '000'); + $this->add(213, 232, ''); + $this->add(233, 240, ''); + + if ($boleto->getSacadorAvalista()) { + $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); + $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); + $this->add(170, 209, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($boleto->getSacadorAvalista()->getNome())), 30)); + } + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + /** + * HEADER DE ARQUIVO + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0000'); + $this->add(8, 8, '0'); + $this->add(9, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); + $this->add(33, 52, Util::formatCnab('X', Util::formatCnab('9', Util::onlyNumbers($this->getConvenio()), 6), 20)); + $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(58, 58, $this->getAgenciaDv()); + $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(71, 71, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(72, 72, ''); + $this->add(73, 102, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($this->getBeneficiario()->getNome())), 30)); + $this->add(103, 132, Util::formatCnab('X', $this->getCooperativa() ?? 'AILOS', 30)); + $this->add(133, 142, ''); + $this->add(143, 143, 1); + $this->add(144, 151, $this->getDataRemessa('dmY')); + $this->add(152, 157, date('His')); + $this->add(158, 163, Util::formatCnab('9', $this->getIdremessa(), 6)); + $this->add(164, 166, '087'); + $this->add(167, 171, '01600'); + $this->add(172, 191, ''); + $this->add(192, 211, ''); + $this->add(212, 240, ''); + + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function headerLote() + { + $this->iniciaHeaderLote(); + + /** + * HEADER DE LOTE + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '1'); + $this->add(9, 9, 'R'); + $this->add(10, 11, '01'); + $this->add(12, 13, ''); + $this->add(14, 16, '045'); + $this->add(17, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); + $this->add(34, 53, Util::formatCnab('X', Util::formatCnab('9', Util::onlyNumbers($this->getConvenio()), 6), 20)); + $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(59, 59, $this->getAgenciaDv()); + $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(72, 72, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(73, 73, ''); + $this->add(74, 103, Util::formatCnab('X', str_replace('&', 'E', Util::normalizeChars($this->getBeneficiario()->getNome())), 30)); + $this->add(104, 183, Util::formatCnab('X', $this->getCooperativa(), 30)); + $this->add(184, 191, Util::formatCnab('9', $this->getIdremessa(), 8)); + $this->add(192, 199, date('dmY')); + $this->add(200, 207, '00000000'); + $this->add(208, 240, ''); + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function trailerLote() + { + $this->iniciaTrailerLote(); + + $valor = array_reduce($this->boletos, function ($valor, $boleto) { + return $valor + $boleto->getValor(); + }, 0); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '5'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', $this->getCountDetalhes() + 2, 6)); + $this->add(24, 29, Util::formatCnab('9', 0, 6)); + $this->add(30, 46, Util::formatCnab('9', 0, 17, 2)); + $this->add(47, 52, Util::formatCnab('9', 0, 6)); + $this->add(53, 69, Util::formatCnab('9', 0, 17, 2)); + $this->add(70, 75, Util::formatCnab('9', 0, 6)); + $this->add(76, 92, Util::formatCnab('9', 0, 17, 2)); + $this->add(93, 98, Util::formatCnab('9', 0, 6)); + $this->add(99, 115, Util::formatCnab('9', 0, 17, 2)); + $this->add(116, 123, '00000000'); + $this->add(124, 240, ''); + + return $this; + } + + /** + * @return Ailos + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '9999'); + $this->add(8, 8, '9'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', 1, 6)); + $this->add(24, 29, Util::formatCnab('9', $this->getCount(), 6)); + $this->add(30, 35, '000000'); + $this->add(36, 240, ''); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bancoob.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bancoob.php index f34b1148..3559b433 100644 --- a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bancoob.php +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bancoob.php @@ -9,11 +9,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab240\Pagamento\Banco; +use VinicciusGuedes\LaravelCnab\Util; use VinicciusGuedes\LaravelCnab\CalculoDV; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab240\AbstractRemessa; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Remessa as RemessaContract; -use VinicciusGuedes\LaravelCnab\Util; class Bancoob extends AbstractRemessa implements RemessaContract { @@ -34,7 +35,6 @@ class Bancoob extends AbstractRemessa implements RemessaContract const OCORRENCIA_EXC_NEGATIVACAO = '68'; const OCORRENCIA_CANC_NEGATIVACAO = '69'; const OCORRENCIA_DESCONTAR_TITULOS_DIA = '93'; - const PROTESTO_DIAS_CORRIDOS = '1'; const PROTESTO_DIAS_UTEIS = '2'; const PROTESTO_NAO_PROTESTAR = '3'; @@ -54,7 +54,6 @@ public function __construct(array $params = []) */ protected $codigoBanco = BoletoContract::COD_BANCO_BANCOOB; - /** * Define as carteiras disponíveis para cada banco * @@ -74,13 +73,12 @@ public function __construct(array $params = []) * * @var null */ - protected $fimArquivo = ""; + protected $fimArquivo = ''; /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob */ public function addBoleto(BoletoContract $boleto) { @@ -88,14 +86,15 @@ public function addBoleto(BoletoContract $boleto) $this->segmentoP($boleto); $this->segmentoQ($boleto); $this->segmentoR($boleto); + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -120,9 +119,9 @@ protected function segmentoP(BoletoContract $boleto) $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); } $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(23, 23, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(23, 23, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(36, 36, Util::formatCnab('X', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(36, 36, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(37, 37, ''); $this->add(38, 47, Util::formatCnab('9', $boleto->getNossoNumero(), 10)); $this->add(48, 49, '01'); //Parcela Única @@ -145,7 +144,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(118, 118, ($boleto->getJuros() !== null && $boleto->getJuros() > 0) ? '2' : '0'); //0 = ISENTO | 1 = R$ ao dia | 2 = % ao mês $this->add(119, 126, ($boleto->getJuros() !== null && $boleto->getJuros() > 0) ? $boleto->getDataVencimento()->copy()->addDays($boleto->getJurosApos() ?: 1)->format('dmY') : '00000000'); $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 2)); //Taxa mensal - $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL + $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); //0 = SEM DESCONTO | 1 = VALOR FIXO | 2 = PERCENTUAL $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); @@ -168,8 +167,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -202,7 +201,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, Util::formatCnab('X', '', 28)); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 40)); @@ -214,8 +213,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { @@ -240,7 +239,7 @@ public function segmentoR(BoletoContract $boleto) $this->add(43, 50, '00000000'); $this->add(51, 65, '000000000000000'); $this->add(66, 66, $boleto->getMulta() > 0 ? '2' : '0'); //0 = ISENTO | 1 = VALOR FIXO | 2 = PERCENTUAL - $this->add(67, 74, $boleto->getMulta() > 0 ? $boleto->getDataVencimento()->copy()->addDay()->format('dmY') : '00000000'); + $this->add(67, 74, $boleto->getMulta() > 0 ? $boleto->getDataVencimento()->copy()->addDay()->format('dmY') : '00000000'); $this->add(75, 89, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); //2,20 = 0000000000220 $this->add(90, 199, ''); $this->add(200, 207, '00000000'); @@ -256,8 +255,8 @@ public function segmentoR(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function header() { @@ -274,9 +273,9 @@ protected function header() $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); $this->add(33, 52, ''); $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(58, 58, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(58, 58, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(71, 71, Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(71, 71, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(72, 72, '0'); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'SICOOB', 30)); @@ -290,12 +289,13 @@ protected function header() $this->add(172, 191, ''); $this->add(192, 211, ''); $this->add(212, 240, ''); + return $this; } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function headerLote() { @@ -316,9 +316,9 @@ protected function headerLote() $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); $this->add(34, 53, ''); $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(59, 59, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(59, 59, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(72, 72, Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(73, 73, ''); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); @@ -331,14 +331,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -358,8 +358,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Bancoob + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Banrisul.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Banrisul.php index 9e6f0cb9..1cf2879f 100644 --- a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Banrisul.php +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Banrisul.php @@ -1,22 +1,16 @@ Cobrança Simples @@ -69,7 +61,7 @@ public function __construct(array $params = []) * U -> CSB e CCB sem registro * @var array */ - protected $carteiras = ['1','2', '3', 'B', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'N', 'P', 'R', 'S', 'T', 'U']; + protected $carteiras = ['1', '2', '3', 'B', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'N', 'P', 'R', 'S', 'T', 'U']; /** * Codigo do cliente junto ao banco. @@ -105,25 +97,26 @@ public function setCodigoCliente($codigoCliente) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { $this->boletos[] = $boleto; $this->segmentoP($boleto); $this->segmentoQ($boleto); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->segmentoY01($boleto); } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -150,7 +143,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); $this->add(23, 23, ''); $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(36, 36, CalculoDV::banrisulContaCorrente($this->getConta())); + $this->add(36, 36, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::banrisulContaCorrente($this->getConta())); $this->add(37, 37, ''); $this->add(38, 57, Util::formatCnab('9', $boleto->getNossoNumero(), 20)); $this->add(58, 58, $this->getCarteira()); @@ -192,8 +185,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -226,7 +219,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -238,8 +231,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ public function segmentoY01(BoletoContract $boleto) { @@ -272,8 +265,8 @@ public function segmentoY01(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function header() { @@ -293,7 +286,7 @@ protected function header() $this->add(58, 58, ''); $this->add(59, 63, '000EE'); $this->add(64, 70, Util::formatCnab('9', $this->getConta(), 7)); - $this->add(71, 71, CalculoDV::banrisulContaCorrente($this->getConta())); + $this->add(71, 71, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::banrisulContaCorrente($this->getConta())); $this->add(72, 72, ''); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'BANRISUL', 30)); @@ -318,8 +311,8 @@ protected function header() } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function headerLote() { @@ -342,7 +335,7 @@ protected function headerLote() $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); $this->add(59, 59, ''); $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(72, 72, CalculoDV::banrisulContaCorrente($this->getConta())); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::banrisulContaCorrente($this->getConta())); $this->add(73, 73, ''); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); @@ -355,8 +348,8 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function trailerLote() { @@ -386,8 +379,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Banrisul + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bb.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bb.php index 4fefcaaf..154fce1f 100644 --- a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bb.php +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bb.php @@ -1,22 +1,16 @@ boletos[] = $boleto; $this->segmentoP($boleto); $this->segmentoQ($boleto); - if($boleto->getStatus() == $boleto::STATUS_REGISTRO) { - $this->segmentoR($boleto); - } + if ($boleto->getStatus() == $boleto::STATUS_REGISTRO) { + $this->segmentoR($boleto); + } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -187,9 +181,9 @@ protected function segmentoP(BoletoContract $boleto) $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); } $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(23, 23, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(23, 23, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(36, 36, CalculoDV::bbContaCorrente($this->getConta())); + $this->add(36, 36, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(37, 37, ''); $this->add(38, 57, Util::formatCnab('X', $this->nossoNumero($boleto), 20)); $this->add(58, 58, '1'); //'1' = Cobrança Simples @@ -201,7 +195,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(78, 85, $boleto->getDataVencimento()->format('dmY')); $this->add(86, 100, Util::formatCnab('9', $boleto->getValor(), 15, 2)); $this->add(101, 105, '00000'); - $this->add(106, 106, '0'); + $this->add(106, 106, ''); $this->add(107, 108, Util::formatCnab('9', $boleto->getEspecieDocCodigo(), 2)); $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); @@ -231,8 +225,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -271,7 +265,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(210, 212, '000'); $this->add(213, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -283,8 +277,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { @@ -331,8 +325,8 @@ public function segmentoR(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function header() { @@ -353,9 +347,9 @@ protected function header() $this->add(48, 50, Util::formatCnab('9', $this->getVariacaoCarteira(), 3)); $this->add(51, 52, ''); $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(58, 58, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(58, 58, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(71, 71, CalculoDV::bbContaCorrente($this->getConta())); + $this->add(71, 71, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(72, 72, ''); $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(103, 132, Util::formatCnab('X', 'BANCO DO BRASIL S.A.', 30)); @@ -373,8 +367,8 @@ protected function header() } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function headerLote() { @@ -389,7 +383,7 @@ protected function headerLote() $this->add(9, 9, 'R'); $this->add(10, 11, '01'); $this->add(12, 13, ''); - $this->add(14, 16, '042'); + $this->add(14, 16, '043'); $this->add(17, 17, ''); $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); @@ -399,9 +393,9 @@ protected function headerLote() $this->add(49, 51, Util::formatCnab('9', $this->getVariacaoCarteira(), 3)); $this->add(52, 53, ''); $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(59, 59, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(59, 59, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(72, 72, CalculoDV::bbContaCorrente($this->getConta())); + $this->add(72, 72, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(73, 73, ''); $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(104, 183, ''); @@ -414,8 +408,8 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function trailerLote() { @@ -432,8 +426,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Bb + * @throws ValidationException */ protected function trailer() { @@ -456,11 +450,13 @@ protected function trailer() * * @return mixed|string */ - private function nossoNumero(BoletoContract $boleto) { + private function nossoNumero(BoletoContract $boleto) + { $convenio = (int) Util::onlyNumbers($this->getConvenio()); if ($convenio > 1000000) { return $boleto->getNossoNumero(); } + return $boleto->getNossoNumero() . CalculoDV::bbNossoNumero($boleto->getNossoNumero()); } } diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bradesco.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bradesco.php index 53b13b8e..ba4a5519 100644 --- a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bradesco.php +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Bradesco.php @@ -1,22 +1,16 @@ codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . Util::formatCnab('9', $this->getAgencia(), 5) . Util::formatCnab('9', $this->getConta(), 7) . - Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bradescoContaCorrente($this->getConta()), 1); + Util::formatCnab('9', ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bradescoContaCorrente($this->getConta()), 1); } return $this->codigoCliente; @@ -128,8 +118,8 @@ public function setCodigoCliente($codigoCliente) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -142,8 +132,8 @@ public function addBoleto(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function segmentoJ(BoletoContract $boleto) { @@ -176,8 +166,8 @@ public function segmentoJ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ public function segmentoJ52(BoletoContract $boleto) { @@ -211,8 +201,8 @@ public function segmentoJ52(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function header() { @@ -248,9 +238,10 @@ protected function header() $this->add(231, 240, ''); return $this; } + /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function headerLote() { @@ -289,15 +280,16 @@ protected function headerLote() return $this; } + /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -314,9 +306,10 @@ protected function trailerLote() return $this; } + /** - * @return $this - * @throws \Exception + * @return Bradesco + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Btg.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Btg.php new file mode 100644 index 00000000..22d761ce --- /dev/null +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Btg.php @@ -0,0 +1,408 @@ +addCampoObrigatorio('codigoCliente'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_BTG; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = [1, 2, 3, 4, 5, 6]; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return Btg + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->segmentoP($boleto); + $this->segmentoQ($boleto); + $this->segmentoR($boleto); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + protected function segmentoP(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'P'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(23, 23, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(24, 35, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(36, 36, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(37, 37, ''); + $this->add(38, 57, Util::formatCnab('X', $boleto->getNossoNumero(), 20)); + $this->add(58, 58, $this->getCarteira()); + $this->add(59, 59, '1'); //'1' = Com cadastramento (cobrança registrada) + $this->add(60, 60, '1'); //'1' = Tradicional + $this->add(61, 61, '2'); //'2' = Beneficiário emite + $this->add(62, 62, '2'); //'2' = Beneficiário distribui + $this->add(63, 77, Util::formatCnab('9', $boleto->getNumeroDocumento(), 15)); + $this->add(78, 85, $boleto->getDataVencimento()->format('dmY')); + $this->add(86, 100, Util::formatCnab('9', $boleto->getValor(), 15, 2)); + $this->add(101, 105, '00000'); + $this->add(106, 106, ''); + $this->add(107, 108, Util::formatCnab('9', $boleto->getEspecieDocCodigo(), 2)); + $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); + $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); + $this->add(118, 118, $boleto->getJuros() ? '1' : '3'); //'1' = Valor por Dia, '3' = Isento + $this->add(119, 126, $boleto->getJurosApos() == 0 ? '00000000' : + $boleto->getDataVencimentoApos()->format('dmY')); + $this->add(127, 141, Util::formatCnab('9', $boleto->getMoraDia(), 15, 2)); //Valor da mora/dia ou Taxa mensal + $this->add(142, 142, $boleto->getDesconto() > 0 ? 2 : 0); // '2' = Percentual Até a Data Informada + $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); + $this->add(151, 165, Util::formatCnab('9', $boleto->getDesconto(), 15, 2)); + $this->add(166, 180, Util::formatCnab('9', 0, 15, 2)); + $this->add(181, 195, Util::formatCnab('9', 0, 15, 2)); + $this->add(196, 220, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); + $this->add(221, 221, self::PROTESTO_SEM); + if ($boleto->getDiasProtesto() > 0) { + $this->add(221, 221, self::PROTESTO_DIAS_CORRIDOS); + } + $this->add(222, 223, Util::formatCnab('9', $boleto->getDiasProtesto(), 2)); + $this->add(224, 224, $boleto->getDiasBaixaAutomatica() > 0 ? 1 : 2); // '1' = Baixar / Devolver; '2' = Não Baixar / Não Devolver + $this->add(225, 227, Util::formatCnab('9', $boleto->getDiasBaixaAutomatica(), 3)); // Utilizar sempre, nesse campo, 60 dias para baixa/devolução. + $this->add(228, 229, Util::formatCnab('9', $boleto->getMoeda(), 2)); + $this->add(230, 239, '0000000000'); + $this->add(240, 240, ''); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + public function segmentoQ(BoletoContract $boleto) + { + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'Q'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(18, 18, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 15)); + $this->add(34, 73, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(74, 113, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(114, 128, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 15)); + $this->add(129, 133, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 5)); + $this->add(134, 136, Util::formatCnab('9', Util::onlyNumbers(substr($boleto->getPagador()->getCep(), 6, 9)), 3)); + $this->add(137, 151, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); + $this->add(152, 153, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(154, 154, '0'); + $this->add(155, 169, '000000000000000'); + $this->add(170, 209, ''); + $this->add(210, 212, '000'); + $this->add(213, 232, ''); + $this->add(233, 240, ''); + + if ($boleto->getSacadorAvalista()) { + $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); + $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); + $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 40)); + } + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return Btg + * @throws ValidationException + */ + protected function segmentoR(BoletoContract $boleto) + { + if (! $boleto->getMulta() > 0 && ! $boleto->getDesconto() > 0) { + return $this; + } + + $this->iniciaDetalhe(); + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '3'); + $this->add(9, 13, Util::formatCnab('9', $this->iRegistrosLote, 5)); + $this->add(14, 14, 'R'); + $this->add(15, 15, ''); + $this->add(16, 17, self::OCORRENCIA_REMESSA); + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(16, 17, self::OCORRENCIA_PEDIDO_BAIXA); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(16, 17, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(16, 17, sprintf('%2.02s', $boleto->getComando())); + } + + $this->add(18, 18, '0'); + $this->add(19, 26, '00000000'); + $this->add(27, 41, Util::formatCnab('9', 0, 15, 2)); + $this->add(42, 42, '0'); + $this->add(43, 50, '00000000'); + $this->add(51, 65, Util::formatCnab('9', 0, 15, 2)); + $this->add(66, 66, '0'); + $this->add(67, 74, '00000000'); + $this->add(75, 89, Util::formatCnab('9', 0, 15, 2)); + if ($boleto->getMulta() > 0) { + $this->add(66, 66, '2'); // '2' = Percentual + $this->add(67, 74, $boleto->getDataVencimento()->format('dmY')); + $this->add(75, 89, Util::formatCnab('9', $boleto->getMulta(), 15, 2)); + } + $this->add(90, 99, Util::formatCnab('X', '', 10)); + $this->add(100, 139, Util::formatCnab('X', '', 40)); + $this->add(140, 179, Util::formatCnab('X', '', 40)); + $this->add(180, 199, Util::formatCnab('X', '', 20)); + $this->add(200, 207, Util::formatCnab('9', 0, 8)); + $this->add(208, 210, Util::formatCnab('9', Util::onlyNumbers($this->getCodigoBanco()), 3)); + $this->add(211, 215, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(216, 216, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(217, 228, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(229, 229, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(230, 230, ''); + $this->add(231, 231, ''); + $this->add(232, 240, Util::formatCnab('X', '', 9)); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + /** + * HEADER DE ARQUIVO + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0000'); + $this->add(8, 8, '0'); + $this->add(9, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); + $this->add(33, 52, Util::formatCnab('X', $this->getCodigoCliente(), 20)); + $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(58, 58, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(59, 70, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(71, 71, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(72, 72, ''); + $this->add(73, 102, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(103, 132, Util::formatCnab('X', 'BANCO BTG PACTUAL S.A.', 30)); + $this->add(133, 142, ''); + $this->add(143, 143, 1); + $this->add(144, 151, $this->getDataRemessa('dmY')); + $this->add(152, 157, date('His')); + $this->add(158, 163, Util::formatCnab('9', $this->getIdremessa(), 6)); + $this->add(164, 166, '083'); + $this->add(167, 171, '00000'); + $this->add(172, 191, ''); + $this->add(192, 211, ''); + $this->add(212, 240, ''); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function headerLote() + { + $this->iniciaHeaderLote(); + + /** + * HEADER DE LOTE + */ + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '1'); + $this->add(9, 9, 'R'); + $this->add(10, 11, '01'); + $this->add(12, 13, ''); + $this->add(14, 16, '060'); + $this->add(17, 17, ''); + $this->add(18, 18, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? 2 : 1); + $this->add(19, 33, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 15)); + $this->add(34, 53, Util::formatCnab('X', '', 20)); + $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(59, 59, Util::formatCnab('9', $this->getAgenciaDv(), 1)); + $this->add(60, 71, Util::formatCnab('9', $this->getConta(), 12)); + $this->add(72, 72, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(73, 73, ''); + $this->add(74, 103, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(104, 183, ''); + $this->add(184, 191, Util::formatCnab('9', $this->getIdremessa(), 8)); + $this->add(192, 199, date('dmY')); + $this->add(200, 207, '00000000'); + $this->add(208, 240, ''); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function trailerLote() + { + $this->iniciaTrailerLote(); + + $valor = array_reduce($this->boletos, function ($valor, $boleto) { + return $valor + $boleto->getValor(); + }, 0); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '0001'); + $this->add(8, 8, '5'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', $this->getCountDetalhes() + 2, 6)); + $this->add(24, 29, Util::formatCnab('9', 0, 6)); + $this->add(30, 46, Util::formatCnab('9', 0, 17, 2)); + $this->add(47, 52, Util::formatCnab('9', 0, 6)); + $this->add(53, 69, Util::formatCnab('9', 0, 17, 2)); + $this->add(70, 75, Util::formatCnab('9', 0, 6)); + $this->add(76, 92, Util::formatCnab('9', 0, 17, 2)); + $this->add(93, 98, Util::formatCnab('9', 0, 6)); + $this->add(99, 115, Util::formatCnab('9', 0, 17, 2)); + $this->add(116, 123, '00000000'); + $this->add(124, 240, ''); + + return $this; + } + + /** + * @return Btg + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); + $this->add(4, 7, '9999'); + $this->add(8, 8, '9'); + $this->add(9, 17, ''); + $this->add(18, 23, Util::formatCnab('9', 1, 6)); + $this->add(24, 29, Util::formatCnab('9', $this->getCount(), 6)); + $this->add(30, 35, '000000'); + $this->add(36, 240, ''); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Caixa.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Caixa.php index f7932b5c..ce5e7227 100644 --- a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Caixa.php +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Caixa.php @@ -1,23 +1,16 @@ segmentoP($boleto); $this->segmentoQ($boleto); $this->segmentoR($boleto); + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -140,7 +132,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(16, 17, self::OCORRENCIA_ALT_OUTROS_DADOS); } $this->add(18, 22, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(23, 23, CalculoDV::cefAgencia($this->getAgencia())); + $this->add(23, 23, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::cefAgencia($this->getAgencia())); if (strlen($this->getCodigoCliente()) == 7) { $this->add(24, 30, Util::formatCnab('9', $this->getCodigoCliente(), 7)); $this->add(31, 37, '0000000'); @@ -165,7 +157,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(109, 109, Util::formatCnab('9', $boleto->getAceite(), 1)); $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); $this->add(118, 118, $boleto->getJuros() ? '2' : '3'); //'2' = Percentual Mensal '3' = Isento - $this->add(119, 126, $boleto->getDataVencimento()->copy()->addDays($boleto->getJurosApos() === false ? 1 : (int)$boleto->getJurosApos())->format('dmY')); + $this->add(119, 126, $boleto->getDataVencimento()->copy()->addDays($boleto->getJurosApos() === false ? 1 : (int) $boleto->getJurosApos())->format('dmY')); $this->add(127, 141, Util::formatCnab('9', $boleto->getJuros(), 15, 2)); //Taxa mensal $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); // 0 = Sem Desconto, 1 = Valor Fixo até a data informada, 2 = Percentual até a data informada $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); @@ -190,8 +182,8 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -243,8 +235,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ public function segmentoR(BoletoContract $boleto) { @@ -277,8 +269,8 @@ public function segmentoR(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function header() { @@ -295,7 +287,7 @@ protected function header() $this->add(19, 32, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); $this->add(33, 52, Util::formatCnab('9', 0, 20)); $this->add(53, 57, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(58, 58, CalculoDV::cefAgencia($this->getAgencia())); + $this->add(58, 58, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::cefAgencia($this->getAgencia())); if (strlen($this->getCodigoCliente()) == 7) { $this->add(59, 65, Util::formatCnab('9', $this->getCodigoCliente(), 7)); $this->add(66, 72, '0000000'); @@ -316,12 +308,13 @@ protected function header() $this->add(192, 211, Util::formatCnab('X', 'REMESSA-PRODUCAO', 20)); $this->add(212, 215, ''); $this->add(216, 240, ''); + return $this; } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function headerLote() { @@ -348,7 +341,7 @@ protected function headerLote() $this->add(40, 53, Util::formatCnab('9', 0, 14)); } $this->add(54, 58, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(59, 59, CalculoDV::cefAgencia($this->getAgencia())); + $this->add(59, 59, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::cefAgencia($this->getAgencia())); if (strlen($this->getCodigoCliente()) == 7) { $this->add(60, 65, '000000'); } else { @@ -367,8 +360,8 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function trailerLote() { @@ -396,8 +389,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Caixa + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Itau.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Itau.php index 69903496..91a297c8 100644 --- a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Itau.php +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Itau.php @@ -1,15 +1,13 @@ getPixQrCode()) { $this->segmentoJ52Pix($boleto); } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ public function segmentoJ(BoletoContract $boleto) { @@ -119,8 +116,8 @@ public function segmentoJ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ public function segmentoJ52(BoletoContract $boleto) { @@ -155,8 +152,8 @@ public function segmentoJ52(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ public function segmentoJ52Pix(BoletoContract $boleto) { @@ -181,8 +178,8 @@ public function segmentoJ52Pix(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function header() { @@ -191,7 +188,6 @@ protected function header() /** * HEADER DE ARQUIVO */ - $this->add(1, 3, Util::onlyNumbers($this->getCodigoBanco())); $this->add(4, 7, '0000'); $this->add(8, 8, '0'); @@ -220,8 +216,8 @@ protected function header() } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function headerLote() { @@ -262,14 +258,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -287,8 +283,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Itau + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Santander.php b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Santander.php index 62083ffb..ab8c7621 100644 --- a/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Santander.php +++ b/src/Cnab/Remessa/Cnab240/Pagamento/Banco/Santander.php @@ -1,25 +1,13 @@ carteira = 'A'; + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -91,17 +84,18 @@ public function addBoleto(BoletoContract $boleto) $this->segmentoP($boleto); $this->segmentoQ($boleto); $this->segmentoR($boleto); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->segmentoY01($boleto); } + return $this; } /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function segmentoP(BoletoContract $boleto) { @@ -140,7 +134,7 @@ protected function segmentoP(BoletoContract $boleto) $this->add(110, 117, $boleto->getDataDocumento()->format('dmY')); $this->add(118, 118, $boleto->getJuros() ? '1' : '3'); //'1' = Valor por Dia, '3' = Isento $this->add(119, 126, $boleto->getJurosApos() == 0 ? '00000000' : - $boleto->getDataVencimentoApos()->format('dmY')); + $boleto->getDataVencimentoApos()->format('dmY')); $this->add(127, 141, Util::formatCnab('9', $boleto->getMoraDia(), 15, 2)); //Valor da mora/dia ou Taxa mensal $this->add(142, 142, $boleto->getDesconto() > 0 ? '1' : '0'); $this->add(143, 150, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmY') : '00000000'); @@ -165,12 +159,12 @@ protected function segmentoP(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function segmentoR(BoletoContract $boleto) { - if (!$boleto->getMulta() > 0 && !$boleto->getDesconto() > 0) { + if (! $boleto->getMulta() > 0 && ! $boleto->getDesconto() > 0) { return $this; } @@ -225,7 +219,7 @@ protected function segmentoR(BoletoContract $boleto) $this->add(211, 215, Util::formatCnab('9', $this->getAgencia(), 5)); $this->add(216, 216, ''); $this->add(217, 228, Util::formatCnab('9', $this->getConta(), 12)); - $this->add(229, 229, Util::modulo11($this->getConta())); + $this->add(229, 229, Util::formatCnab('9', $this->getContaDv(), 1)); $this->add(230, 230, ''); $this->add(231, 231, ''); $this->add(232, 240, Util::formatCnab('X', '', 9)); @@ -236,8 +230,8 @@ protected function segmentoR(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ public function segmentoQ(BoletoContract $boleto) { @@ -277,7 +271,7 @@ public function segmentoQ(BoletoContract $boleto) $this->add(213, 232, ''); $this->add(233, 240, ''); - if($boleto->getSacadorAvalista()) { + if ($boleto->getSacadorAvalista()) { $this->add(154, 154, strlen(Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento())) == 14 ? 2 : 1); $this->add(155, 169, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 15)); $this->add(170, 209, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 30)); @@ -289,8 +283,8 @@ public function segmentoQ(BoletoContract $boleto) /** * @param BoletoContract $boleto * - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ public function segmentoY01(BoletoContract $boleto) { @@ -323,8 +317,8 @@ public function segmentoY01(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function header() { @@ -358,13 +352,12 @@ protected function header() $this->add(192, 211, ''); $this->add(212, 240, ''); - return $this; } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function headerLote() { @@ -400,14 +393,14 @@ protected function headerLote() } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function trailerLote() { $this->iniciaTrailerLote(); - $valor = array_reduce($this->boletos, function($valor, $boleto) { + $valor = array_reduce($this->boletos, function ($valor, $boleto) { return $valor + $boleto->getValor(); }, 0); @@ -431,8 +424,8 @@ protected function trailerLote() } /** - * @return $this - * @throws \Exception + * @return Sicredi + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/AbstractRemessa.php b/src/Cnab/Remessa/Cnab400/AbstractRemessa.php index d57de070..9f6e026a 100644 --- a/src/Cnab/Remessa/Cnab400/AbstractRemessa.php +++ b/src/Cnab/Remessa/Cnab400/AbstractRemessa.php @@ -1,8 +1,10 @@ isValid($messages)) { - throw new \Exception('Campos requeridos pelo banco, aparentam estar ausentes ' . $messages); + throw new ValidationException('Campos requeridos pelo banco, aparentam estar ausentes ' . $messages); } $stringRemessa = ''; if ($this->iRegistros < 1) { - throw new \Exception('Nenhuma linha detalhe foi adicionada'); + throw new ValidationException('Nenhuma linha detalhe foi adicionada'); } $this->header(); @@ -98,7 +100,6 @@ public function gerar() } else { $stringRemessa .= $this->valida($detalhe) . $this->fimLinha; } - } $this->trailer(); @@ -107,4 +108,3 @@ public function gerar() return Encoding::toUTF8($stringRemessa); } } - diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bancoob.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bancoob.php index 7e0026ed..a536952f 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bancoob.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bancoob.php @@ -1,18 +1,19 @@ add(10, 11, '01'); $this->add(12, 26, Util::formatCnab('X', 'COBRANÇA', 15)); $this->add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(31, 31, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(31, 31, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(32, 40, Util::formatCnab('9', $this->getConvenio(), 9)); $this->add(41, 46, ''); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); @@ -156,7 +156,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob $boleto * * @return Bancoob - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -171,9 +171,9 @@ public function addBoleto(BoletoContract $boleto) $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); $this->add(4, 17, Util::formatCnab('9L', $this->getBeneficiario()->getDocumento(), 14)); $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(22, 22, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(22, 22, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(23, 30, Util::formatCnab('9', $this->getConta(), 8)); - $this->add(31, 31, Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(31, 31, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(32, 37, '000000'); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle $this->add(63, 74, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); @@ -207,7 +207,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 142, $this->getCodigoBanco()); $this->add(143, 146, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(147, 147, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(147, 147, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(148, 149, isset($this->especie400[$boleto->getEspecieDocCodigo()]) ? $this->especie400[$boleto->getEspecieDocCodigo()] : '99'); $this->add(150, 150, ($boleto->getAceite() == 'N' ? '0' : '1')); @@ -221,7 +221,7 @@ public function addBoleto(BoletoContract $boleto) if (defined($const)) { $this->add(157, 158, constant($const)); } else { - throw new \Exception("A instrução para protesto em ".$boleto->getDiasProtesto()." dias não existe no banco."); + throw new ValidationException('A instrução para protesto em ' . $boleto->getDiasProtesto() . ' dias não existe no banco.'); } } $this->add(161, 166, Util::formatCnab('9', $boleto->getJuros(), 6, 4)); @@ -254,7 +254,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bancoob - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Banrisul.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Banrisul.php index a3c8f499..7924b04c 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Banrisul.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Banrisul.php @@ -1,12 +1,12 @@ teste = (boolean) $teste; + $this->teste = (bool) $teste; + return $this; } + /** * Retorna se é com registro. * @@ -146,6 +146,7 @@ public function isTeste() { return $this->teste; } + /** * Retorna o codigo do cliente. * @@ -169,6 +170,7 @@ public function setCodigoCliente($codigoCliente) return $this; } + /** * Retorna o codigo do cliente office banking. * @@ -195,7 +197,7 @@ public function setCodigoClienteOfficeBanking($officeBanking) /** * @return Banrisul - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -238,7 +240,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Banrisul $boleto * * @return Banrisul - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -263,7 +265,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { - throw new \Exception('Banrisul não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); + throw new ValidationException('Banrisul não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); @@ -293,10 +295,10 @@ public function addBoleto(BoletoContract $boleto) $this->add(162, 173, Util::formatCnab('9', $boleto->getMoraDia(), 12, 2)); $this->add(174, 192, ''); - if ($boleto->getDesconto() > 0) { - $this->add(174, 179, $boleto->getDataDesconto()->format('dmy')); - $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); - } + if ($boleto->getDesconto() > 0) { + $this->add(174, 179, $boleto->getDataDesconto()->format('dmy')); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + } $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); @@ -312,9 +314,9 @@ public function addBoleto(BoletoContract $boleto) $this->add(335, 349, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); $this->add(350, 351, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); - if ($this->isCarteiraRSX()){ + if ($this->isCarteiraRSX()) { $this->add(352, 371, ''); - }else{ + } else { $this->add(352, 355, ''); $this->add(356, 357, ''); $this->add(358, 369, ''); @@ -334,7 +336,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Banrisul - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bb.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bb.php index 3cdf05dc..71339b90 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bb.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bb.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco; +use VinicciusGuedes\LaravelCnab\Util; use VinicciusGuedes\LaravelCnab\CalculoDV; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\AbstractRemessa; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Remessa as RemessaContract; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Remessa as RemessaContract; class Bb extends AbstractRemessa implements RemessaContract { @@ -14,7 +15,6 @@ class Bb extends AbstractRemessa implements RemessaContract const TIPO_COBRANCA_VENDOR = '08VDR'; const TIPO_COBRANCA_VINCULADA = '02VIN'; const TIPO_COBRANCA_SIMPLES = ''; - const ESPECIE_DUPLICATA = '01'; const ESPECIE_NOTA_PROMISSORIA = '02'; const ESPECIE_NOTA_SEGURO = '03'; @@ -28,7 +28,6 @@ class Bb extends AbstractRemessa implements RemessaContract const ESPECIE_DIV_ATV_UNIAO = '25'; const ESPECIE_DIV_ATV_ESTADO = '26'; const ESPECIE_DIV_ATV_MUNICIPIO = '27'; - const OCORRENCIA_REMESSA = '01'; const OCORRENCIA_PEDIDO_BAIXA = '02'; const OCORRENCIA_PEDIDO_DEBITO = '03'; @@ -51,7 +50,6 @@ class Bb extends AbstractRemessa implements RemessaContract const OCORRENCIA_DISPENSAR_LIMITE_REC = '38'; const OCORRENCIA_ALT_LIMITE_REC = '39'; const OCORRENCIA_ALT_MODALIDADE = '40'; - const INSTRUCAO_SEM = '00'; const INSTRUCAO_COBRAR_JUROS = '01'; const INSTRUCAO_NAO_PROTESTAR = '07'; @@ -76,7 +74,6 @@ public function __construct(array $params = []) $this->addCampoObrigatorio('convenio', 'convenioLider'); } - /** * Código do banco * @@ -223,7 +220,7 @@ public function setTipoCobranca($tipoCobranca) /** * @return Bb - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -236,9 +233,9 @@ protected function header() $this->add(12, 19, Util::formatCnab('X', 'COBRANCA', 8)); $this->add(20, 26, ''); $this->add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(31, 31, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(31, 31, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(32, 39, Util::formatCnab('9', $this->getConta(), 8)); - $this->add(40, 40, $this->getContaDv() ?: CalculoDV::bbContaCorrente($this->getConta())); + $this->add(40, 40, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(41, 46, '000000'); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(77, 79, $this->getCodigoBanco()); @@ -257,7 +254,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb $boleto * * @return Bb - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -272,9 +269,9 @@ public function addBoleto(BoletoContract $boleto) $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); $this->add(4, 17, Util::formatCnab('9L', $this->getBeneficiario()->getDocumento(), 14)); $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(22, 22, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(22, 22, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(23, 30, Util::formatCnab('9', $this->getConta(), 8)); - $this->add(31, 31, $this->getContaDv() ?: CalculoDV::bbContaCorrente($this->getConta())); + $this->add(31, 31, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(32, 38, Util::formatCnab('9', $this->getConvenio(), 7)); $this->add(39, 63, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle $this->add(64, 80, $boleto->getNossoNumero()); @@ -361,7 +358,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bb - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bnb.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bnb.php index 3bf1034e..38e2d487 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bnb.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bnb.php @@ -1,11 +1,13 @@ getCarteira() == '21') { return '4'; } + return '1'; } /** * @return Bnb - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -93,7 +94,7 @@ protected function header() $this->add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(31, 32, '00'); $this->add(33, 39, Util::formatCnab('9', $this->getConta(), 7)); - $this->add(40, 40, $this->getContaDv() ?: CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(40, 40, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); $this->add(41, 46, ''); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(77, 79, $this->getCodigoBanco()); @@ -109,7 +110,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bnb $boleto * * @return Bnb - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -125,7 +126,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(22, 23, '00'); $this->add(24, 30, Util::formatCnab('9', $this->getConta(), 7)); - $this->add(31, 31, $this->getContaDv() ?: CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(31, 31, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); $this->add(32, 33, Util::formatCnab('9', round($boleto->getMulta()), 2)); // Só aceita números inteiros $this->add(34, 37, ''); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // Numero de controle @@ -188,7 +189,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bnb - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bradesco.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bradesco.php index 814ceb1c..82839e32 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bradesco.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Bradesco.php @@ -1,11 +1,13 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -70,7 +68,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['02', '04', '09', '28']; /** @@ -98,15 +95,15 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { if (empty($this->codigoCliente)) { $this->codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . - Util::formatCnab('9', $this->getAgencia(), 5) . - Util::formatCnab('9', $this->getConta(), 7) . - Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bradescoContaCorrente($this->getConta()), 1); + Util::formatCnab('9', $this->getAgencia(), 5) . + Util::formatCnab('9', $this->getConta(), 7) . + Util::formatCnab('9', ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bradescoContaCorrente($this->getConta()), 1); } return $this->codigoCliente; @@ -128,7 +125,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Bradesco - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -157,7 +154,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco $boleto * * @return Bradesco - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -243,7 +240,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bradesco - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/C6.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/C6.php new file mode 100644 index 00000000..aa758eac --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/C6.php @@ -0,0 +1,240 @@ +addCampoObrigatorio('idremessa', 'codigoCliente'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_C6; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = ['10', '20', '30', '40', '60']; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return C6 + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return C6 + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 20, Util::formatCnab('X', 'COBRANCA', 8)); + $this->add(21, 26, ''); + $this->add(27, 38, Util::formatCnab('9', $this->getCodigoCliente(), 12)); + $this->add(39, 46, ''); + $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, ''); + $this->add(95, 100, $this->getDataRemessa('dmy')); + $this->add(101, 108, ''); + $this->add(109, 120, Util::formatCnab('9', 0, 12)); + $this->add(121, 386, ''); + $this->add(387, 394, Util::formatCnab('9', $this->getIdremessa(), 8)); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco $boleto + * + * @return C6 + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); + $this->add(4, 17, Util::formatCnab('9L', $this->getBeneficiario()->getDocumento(), 14)); + $this->add(18, 29, Util::formatCnab('9', $this->getCodigoCliente(), 12)); + $this->add(30, 37, ''); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 74, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); + $this->add(75, 82, ''); + $this->add(83, 85, Util::formatCnab('9', $this->getCodigoBanco(), 3)); + $this->add(86, 106, ''); + $this->add(107, 108, Util::formatCnab('9', $this->getCarteira(), 2)); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 147, ''); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, $boleto->getAceite()); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, self::INSTRUCAO_SEM); + $this->add(159, 160, self::INSTRUCAO_SEM); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 198, $boleto->getMulta() > 0 ? $boleto->getDataVencimento()->format('dmy') : '000000'); + $this->add(199, 205, ''); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(315, 326, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 12)); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 349, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); + $this->add(350, 351, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(352, 381, ''); + if ($boleto->getSacadorAvalista()) { + $this->add(352, 381, Util::formatCnab('X', Util::onlyNumbers($boleto->getSacadorAvalista()->getNome()), 30)); + } + $this->add(382, 382, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(383, 384, Util::formatCnab('9', (int) ($boleto->getMulta() > 0 ? $boleto->getMulta() : 0), 2)); + $this->add(385, 385, ''); + $this->add(386, 391, $boleto->getDataVencimento()->copy()->addDays((int) $boleto->getJurosApos())->format('dmy')); + $this->add(392, 393, $boleto->getDiasProtesto('00')); + $this->add(394, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + + $msgs = array_filter($boleto->getDescricaoDemonstrativo()); + if (count($msgs) > 0) { + $this->iniciaDetalhe(); + $this->add(1, 1, '2'); + $this->add(2, 81, Util::formatCnab('X', Arr::get($msgs, 0), 80)); + $this->add(82, 161, Util::formatCnab('X', Arr::get($msgs, 1), 80)); + $this->add(162, 241, Util::formatCnab('X', Arr::get($msgs, 2), 80)); + $this->add(242, 321, Util::formatCnab('X', Arr::get($msgs, 3), 80)); + $this->add(322, 365, ''); + $this->add(366, 375, Util::formatCnab('9', substr($boleto->getNossoNumero(), 1, 10), 10)); + $this->add(376, 381, $boleto->getDataVencimento()->format('dmy')); + $this->add(382, 394, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + + return $this; + } + + /** + * @return C6 + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Caixa.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Caixa.php index d906a5bb..ecf2041a 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Caixa.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Caixa.php @@ -1,12 +1,14 @@ addCampoObrigatorio('codigoCliente', 'idremessa'); } - /** * Código do banco * @@ -94,6 +93,7 @@ public function getCarteiraNumero() if ($this->getCarteira() == 'SR') { return '02'; } + return '01'; } @@ -113,7 +113,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Caixa - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -148,7 +148,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Caixa $boleto * * @return Caixa - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -235,7 +235,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Caixa - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Cresol.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Cresol.php new file mode 100644 index 00000000..6822edf6 --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Cresol.php @@ -0,0 +1,244 @@ +addCampoObrigatorio('idremessa'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_CRESOL; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = ['09']; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + * @throws \Exception + */ + public function getCodigoCliente() + { + if (empty($this->codigoCliente)) { + $this->codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . + Util::formatCnab('9', $this->getAgencia(), 5) . + Util::formatCnab('9', $this->getConta(), 7) . + Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::cresolContaCorrente($this->getConta()), 1); + } + + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return Cresol + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return $this + * @throws \Exception + */ + protected function header() + { + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 26, Util::formatCnab('X', 'COBRANCA', 15)); + $this->add(27, 46, Util::formatCnab('9', $this->getCodigoCliente(), 20)); + // $this->add(47, 76, Util::formatCnab('X', '', 30)); + $this->add(47, 76, ''); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, Util::formatCnab('X', 'Cresol', 15)); + $this->add(95, 100, ''); + $this->add(101, 108, ''); + $this->add(109, 110, ''); + // $this->add(111, 117, Util::formatCnab('9', $this->getIdremessa(), 7)); + $this->add(110, 117, ''); + $this->add(118, 394, ''); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return $this + * @throws \Exception + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 6, ''); + $this->add(7, 7, ''); + $this->add(8, 12, ''); + $this->add(13, 19, ''); + $this->add(20, 20, ''); + $this->add(21, 21, '0'); + $this->add(22, 24, Util::formatCnab('9', $this->getCarteira(), 3)); + $this->add(25, 29, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(30, 36, Util::formatCnab('9', $this->getConta(), 7)); + $this->add(37, 37, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 65, ''); + $this->add(66, 66, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(67, 70, Util::formatCnab('9', $boleto->getMulta() > 0 ? $boleto->getMulta() : '0', 4, 2)); + $this->add(71, 82, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); + // 71 - 81 Identificação do Título no Banco -> Número Bancário para Cobrança Com e Sem Registro. + // 82 Dígito de Auto Conferência do Número Bancário -> digito N/N + $this->add(83, 92, ''); + $this->add(93, 93, '2'); // 1 = Banco emite e Processa o registro. 2 = Cliente emite e o Banco somente processa o registro + $this->add(94, 94, ''); // N= Não registra na cobrança. Diferente de N registra e emite Boleto. + $this->add(95, 104, ''); + $this->add(105, 105, ''); + $this->add(106, 106, ''); + $this->add(107, 108, ''); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 142, ''); + $this->add(143, 147, ''); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, ''); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, ''); + $this->add(159, 160, ''); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(315, 326, ''); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + + return $this; + } + + /** + * @return $this + * @throws \Exception + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Delbank.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Delbank.php index 34c4053d..be6313bc 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Delbank.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Delbank.php @@ -1,16 +1,16 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -45,7 +43,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['112', '121']; /** @@ -73,7 +70,7 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { @@ -96,7 +93,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Delbank - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -122,16 +119,16 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Delbank $boleto * * @return Delbank - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { $this->boletos[] = $boleto; - $this->iniciaDetalhe(); + $this->iniciaDetalhe(); $this->add(1, 1, '1'); $this->add(2, 3, '04'); - $this->add(4, 17, Util::onlyNumbers($this->getBeneficiario()->getDocumento()) ); + $this->add(4, 17, Util::onlyNumbers($this->getBeneficiario()->getDocumento())); $this->add(18, 37, Util::formatCnab('X', $this->getCodigoCliente(), 20)); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle $this->add(63, 73, Util::formatCnab('9', $boleto->getNossoNumero(), 11)); @@ -142,23 +139,23 @@ public function addBoleto(BoletoContract $boleto) $this->add(104, 105, Util::formatCnab('9', 0, 2)); $this->add(106, 107, ''); $this->add(108, 108, '1'); // CARTEIRA - if($boleto->getCarteira() == "121"){ - $this->add(108, 108, '6'); // CARTEIRA - } + if ($boleto->getCarteira() == '121') { + $this->add(108, 108, '6'); // CARTEIRA + } $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO - // BAIXA + // BAIXA if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); } - // ALTERAR VENCIMENTO + // ALTERAR VENCIMENTO if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); } - // ALTERAR DATA + // ALTERAR DATA if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); } @@ -201,13 +198,12 @@ public function addBoleto(BoletoContract $boleto) $this->add(386, 391, ''); $this->add(392, 393, ''); if ($boleto->getDiasProtesto() > 0) { - $this->add(392, 393, Util::formatCnab('9', Util::onlyNumbers($boleto->getDiasProtesto()), 2)); - } + $this->add(392, 393, Util::formatCnab('9', Util::onlyNumbers($boleto->getDiasProtesto()), 2)); + } $this->add(394, 394, ''); $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); - if (sizeof($boleto->getInstrucoes()) > 0) - { + if (sizeof($boleto->getInstrucoes()) > 0) { $this->iniciaDetalhe(); $this->add(1, 1, '2'); $this->add(2, 2, '0'); @@ -217,7 +213,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(210, 278, Util::formatCnab('X', $boleto->getInstrucoes()[3], 69)); $this->add(279, 347, Util::formatCnab('X', $boleto->getInstrucoes()[4], 69)); $this->add(348, 394, ''); - $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); } return $this; @@ -225,7 +221,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Delbank - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Fibra.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Fibra.php index 742f8ae3..71bb2925 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Fibra.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Fibra.php @@ -1,11 +1,12 @@ addCampoObrigatorio('codigoCliente'); } - /** * Código do banco * @@ -52,7 +50,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = false; /** @@ -80,7 +77,7 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { @@ -103,7 +100,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Fibra - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -129,7 +126,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Fibra $boleto * * @return Fibra - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -166,8 +163,8 @@ public function addBoleto(BoletoContract $boleto) $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 142, $this->getCodigoBanco()); - $this->add(143, 146, Util::formatCnab('9', 0, 4)); - $this->add(147, 147, Util::formatCnab('9', 0, 1)); + $this->add(143, 146, Util::formatCnab('9', 0, 4)); + $this->add(147, 147, Util::formatCnab('9', 0, 1)); $this->add(148, 149, $boleto->getEspecieDocCodigo()); $this->add(150, 150, $boleto->getAceite()); $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); @@ -211,7 +208,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Fibra - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Hsbc.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Hsbc.php index 05c2b894..0e83bcff 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Hsbc.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Hsbc.php @@ -1,10 +1,12 @@ addCampoObrigatorio('contaDv'); } - /** * Código do banco * @@ -108,7 +107,7 @@ public function getCarteiraNumero() /** * @return Hsbc - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -144,7 +143,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Hsbc $boleto * * @return Hsbc - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -177,7 +176,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { - throw new \Exception('HSBC não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); + throw new ValidationException('HSBC não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); @@ -233,7 +232,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Hsbc - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Inter.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Inter.php index e50849a5..bbb5dc30 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Inter.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Inter.php @@ -1,10 +1,12 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -29,7 +30,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['112']; /** @@ -48,7 +48,7 @@ public function __construct(array $params = []) /** * @return Inter - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -77,7 +77,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter $boleto * * @return Inter - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -145,7 +145,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Inter - * @throws \Exception + * @throws ValidationException */ protected function trailer() { @@ -160,14 +160,16 @@ protected function trailer() public function nomeSugerido() { -// CI400_001_???????.REM -// CI400 - Cobrança Inter -// 001 - Versão do layout -// ??????? - Número sequencial de remessa com sete caracteres (o mesmo número inserido no campo 111 a 117 do header do arquivo remesssa) -// .REM - Extensão do arquivo remessa - return sprintf( - 'CI400_001_%07s.REM', - $this->getIdremessa() - ); + // CI400_001_???????.REM + // CI400 - Cobrança Inter + // 001 - Versão do layout + // ??????? - Número sequencial de remessa com sete caracteres (o mesmo número inserido no campo 111 a 117 do header do arquivo remesssa) + // .REM - Extensão do arquivo remessa + return sprintf('CI400_001_%07s.REM', $this->getIdremessa()); + } + + public function save($path, $suggestName = true) + { + return parent::save($path, $suggestName); } } diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Itau.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Itau.php index 6d3dfa81..62f86869 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Itau.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Itau.php @@ -1,11 +1,13 @@ add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(31, 32, '00'); $this->add(33, 37, Util::formatCnab('9', $this->getConta(), 5)); - $this->add(38, 38, $this->getContaDv() ?: CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(38, 38, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); $this->add(39, 46, ''); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(77, 79, $this->getCodigoBanco()); @@ -167,7 +168,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau $boleto * * @return Itau - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -178,13 +179,15 @@ public function addBoleto(BoletoContract $boleto) $this->iniciaDetalhe(); } + $pix = $boleto->validarPix(); + $this->add(1, 1, '1'); $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); $this->add(4, 17, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(22, 23, '00'); $this->add(24, 28, Util::formatCnab('9', $this->getConta(), 5)); - $this->add(29, 29, $this->getContaDv() ?: CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(29, 29, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); $this->add(30, 33, ''); $this->add(34, 37, '0000'); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle @@ -193,7 +196,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(84, 86, Util::formatCnab('9', $this->getCarteiraNumero(), 3)); $this->add(87, 107, ''); $this->add(108, 108, 'I'); - $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + $this->add(109, 110, $pix ? self::OCORRENCIA_REMESSA_PIX : self::OCORRENCIA_REMESSA); // REGISTRO ou REGISTRO PIX if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA } @@ -258,12 +261,21 @@ public function addBoleto(BoletoContract $boleto) $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); } + if ($pix) { + $this->iniciaDetalhe(); + $this->add(1, 1, '3'); + $this->add(2, 78, Util::formatCnab('X', $boleto->getPixChave(), 77)); + $this->add(79, 142, Util::formatCnab('X', $boleto->getID(), 35)); + $this->add(143, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + return $this; } /** * @return Itau - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Ourinvest.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Ourinvest.php new file mode 100644 index 00000000..208c71b2 --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Ourinvest.php @@ -0,0 +1,206 @@ +addCampoObrigatorio('idremessa'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_OURINVEST; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = false; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * @return Ourinvest + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 26, Util::formatCnab('X', 'COBRANCA', 15)); + $this->add(27, 46, Util::formatCnab('9', $this->getConta(), 20)); + $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, Util::formatCnab('X', 'Banco Ourinvest', 15)); + $this->add(95, 100, $this->getDataRemessa('dmy')); + $this->add(101, 108, ''); + $this->add(109, 110, 'MX'); + $this->add(111, 117, Util::formatCnab('9', $this->getIdremessa(), 7)); + $this->add(118, 394, ''); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco $boleto + * + * @return Ourinvest + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 6, ''); + $this->add(7, 7, ''); + $this->add(8, 12, ''); + $this->add(13, 19, ''); + $this->add(20, 20, ''); + $this->add(21, 21, '0'); + $this->add(22, 24, Util::formatCnab('9', $this->getCarteira(), 3)); + $this->add(25, 29, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(30, 36, Util::formatCnab('9', $this->getConta(), 7)); + $this->add(37, 37, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::ourinvestConta($this->getConta())); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 65, '000'); + $this->add(66, 66, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(67, 70, Util::formatCnab('9', $boleto->getMulta() > 0 ? $boleto->getMulta() : '0', 4, 2)); + $this->add(71, 82, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); + $this->add(83, 92, Util::formatCnab('9', 0, 10, 2)); + $this->add(93, 93, $boleto->isEmissaoPropria() ? '2' : '1'); // 1 = Banco emite e Processa o registro. 2 = Cliente emite e o Banco somente processa o registro + $this->add(94, 94, ''); + $this->add(95, 104, ''); + $this->add(105, 108, ''); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 142, '000'); + $this->add(143, 147, '00000'); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, 'N'); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, self::INSTRUCAO_SEM); + $this->add(159, 160, self::INSTRUCAO_SEM); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(275, 312, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 38)); + $this->add(313, 324, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 12)); + $this->add(325, 326, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 394, Util::formatCnab('X', '', 60)); + if ($boleto->getSacadorAvalista()) { + $this->add(335, 348, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 14)); + $this->add(349, 350, Util::formatCnab('X', '', 2)); + $this->add(351, 394, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 44)); + } + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + if ($chaveNfe = $boleto->getChaveNfe()) { + $this->iniciaDetalhe(); + $this->add(1, 1, '2'); + $this->add(82, 125, Util::formatCnab('9', $chaveNfe, 44)); + $this->add(242, 321, Util::formatCnab('X', $boleto->getPagador()->getEmail(), 80)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + + return $this; + } + + /** + * @return Ourinvest + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } + + public function nomeSugerido() + { + //CBDDMM??.REM + //CB – Cobrança Ourinvest + //DD – O Dia geração do arquivo + //MM – O Mês da geração do Arquivo + //?? - variáveis alfanumérico-Numéricas Ex.: + //01, AB, A1 etc. + //.Rem – Extensão do arquivo. + return sprintf('CB%02s%02s01.REM', date('d'), date('m')); + } + + public function save($path, $suggestName = true) + { + return parent::save($path, $suggestName); + } +} diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Pine.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Pine.php index 5acdb014..58d0c742 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Pine.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Pine.php @@ -1,11 +1,12 @@ addCampoObrigatorio('codigoCliente'); } - /** * Código do banco * @@ -50,7 +48,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = [112, 110]; /** @@ -78,7 +75,7 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { @@ -101,7 +98,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Pine - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -127,7 +124,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine $boleto * * @return Pine - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -164,8 +161,8 @@ public function addBoleto(BoletoContract $boleto) $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 142, $this->getCodigoBanco()); - $this->add(143, 146, Util::formatCnab('9', 0, 4)); - $this->add(147, 147, Util::formatCnab('9', 0, 1)); + $this->add(143, 146, Util::formatCnab('9', 0, 4)); + $this->add(147, 147, Util::formatCnab('9', 0, 1)); $this->add(148, 149, $boleto->getEspecieDocCodigo()); $this->add(150, 150, $boleto->getAceite()); $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); @@ -203,7 +200,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Pine - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Rendimento.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Rendimento.php new file mode 100644 index 00000000..2f6be639 --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Rendimento.php @@ -0,0 +1,224 @@ +setCamposObrigatorios('agencia', 'beneficiario', 'codigoCliente'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_RENDIMENTO; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = false; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + * @throws ValidationException + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return Rendimento + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return Rendimento + * @throws ValidationException + */ + protected function header() + { + if (! Str::startsWith($this->getCodigoCliente(), $this->getAgencia())) { + $this->setCodigoCliente(Util::numberFormatGeral($this->getAgencia(), 4) . Util::numberFormatGeral($this->getCodigoCliente(), 10)); + } + + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 26, Util::formatCnab('X', 'COBRANCA', 15)); + $this->add(27, 46, Util::formatCnab('X', $this->getCodigoCliente(), 20)); + $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, Util::formatCnab('X', 'RENDIMENTO S.A', 15)); + $this->add(95, 100, $this->getDataRemessa('dmy')); + $this->add(101, 394, ''); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine $boleto + * + * @return Rendimento + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + if (! Str::startsWith($this->getCodigoCliente(), $this->getAgencia())) { + $this->setCodigoCliente(Util::numberFormatGeral($this->getAgencia(), 4) . Util::numberFormatGeral($this->getCodigoCliente(), 10)); + } + + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); + $this->add(4, 17, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); + $this->add(18, 37, Util::formatCnab('X', $this->getCodigoCliente(), 20)); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 73, Util::formatCnab('9', $boleto->getNossoNumero(), 11)); + $this->add(74, 86, Util::formatCnab('X', '', 11)); + $this->add(87, 89, Util::formatCnab('X', '', 3)); + $this->add(90, 90, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(91, 103, Util::formatCnab('9', $boleto->getMulta(), 13, 4)); + $this->add(104, 105, $boleto->getMulta() > 0 ? '01' : '00'); + $this->add(106, 107, ''); + $this->add(108, 108, Util::formatCnab('9', $boleto->getModalidadeCarteira(), 1)); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('9', $boleto->getNumero(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 142, $this->getCodigoBanco()); + $this->add(143, 146, Util::formatCnab('9', 0, 4)); + $this->add(147, 147, Util::formatCnab('9', 0, 1)); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, $boleto->getAceite()); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, self::INSTRUCAO_SEM); + $this->add(159, 160, self::INSTRUCAO_SEM); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 264, Util::formatCnab('X', $boleto->getPagador()->getNome(), 30)); + $this->add(265, 274, Util::formatCnab('X', '', 10)); + $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(315, 326, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 12)); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 349, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); + $this->add(350, 351, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(352, 381, Util::formatCnab('X', $boleto->getSacadorAvalista() ? $boleto->getSacadorAvalista()->getNome() : '', 30)); + $this->add(382, 385, Util::formatCnab('X', '', 3)); + $this->add(386, 391, Util::formatCnab('X', '', 6)); + $this->add(392, 393, Util::formatCnab('9', $boleto->getDiasProtesto('0'), 2)); + $this->add(394, 394, $boleto->getMoeda()); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + if ($chaveNfe = $boleto->getChaveNfe()) { + $this->iniciaDetalhe(); + $this->add(1, 1, '4'); + $this->add(38, 81, Util::formatCnab('9', $chaveNfe, 44)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + + return $this; + } + + /** + * @return Rendimento + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Santander.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Santander.php index 3df1dde1..f34658c4 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Santander.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Santander.php @@ -1,11 +1,13 @@ addCampoObrigatorio('codigoCliente'); } - /** * Código do banco * @@ -104,7 +103,7 @@ public function setCodigoCliente($codigoCliente) * Retorna o codigo de transmissão. * * @return string - * @throws \Exception + * @throws ValidationException */ public function getCodigoTransmissao() { @@ -127,7 +126,7 @@ public function getCodigoTransmissao() /** * @return Santander - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -155,7 +154,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Santander $boleto * * @return Santander - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -229,7 +228,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(352, 381, Util::formatCnab('X', $boleto->getSacadorAvalista() ? $boleto->getSacadorAvalista()->getNome() : '', 30)); $this->add(382, 382, ''); $this->add(383, 383, 'I'); - $this->add(384, 385, substr($this->getConta(), -1) . CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(384, 385, substr($this->getConta(), -1) . (! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta()))); if (strlen($this->getConta()) == 9) { $this->add(384, 385, substr($this->getConta(), -2)); } @@ -241,12 +240,36 @@ public function addBoleto(BoletoContract $boleto) $this->add(401, 444, Util::formatCnab('9', $chaveNfe, 44)); } + if ($boleto->validarPix()) { + $tipoChave = [ + $boleto::TIPO_CHAVEPIX_CPF => 1, + $boleto::TIPO_CHAVEPIX_CNPJ => 2, + $boleto::TIPO_CHAVEPIX_CELULAR => 3, + $boleto::TIPO_CHAVEPIX_EMAIL => 4, + $boleto::TIPO_CHAVEPIX_ALEATORIA => 5, + ]; + $this->iniciaDetalhe(); + $this->add(1, 1, '8'); + $this->add(2, 3, '00'); // '00' = Conforme Perfil do Beneficiário; '01' = Aceita qualquer valor; ‘02’ = Entre o mínimo e o máximo; ‘03’ = Não aceita pagamento com o valor divergente + $this->add(4, 5, '01'); // Quantidade de pagamentos + $this->add(6, 6, '2'); // '1' = % (percentual); '2' = valor + $this->add(7, 19, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(20, 24, Util::formatCnab('9', 200, 5, 2)); + $this->add(25, 37, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(38, 42, Util::formatCnab('9', 100, 5, 2)); + $this->add(43, 43, Util::formatCnab('9', $tipoChave[$boleto->getPixChaveTipo()], 1)); + $this->add(44, 120, Util::formatCnab('Z', $boleto->getPixChave(), 77)); + $this->add(121, 155, Util::formatCnab('X', $boleto->getID(), 35)); + $this->add(156, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + return $this; } /** * @return Santander - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Sicredi.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Sicredi.php index 758f2cea..bbeafb10 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Sicredi.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Sicredi.php @@ -1,11 +1,13 @@ carteira = 'A'; + return $this; } @@ -88,7 +89,7 @@ public function setCarteira($carteira) */ protected $codigoCliente; - /** + /** * Retorna o codigo do cliente. * * @return mixed @@ -114,7 +115,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Sicredi - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -144,12 +145,12 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Sicredi $boleto * * @return Sicredi - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { $this->boletos[] = $boleto; - if (!$boleto->isComRegistro()) { + if (! $boleto->isComRegistro()) { return $this; } @@ -248,7 +249,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Sicredi - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Unicred.php b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Unicred.php index 999c3927..847098ab 100644 --- a/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Unicred.php +++ b/src/Cnab/Remessa/Cnab400/Cobranca/Banco/Unicred.php @@ -1,11 +1,13 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -55,7 +54,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['21']; /** @@ -83,15 +81,15 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { if (empty($this->codigoCliente)) { $this->codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . - Util::formatCnab('9', $this->getAgencia(), 5) . - Util::formatCnab('9', $this->getConta(), 7) . - Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::unicredContaCorrente($this->getConta()), 1); + Util::formatCnab('9', $this->getAgencia(), 5) . + Util::formatCnab('9', $this->getConta(), 7) . + ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::unicredContaCorrente($this->getConta()); } return $this->codigoCliente; @@ -102,7 +100,7 @@ public function getCodigoCliente() * * @param mixed $codigoCliente * - * @return Bradesco + * @return Unicred */ public function setCodigoCliente($codigoCliente) { @@ -112,8 +110,8 @@ public function setCodigoCliente($codigoCliente) } /** - * @return $this - * @throws \Exception + * @return Unicred + * @throws ValidationException */ protected function header() { @@ -141,8 +139,8 @@ protected function header() /** * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Unicred $boleto * - * @return $this - * @throws \Exception + * @return Unicred + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -151,7 +149,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(1, 1, '1'); $this->add(2, 6, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(7, 7, CalculoDv::unicredAgencia($this->getAgencia()) ); + $this->add(7, 7, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::unicredAgencia($this->getAgencia())); $this->add(8, 19, Util::formatCnab('9', $this->getConta(), 12)); $this->add(20, 20, Util::formatCnab('9', $this->getContaDv(), 1)); $this->add(21, 21, '0'); @@ -170,25 +168,25 @@ public function addBoleto(BoletoContract $boleto) // ‘3’ = Isento // *OBSERVAÇÃO: // Para boletos com espécie 31 (Cartão de crédito): Deve ser '3' = Isento. - $this->add(94, 94, $boleto->getMulta() > 0 ? '2' : '3' ); //Código da multa 2 = TAXA (%) + $this->add(94, 94, $boleto->getMulta() > 0 ? '2' : '3'); //Código da multa 2 = TAXA (%) $this->add(95, 104, Util::formatCnab('9', $boleto->getMulta() > 0 ? $boleto->getMulta() : '0', 10, 2)); /** Código adotado pela FEBRABAN para identificação do tipo de pagamento de mora de juros. - Domínio: - ‘1’ = Valor Diário (R$) - ‘2’ = Taxa Mensal (%) - ‘3’= Valor Mensal (R$) * - ‘4’ = Taxa diária (%) - ‘5’ = Isento - **/ - $this->add(105, 105, (null!==$boleto->getMoraDia() && $boleto->getMoraDia()) > 0 ? '1' : '5' ); + * Domínio: + * ‘1’ = Valor Diário (R$) + * ‘2’ = Taxa Mensal (%) + * ‘3’= Valor Mensal (R$) * + * ‘4’ = Taxa diária (%) + * ‘5’ = Isento + **/ + $this->add(105, 105, (null !== $boleto->getMoraDia() && $boleto->getMoraDia()) > 0 ? '1' : '5'); /** Indica se o Título pode ou não ser utilizado como garantia de operação de desconto futura. - Domínio: - ‘S’ = Título selecionado para ser utilizado como garantia em uma operação de desconto - futura. - ‘N’ = Título NÃO selecionado para ser utilizado como garantia em uma operação de - desconto futura. - Default: ‘N’ - **/ + * Domínio: + * ‘S’ = Título selecionado para ser utilizado como garantia em uma operação de desconto + * futura. + * ‘N’ = Título NÃO selecionado para ser utilizado como garantia em uma operação de + * desconto futura. + * Default: ‘N’ + **/ $this->add(106, 106, 'N'); // Identificação de Título Descontável. $this->add(107, 108, ''); $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO @@ -205,56 +203,56 @@ public function addBoleto(BoletoContract $boleto) $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); } $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); - $this->add(121, 126, $boleto->getDataVencimento()->format('dmy'));//DDMMAA + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); //DDMMAA $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 149, '0000000000'); // Código adotado pela FEBRABAN para identificação do desconto. // Domínio: // 0 = Isento // 1 = Valor Fixo - $this->add(150, 150, $boleto->getDesconto() > 0 ? '1' : '0' ); //Código do desconto + $this->add(150, 150, $boleto->getDesconto() > 0 ? '1' : '0'); //Código do desconto $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); $this->add(157, 157, '0'); // $this->add(158, 158, self::INSTRUCAO_SEM); if ($boleto->getDiasProtesto() > 0) { - // Código adotado pela FEBRABAN para identificar o tipo de prazo a ser considerado para o protesto. - // Domínio: - // 1 = Protestar Dias Corridos - // 2 = Protestar Dias Úteis - // 3 = Não Protestar => PADRAO - $this->add(158, 158, self::INSTRUCAO_PROTESTAR_DIAS_UTEIS);//Código para Protesto + // Código adotado pela FEBRABAN para identificar o tipo de prazo a ser considerado para o protesto. + // Domínio: + // 1 = Protestar Dias Corridos + // 2 = Protestar Dias Úteis + // 3 = Não Protestar => PADRAO + $this->add(158, 158, self::INSTRUCAO_PROTESTAR_DIAS_UTEIS); //Código para Protesto $this->add(159, 160, Util::formatCnab('9', $boleto->getDiasProtesto(), 2)); } else { - $this->add(158, 158, self::INSTRUCAO_NAO_PROTESTAR);//Código para Protesto + $this->add(158, 158, self::INSTRUCAO_NAO_PROTESTAR); //Código para Protesto $this->add(159, 160, Util::formatCnab('9', 0, 2)); } $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); - $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto()>0?$boleto->getDesconto():'0', 13, 2)); - $this->add(193, 203, Util::formatCnab('9', $boleto->getNossoNumero(), 11));//Nosso Número na UNICRED - $this->add(204, 205, '00');//Valor do Abatimento a ser concedido - $this->add(206, 218, Util::formatCnab('9', 0, 13) );//Valor do Abatimento a ser concedido + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto() > 0 ? $boleto->getDesconto() : '0', 13, 2)); + $this->add(193, 203, Util::formatCnab('9', $boleto->getNossoNumero(), 11)); //Nosso Número na UNICRED + $this->add(204, 205, '00'); //Valor do Abatimento a ser concedido + $this->add(206, 218, Util::formatCnab('9', 0, 13)); //Valor do Abatimento a ser concedido // Tipo de inscrição do Pagador // 01 – CPF // 02 - CNPJ - $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01');//Identificação do Tipo de Inscrição do Pagador + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); //Identificação do Tipo de Inscrição do Pagador /** Quando se tratar de CNPJ, adotar o critério de preenchimento da direita para a esquerda,utilizando: - - 2 posições para o controle; - - 4 posições para a filial; - - 8 posições para o CNPJ. - Quando se tratar de CPF, adotar o mesmo critério da direita para a esquerda, utilizando: - - 2 posições para o controle; - - 9 posições para o CPF; - - 3 posições a esquerda zeradas. - **/ + * - 2 posições para o controle; + * - 4 posições para a filial; + * - 8 posições para o CNPJ. + * Quando se tratar de CPF, adotar o mesmo critério da direita para a esquerda, utilizando: + * - 2 posições para o controle; + * - 9 posições para o CPF; + * - 3 posições a esquerda zeradas. + **/ $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); $this->add(315, 326, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 12)); $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); $this->add(335, 354, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 20)); //Cidade Pagador - $this->add(355, 356, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2 )); //UF pagador + $this->add(355, 356, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); //UF pagador $this->add(357, 394, Util::formatCnab('X', $boleto->getSacadorAvalista() ? $boleto->getSacadorAvalista()->getNome() : '', 38)); $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); //No Sequencial do Registro @@ -262,8 +260,8 @@ public function addBoleto(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Unicred + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bancoob.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bancoob.php index 37b8a072..2c6cd762 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bancoob.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bancoob.php @@ -1,18 +1,19 @@ add(10, 11, '01'); $this->add(12, 26, Util::formatCnab('X', 'COBRANÇA', 15)); $this->add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(31, 31, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(31, 31, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(32, 40, Util::formatCnab('9', $this->getConvenio(), 9)); $this->add(41, 46, ''); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); @@ -156,7 +156,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bancoob $boleto * * @return Bancoob - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -171,9 +171,9 @@ public function addBoleto(BoletoContract $boleto) $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); $this->add(4, 17, Util::formatCnab('9L', $this->getBeneficiario()->getDocumento(), 14)); $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(22, 22, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(22, 22, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(23, 30, Util::formatCnab('9', $this->getConta(), 8)); - $this->add(31, 31, Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bancoobContaCorrente($this->getConta()), 1)); + $this->add(31, 31, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bancoobContaCorrente($this->getConta())); $this->add(32, 37, '000000'); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle $this->add(63, 74, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); @@ -207,7 +207,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 142, $this->getCodigoBanco()); $this->add(143, 146, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(147, 147, CalculoDv::bancoobAgencia($this->getAgencia())); + $this->add(147, 147, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bancoobAgencia($this->getAgencia())); $this->add(148, 149, isset($this->especie400[$boleto->getEspecieDocCodigo()]) ? $this->especie400[$boleto->getEspecieDocCodigo()] : '99'); $this->add(150, 150, ($boleto->getAceite() == 'N' ? '0' : '1')); @@ -221,7 +221,7 @@ public function addBoleto(BoletoContract $boleto) if (defined($const)) { $this->add(157, 158, constant($const)); } else { - throw new \Exception("A instrução para protesto em ".$boleto->getDiasProtesto()." dias não existe no banco."); + throw new ValidationException('A instrução para protesto em ' . $boleto->getDiasProtesto() . ' dias não existe no banco.'); } } $this->add(161, 166, Util::formatCnab('9', $boleto->getJuros(), 6, 4)); @@ -254,7 +254,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bancoob - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Banrisul.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Banrisul.php index 78569d03..2f4d86ec 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Banrisul.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Banrisul.php @@ -1,12 +1,12 @@ teste = (boolean) $teste; + $this->teste = (bool) $teste; + return $this; } + /** * Retorna se é com registro. * @@ -146,6 +146,7 @@ public function isTeste() { return $this->teste; } + /** * Retorna o codigo do cliente. * @@ -169,6 +170,7 @@ public function setCodigoCliente($codigoCliente) return $this; } + /** * Retorna o codigo do cliente office banking. * @@ -195,7 +197,7 @@ public function setCodigoClienteOfficeBanking($officeBanking) /** * @return Banrisul - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -238,7 +240,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Banrisul $boleto * * @return Banrisul - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -263,7 +265,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { - throw new \Exception('Banrisul não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); + throw new ValidationException('Banrisul não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); @@ -293,10 +295,10 @@ public function addBoleto(BoletoContract $boleto) $this->add(162, 173, Util::formatCnab('9', $boleto->getMoraDia(), 12, 2)); $this->add(174, 192, ''); - if ($boleto->getDesconto() > 0) { - $this->add(174, 179, $boleto->getDataDesconto()->format('dmy')); - $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); - } + if ($boleto->getDesconto() > 0) { + $this->add(174, 179, $boleto->getDataDesconto()->format('dmy')); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + } $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); @@ -312,9 +314,9 @@ public function addBoleto(BoletoContract $boleto) $this->add(335, 349, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); $this->add(350, 351, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); - if ($this->isCarteiraRSX()){ + if ($this->isCarteiraRSX()) { $this->add(352, 371, ''); - }else{ + } else { $this->add(352, 355, ''); $this->add(356, 357, ''); $this->add(358, 369, ''); @@ -334,7 +336,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Banrisul - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bb.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bb.php index 4cd9f06a..c36665da 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bb.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bb.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Pagamento\Banco; +use VinicciusGuedes\LaravelCnab\Util; use VinicciusGuedes\LaravelCnab\CalculoDV; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\AbstractRemessa; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Remessa as RemessaContract; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Remessa as RemessaContract; class Bb extends AbstractRemessa implements RemessaContract { @@ -14,7 +15,6 @@ class Bb extends AbstractRemessa implements RemessaContract const TIPO_COBRANCA_VENDOR = '08VDR'; const TIPO_COBRANCA_VINCULADA = '02VIN'; const TIPO_COBRANCA_SIMPLES = ''; - const ESPECIE_DUPLICATA = '01'; const ESPECIE_NOTA_PROMISSORIA = '02'; const ESPECIE_NOTA_SEGURO = '03'; @@ -28,7 +28,6 @@ class Bb extends AbstractRemessa implements RemessaContract const ESPECIE_DIV_ATV_UNIAO = '25'; const ESPECIE_DIV_ATV_ESTADO = '26'; const ESPECIE_DIV_ATV_MUNICIPIO = '27'; - const OCORRENCIA_REMESSA = '01'; const OCORRENCIA_PEDIDO_BAIXA = '02'; const OCORRENCIA_PEDIDO_DEBITO = '03'; @@ -51,7 +50,6 @@ class Bb extends AbstractRemessa implements RemessaContract const OCORRENCIA_DISPENSAR_LIMITE_REC = '38'; const OCORRENCIA_ALT_LIMITE_REC = '39'; const OCORRENCIA_ALT_MODALIDADE = '40'; - const INSTRUCAO_SEM = '00'; const INSTRUCAO_COBRAR_JUROS = '01'; const INSTRUCAO_NAO_PROTESTAR = '07'; @@ -76,7 +74,6 @@ public function __construct(array $params = []) $this->addCampoObrigatorio('convenio', 'convenioLider'); } - /** * Código do banco * @@ -223,7 +220,7 @@ public function setTipoCobranca($tipoCobranca) /** * @return Bb - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -236,9 +233,9 @@ protected function header() $this->add(12, 19, Util::formatCnab('X', 'COBRANCA', 8)); $this->add(20, 26, ''); $this->add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(31, 31, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(31, 31, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(32, 39, Util::formatCnab('9', $this->getConta(), 8)); - $this->add(40, 40, $this->getContaDv() ?: CalculoDV::bbContaCorrente($this->getConta())); + $this->add(40, 40, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(41, 46, '000000'); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(77, 79, $this->getCodigoBanco()); @@ -257,7 +254,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bb $boleto * * @return Bb - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -272,9 +269,9 @@ public function addBoleto(BoletoContract $boleto) $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); $this->add(4, 17, Util::formatCnab('9L', $this->getBeneficiario()->getDocumento(), 14)); $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); - $this->add(22, 22, CalculoDV::bbAgencia($this->getAgencia())); + $this->add(22, 22, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::bbAgencia($this->getAgencia())); $this->add(23, 30, Util::formatCnab('9', $this->getConta(), 8)); - $this->add(31, 31, $this->getContaDv() ?: CalculoDV::bbContaCorrente($this->getConta())); + $this->add(31, 31, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bbContaCorrente($this->getConta())); $this->add(32, 38, Util::formatCnab('9', $this->getConvenio(), 7)); $this->add(39, 63, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle $this->add(64, 80, $boleto->getNossoNumero()); @@ -361,7 +358,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bb - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bnb.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bnb.php index ca0962b5..2fac0df2 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bnb.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bnb.php @@ -1,11 +1,13 @@ getCarteira() == '21') { return '4'; } + return '1'; } /** * @return Bnb - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -93,7 +94,7 @@ protected function header() $this->add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(31, 32, '00'); $this->add(33, 39, Util::formatCnab('9', $this->getConta(), 7)); - $this->add(40, 40, $this->getContaDv() ?: CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(40, 40, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); $this->add(41, 46, ''); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(77, 79, $this->getCodigoBanco()); @@ -109,7 +110,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bnb $boleto * * @return Bnb - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -125,7 +126,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(22, 23, '00'); $this->add(24, 30, Util::formatCnab('9', $this->getConta(), 7)); - $this->add(31, 31, $this->getContaDv() ?: CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(31, 31, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bnbContaCorrente($this->getAgencia(), $this->getConta())); $this->add(32, 33, Util::formatCnab('9', round($boleto->getMulta()), 2)); // Só aceita números inteiros $this->add(34, 37, ''); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // Numero de controle @@ -188,7 +189,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bnb - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bradesco.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bradesco.php index 9edc241a..ec8edaa1 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bradesco.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Bradesco.php @@ -1,11 +1,13 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -70,7 +68,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['02', '04', '09', '28']; /** @@ -98,7 +95,7 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { @@ -106,7 +103,7 @@ public function getCodigoCliente() $this->codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . Util::formatCnab('9', $this->getAgencia(), 5) . Util::formatCnab('9', $this->getConta(), 7) . - Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::bradescoContaCorrente($this->getConta()), 1); + Util::formatCnab('9', ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::bradescoContaCorrente($this->getConta()), 1); } return $this->codigoCliente; @@ -128,7 +125,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Bradesco - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -157,7 +154,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco $boleto * * @return Bradesco - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -243,7 +240,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Bradesco - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/C6.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/C6.php new file mode 100644 index 00000000..0ea0ee07 --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/C6.php @@ -0,0 +1,240 @@ +addCampoObrigatorio('idremessa', 'codigoCliente'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_C6; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = ['10', '20', '30', '40', '60']; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return C6 + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return C6 + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 20, Util::formatCnab('X', 'COBRANCA', 8)); + $this->add(21, 26, ''); + $this->add(27, 38, Util::formatCnab('9', $this->getCodigoCliente(), 12)); + $this->add(39, 46, ''); + $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, ''); + $this->add(95, 100, $this->getDataRemessa('dmy')); + $this->add(101, 108, ''); + $this->add(109, 120, Util::formatCnab('9', 0, 12)); + $this->add(121, 386, ''); + $this->add(387, 394, Util::formatCnab('9', $this->getIdremessa(), 8)); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco $boleto + * + * @return C6 + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); + $this->add(4, 17, Util::formatCnab('9L', $this->getBeneficiario()->getDocumento(), 14)); + $this->add(18, 29, Util::formatCnab('9', $this->getCodigoCliente(), 12)); + $this->add(30, 37, ''); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 74, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); + $this->add(75, 82, ''); + $this->add(83, 85, Util::formatCnab('9', $this->getCodigoBanco(), 3)); + $this->add(86, 106, ''); + $this->add(107, 108, Util::formatCnab('9', $this->getCarteira(), 2)); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 147, ''); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, $boleto->getAceite()); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, self::INSTRUCAO_SEM); + $this->add(159, 160, self::INSTRUCAO_SEM); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 198, $boleto->getMulta() > 0 ? $boleto->getDataVencimento()->format('dmy') : '000000'); + $this->add(199, 205, ''); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(315, 326, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 12)); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 349, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); + $this->add(350, 351, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(352, 381, ''); + if ($boleto->getSacadorAvalista()) { + $this->add(352, 381, Util::formatCnab('X', Util::onlyNumbers($boleto->getSacadorAvalista()->getNome()), 30)); + } + $this->add(382, 382, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(383, 384, Util::formatCnab('9', (int) ($boleto->getMulta() > 0 ? $boleto->getMulta() : 0), 2)); + $this->add(385, 385, ''); + $this->add(386, 391, $boleto->getDataVencimento()->copy()->addDays((int) $boleto->getJurosApos())->format('dmy')); + $this->add(392, 393, $boleto->getDiasProtesto('00')); + $this->add(394, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + + $msgs = array_filter($boleto->getDescricaoDemonstrativo()); + if (count($msgs) > 0) { + $this->iniciaDetalhe(); + $this->add(1, 1, '2'); + $this->add(2, 81, Util::formatCnab('X', Arr::get($msgs, 0), 80)); + $this->add(82, 161, Util::formatCnab('X', Arr::get($msgs, 1), 80)); + $this->add(162, 241, Util::formatCnab('X', Arr::get($msgs, 2), 80)); + $this->add(242, 321, Util::formatCnab('X', Arr::get($msgs, 3), 80)); + $this->add(322, 365, ''); + $this->add(366, 375, Util::formatCnab('9', substr($boleto->getNossoNumero(), 1, 10), 10)); + $this->add(376, 381, $boleto->getDataVencimento()->format('dmy')); + $this->add(382, 394, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + + return $this; + } + + /** + * @return C6 + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Caixa.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Caixa.php index 6bc0f23d..e770a852 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Caixa.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Caixa.php @@ -1,12 +1,14 @@ addCampoObrigatorio('codigoCliente', 'idremessa'); } - /** * Código do banco * @@ -94,6 +93,7 @@ public function getCarteiraNumero() if ($this->getCarteira() == 'SR') { return '02'; } + return '01'; } @@ -113,7 +113,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Caixa - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -148,7 +148,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Caixa $boleto * * @return Caixa - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -235,7 +235,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Caixa - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Cresol.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Cresol.php new file mode 100644 index 00000000..b4f5a2ac --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Cresol.php @@ -0,0 +1,244 @@ +addCampoObrigatorio('idremessa'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_CRESOL; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = ['09']; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + * @throws \Exception + */ + public function getCodigoCliente() + { + if (empty($this->codigoCliente)) { + $this->codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . + Util::formatCnab('9', $this->getAgencia(), 5) . + Util::formatCnab('9', $this->getConta(), 7) . + Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::cresolContaCorrente($this->getConta()), 1); + } + + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return Cresol + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return $this + * @throws \Exception + */ + protected function header() + { + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 26, Util::formatCnab('X', 'COBRANCA', 15)); + $this->add(27, 46, Util::formatCnab('9', $this->getCodigoCliente(), 20)); + // $this->add(47, 76, Util::formatCnab('X', '', 30)); + $this->add(47, 76, ''); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, Util::formatCnab('X', 'Cresol', 15)); + $this->add(95, 100, ''); + $this->add(101, 108, ''); + $this->add(109, 110, ''); + // $this->add(111, 117, Util::formatCnab('9', $this->getIdremessa(), 7)); + $this->add(110, 117, ''); + $this->add(118, 394, ''); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param BoletoContract $boleto + * + * @return $this + * @throws \Exception + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 6, ''); + $this->add(7, 7, ''); + $this->add(8, 12, ''); + $this->add(13, 19, ''); + $this->add(20, 20, ''); + $this->add(21, 21, '0'); + $this->add(22, 24, Util::formatCnab('9', $this->getCarteira(), 3)); + $this->add(25, 29, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(30, 36, Util::formatCnab('9', $this->getConta(), 7)); + $this->add(37, 37, Util::formatCnab('9', $this->getContaDv(), 1)); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 65, ''); + $this->add(66, 66, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(67, 70, Util::formatCnab('9', $boleto->getMulta() > 0 ? $boleto->getMulta() : '0', 4, 2)); + $this->add(71, 82, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); + // 71 - 81 Identificação do Título no Banco -> Número Bancário para Cobrança Com e Sem Registro. + // 82 Dígito de Auto Conferência do Número Bancário -> digito N/N + $this->add(83, 92, ''); + $this->add(93, 93, '2'); // 1 = Banco emite e Processa o registro. 2 = Cliente emite e o Banco somente processa o registro + $this->add(94, 94, ''); // N= Não registra na cobrança. Diferente de N registra e emite Boleto. + $this->add(95, 104, ''); + $this->add(105, 105, ''); + $this->add(106, 106, ''); + $this->add(107, 108, ''); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 142, ''); + $this->add(143, 147, ''); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, ''); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, ''); + $this->add(159, 160, ''); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(315, 326, ''); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + + return $this; + } + + /** + * @return $this + * @throws \Exception + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Delbank.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Delbank.php index 4714bc3e..8a7fa4b0 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Delbank.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Delbank.php @@ -1,16 +1,16 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -45,7 +43,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['112', '121']; /** @@ -73,7 +70,7 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { @@ -96,7 +93,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Delbank - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -122,16 +119,16 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Delbank $boleto * * @return Delbank - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { $this->boletos[] = $boleto; - $this->iniciaDetalhe(); + $this->iniciaDetalhe(); $this->add(1, 1, '1'); $this->add(2, 3, '04'); - $this->add(4, 17, Util::onlyNumbers($this->getBeneficiario()->getDocumento()) ); + $this->add(4, 17, Util::onlyNumbers($this->getBeneficiario()->getDocumento())); $this->add(18, 37, Util::formatCnab('X', $this->getCodigoCliente(), 20)); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle $this->add(63, 73, Util::formatCnab('9', $boleto->getNossoNumero(), 11)); @@ -142,23 +139,23 @@ public function addBoleto(BoletoContract $boleto) $this->add(104, 105, Util::formatCnab('9', 0, 2)); $this->add(106, 107, ''); $this->add(108, 108, '1'); // CARTEIRA - if($boleto->getCarteira() == "121"){ - $this->add(108, 108, '6'); // CARTEIRA - } + if ($boleto->getCarteira() == '121') { + $this->add(108, 108, '6'); // CARTEIRA + } $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO - // BAIXA + // BAIXA if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); } - // ALTERAR VENCIMENTO + // ALTERAR VENCIMENTO if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); } - // ALTERAR DATA + // ALTERAR DATA if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); } @@ -201,13 +198,12 @@ public function addBoleto(BoletoContract $boleto) $this->add(386, 391, ''); $this->add(392, 393, ''); if ($boleto->getDiasProtesto() > 0) { - $this->add(392, 393, Util::formatCnab('9', Util::onlyNumbers($boleto->getDiasProtesto()), 2)); - } + $this->add(392, 393, Util::formatCnab('9', Util::onlyNumbers($boleto->getDiasProtesto()), 2)); + } $this->add(394, 394, ''); $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); - if (sizeof($boleto->getInstrucoes()) > 0) - { + if (sizeof($boleto->getInstrucoes()) > 0) { $this->iniciaDetalhe(); $this->add(1, 1, '2'); $this->add(2, 2, '0'); @@ -217,7 +213,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(210, 278, Util::formatCnab('X', $boleto->getInstrucoes()[3], 69)); $this->add(279, 347, Util::formatCnab('X', $boleto->getInstrucoes()[4], 69)); $this->add(348, 394, ''); - $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); } return $this; @@ -225,7 +221,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Delbank - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Fibra.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Fibra.php index 599e1b94..df912ec3 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Fibra.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Fibra.php @@ -1,11 +1,12 @@ addCampoObrigatorio('codigoCliente'); } - /** * Código do banco * @@ -52,7 +50,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = false; /** @@ -80,7 +77,7 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { @@ -103,7 +100,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Fibra - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -129,7 +126,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Fibra $boleto * * @return Fibra - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -166,8 +163,8 @@ public function addBoleto(BoletoContract $boleto) $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 142, $this->getCodigoBanco()); - $this->add(143, 146, Util::formatCnab('9', 0, 4)); - $this->add(147, 147, Util::formatCnab('9', 0, 1)); + $this->add(143, 146, Util::formatCnab('9', 0, 4)); + $this->add(147, 147, Util::formatCnab('9', 0, 1)); $this->add(148, 149, $boleto->getEspecieDocCodigo()); $this->add(150, 150, $boleto->getAceite()); $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); @@ -211,7 +208,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Fibra - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Hsbc.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Hsbc.php index c03e6df0..aa585088 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Hsbc.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Hsbc.php @@ -1,10 +1,12 @@ addCampoObrigatorio('contaDv'); } - /** * Código do banco * @@ -108,7 +107,7 @@ public function getCarteiraNumero() /** * @return Hsbc - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -144,7 +143,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Hsbc $boleto * * @return Hsbc - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -177,7 +176,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { - throw new \Exception('HSBC não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); + throw new ValidationException('HSBC não suporta alteração geral, use o comando `comandarInstrucao` no boleto para enviar uma solicitação especifica'); } if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); @@ -233,7 +232,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Hsbc - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Inter.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Inter.php index 857b3184..f3dea91f 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Inter.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Inter.php @@ -1,10 +1,12 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -29,7 +30,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['112']; /** @@ -48,7 +48,7 @@ public function __construct(array $params = []) /** * @return Inter - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -77,7 +77,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Inter $boleto * * @return Inter - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -145,7 +145,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Inter - * @throws \Exception + * @throws ValidationException */ protected function trailer() { @@ -160,14 +160,16 @@ protected function trailer() public function nomeSugerido() { -// CI400_001_???????.REM -// CI400 - Cobrança Inter -// 001 - Versão do layout -// ??????? - Número sequencial de remessa com sete caracteres (o mesmo número inserido no campo 111 a 117 do header do arquivo remesssa) -// .REM - Extensão do arquivo remessa - return sprintf( - 'CI400_001_%07s.REM', - $this->getIdremessa() - ); + // CI400_001_???????.REM + // CI400 - Cobrança Inter + // 001 - Versão do layout + // ??????? - Número sequencial de remessa com sete caracteres (o mesmo número inserido no campo 111 a 117 do header do arquivo remesssa) + // .REM - Extensão do arquivo remessa + return sprintf('CI400_001_%07s.REM', $this->getIdremessa()); + } + + public function save($path, $suggestName = true) + { + return parent::save($path, $suggestName); } } diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Itau.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Itau.php index ea30cf06..0018eb84 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Itau.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Itau.php @@ -1,11 +1,13 @@ add(27, 30, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(31, 32, '00'); $this->add(33, 37, Util::formatCnab('9', $this->getConta(), 5)); - $this->add(38, 38, $this->getContaDv() ?: CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(38, 38, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); $this->add(39, 46, ''); $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); $this->add(77, 79, $this->getCodigoBanco()); @@ -167,7 +168,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Itau $boleto * * @return Itau - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -178,13 +179,15 @@ public function addBoleto(BoletoContract $boleto) $this->iniciaDetalhe(); } + $pix = $boleto->validarPix(); + $this->add(1, 1, '1'); $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); $this->add(4, 17, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); $this->add(18, 21, Util::formatCnab('9', $this->getAgencia(), 4)); $this->add(22, 23, '00'); $this->add(24, 28, Util::formatCnab('9', $this->getConta(), 5)); - $this->add(29, 29, $this->getContaDv() ?: CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(29, 29, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::itauContaCorrente($this->getAgencia(), $this->getConta())); $this->add(30, 33, ''); $this->add(34, 37, '0000'); $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle @@ -193,7 +196,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(84, 86, Util::formatCnab('9', $this->getCarteiraNumero(), 3)); $this->add(87, 107, ''); $this->add(108, 108, 'I'); - $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + $this->add(109, 110, $pix ? self::OCORRENCIA_REMESSA_PIX : self::OCORRENCIA_REMESSA); // REGISTRO ou REGISTRO PIX if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA } @@ -258,12 +261,21 @@ public function addBoleto(BoletoContract $boleto) $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); } + if ($pix) { + $this->iniciaDetalhe(); + $this->add(1, 1, '3'); + $this->add(2, 78, Util::formatCnab('X', $boleto->getPixChave(), 77)); + $this->add(79, 142, Util::formatCnab('X', $boleto->getID(), 35)); + $this->add(143, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + return $this; } /** * @return Itau - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Ourinvest.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Ourinvest.php new file mode 100644 index 00000000..65890c17 --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Ourinvest.php @@ -0,0 +1,206 @@ +addCampoObrigatorio('idremessa'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_OURINVEST; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = false; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * @return Ourinvest + * @throws ValidationException + */ + protected function header() + { + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 26, Util::formatCnab('X', 'COBRANCA', 15)); + $this->add(27, 46, Util::formatCnab('9', $this->getConta(), 20)); + $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, Util::formatCnab('X', 'Banco Ourinvest', 15)); + $this->add(95, 100, $this->getDataRemessa('dmy')); + $this->add(101, 108, ''); + $this->add(109, 110, 'MX'); + $this->add(111, 117, Util::formatCnab('9', $this->getIdremessa(), 7)); + $this->add(118, 394, ''); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Bradesco $boleto + * + * @return Ourinvest + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 6, ''); + $this->add(7, 7, ''); + $this->add(8, 12, ''); + $this->add(13, 19, ''); + $this->add(20, 20, ''); + $this->add(21, 21, '0'); + $this->add(22, 24, Util::formatCnab('9', $this->getCarteira(), 3)); + $this->add(25, 29, Util::formatCnab('9', $this->getAgencia(), 5)); + $this->add(30, 36, Util::formatCnab('9', $this->getConta(), 7)); + $this->add(37, 37, ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::ourinvestConta($this->getConta())); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 65, '000'); + $this->add(66, 66, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(67, 70, Util::formatCnab('9', $boleto->getMulta() > 0 ? $boleto->getMulta() : '0', 4, 2)); + $this->add(71, 82, Util::formatCnab('9', $boleto->getNossoNumero(), 12)); + $this->add(83, 92, Util::formatCnab('9', 0, 10, 2)); + $this->add(93, 93, $boleto->isEmissaoPropria() ? '2' : '1'); // 1 = Banco emite e Processa o registro. 2 = Cliente emite e o Banco somente processa o registro + $this->add(94, 94, ''); + $this->add(95, 104, ''); + $this->add(105, 108, ''); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 142, '000'); + $this->add(143, 147, '00000'); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, 'N'); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, self::INSTRUCAO_SEM); + $this->add(159, 160, self::INSTRUCAO_SEM); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); + $this->add(275, 312, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 38)); + $this->add(313, 324, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 12)); + $this->add(325, 326, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 394, Util::formatCnab('X', '', 60)); + if ($boleto->getSacadorAvalista()) { + $this->add(335, 348, Util::formatCnab('9', Util::onlyNumbers($boleto->getSacadorAvalista()->getDocumento()), 14)); + $this->add(349, 350, Util::formatCnab('X', '', 2)); + $this->add(351, 394, Util::formatCnab('X', $boleto->getSacadorAvalista()->getNome(), 44)); + } + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + if ($chaveNfe = $boleto->getChaveNfe()) { + $this->iniciaDetalhe(); + $this->add(1, 1, '2'); + $this->add(82, 125, Util::formatCnab('9', $chaveNfe, 44)); + $this->add(242, 321, Util::formatCnab('X', $boleto->getPagador()->getEmail(), 80)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + + return $this; + } + + /** + * @return Ourinvest + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } + + public function nomeSugerido() + { + //CBDDMM??.REM + //CB – Cobrança Ourinvest + //DD – O Dia geração do arquivo + //MM – O Mês da geração do Arquivo + //?? - variáveis alfanumérico-Numéricas Ex.: + //01, AB, A1 etc. + //.Rem – Extensão do arquivo. + return sprintf('CB%02s%02s01.REM', date('d'), date('m')); + } + + public function save($path, $suggestName = true) + { + return parent::save($path, $suggestName); + } +} diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Pine.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Pine.php index 65560112..449d4ce7 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Pine.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Pine.php @@ -1,11 +1,12 @@ addCampoObrigatorio('codigoCliente'); } - /** * Código do banco * @@ -50,7 +48,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = [112, 110]; /** @@ -78,7 +75,7 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { @@ -101,7 +98,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Pine - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -127,7 +124,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine $boleto * * @return Pine - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -164,8 +161,8 @@ public function addBoleto(BoletoContract $boleto) $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 142, $this->getCodigoBanco()); - $this->add(143, 146, Util::formatCnab('9', 0, 4)); - $this->add(147, 147, Util::formatCnab('9', 0, 1)); + $this->add(143, 146, Util::formatCnab('9', 0, 4)); + $this->add(147, 147, Util::formatCnab('9', 0, 1)); $this->add(148, 149, $boleto->getEspecieDocCodigo()); $this->add(150, 150, $boleto->getAceite()); $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); @@ -203,7 +200,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Pine - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Rendimento.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Rendimento.php new file mode 100644 index 00000000..3f4698e0 --- /dev/null +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Rendimento.php @@ -0,0 +1,224 @@ +setCamposObrigatorios('agencia', 'beneficiario', 'codigoCliente'); + } + + /** + * Código do banco + * + * @var string + */ + protected $codigoBanco = BoletoContract::COD_BANCO_RENDIMENTO; + + /** + * Define as carteiras disponíveis para cada banco + * + * @var array + */ + protected $carteiras = false; + + /** + * Caracter de fim de linha + * + * @var string + */ + protected $fimLinha = "\r\n"; + + /** + * Caracter de fim de arquivo + * + * @var null + */ + protected $fimArquivo = "\r\n"; + + /** + * Codigo do cliente junto ao banco. + * + * @var string + */ + protected $codigoCliente; + + /** + * Retorna o codigo do cliente. + * + * @return mixed + * @throws ValidationException + */ + public function getCodigoCliente() + { + return $this->codigoCliente; + } + + /** + * Seta o codigo do cliente. + * + * @param mixed $codigoCliente + * + * @return Rendimento + */ + public function setCodigoCliente($codigoCliente) + { + $this->codigoCliente = $codigoCliente; + + return $this; + } + + /** + * @return Rendimento + * @throws ValidationException + */ + protected function header() + { + if (! Str::startsWith($this->getCodigoCliente(), $this->getAgencia())) { + $this->setCodigoCliente(Util::numberFormatGeral($this->getAgencia(), 4) . Util::numberFormatGeral($this->getCodigoCliente(), 10)); + } + + $this->iniciaHeader(); + + $this->add(1, 1, '0'); + $this->add(2, 2, '1'); + $this->add(3, 9, 'REMESSA'); + $this->add(10, 11, '01'); + $this->add(12, 26, Util::formatCnab('X', 'COBRANCA', 15)); + $this->add(27, 46, Util::formatCnab('X', $this->getCodigoCliente(), 20)); + $this->add(47, 76, Util::formatCnab('X', $this->getBeneficiario()->getNome(), 30)); + $this->add(77, 79, $this->getCodigoBanco()); + $this->add(80, 94, Util::formatCnab('X', 'RENDIMENTO S.A', 15)); + $this->add(95, 100, $this->getDataRemessa('dmy')); + $this->add(101, 394, ''); + $this->add(395, 400, Util::formatCnab('9', 1, 6)); + + return $this; + } + + /** + * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Pine $boleto + * + * @return Rendimento + * @throws ValidationException + */ + public function addBoleto(BoletoContract $boleto) + { + if (! Str::startsWith($this->getCodigoCliente(), $this->getAgencia())) { + $this->setCodigoCliente(Util::numberFormatGeral($this->getAgencia(), 4) . Util::numberFormatGeral($this->getCodigoCliente(), 10)); + } + + $this->boletos[] = $boleto; + $this->iniciaDetalhe(); + + $this->add(1, 1, '1'); + $this->add(2, 3, strlen(Util::onlyNumbers($this->getBeneficiario()->getDocumento())) == 14 ? '02' : '01'); + $this->add(4, 17, Util::formatCnab('9', Util::onlyNumbers($this->getBeneficiario()->getDocumento()), 14)); + $this->add(18, 37, Util::formatCnab('X', $this->getCodigoCliente(), 20)); + $this->add(38, 62, Util::formatCnab('X', $boleto->getNumeroControle(), 25)); // numero de controle + $this->add(63, 73, Util::formatCnab('9', $boleto->getNossoNumero(), 11)); + $this->add(74, 86, Util::formatCnab('X', '', 11)); + $this->add(87, 89, Util::formatCnab('X', '', 3)); + $this->add(90, 90, $boleto->getMulta() > 0 ? '2' : '0'); + $this->add(91, 103, Util::formatCnab('9', $boleto->getMulta(), 13, 4)); + $this->add(104, 105, $boleto->getMulta() > 0 ? '01' : '00'); + $this->add(106, 107, ''); + $this->add(108, 108, Util::formatCnab('9', $boleto->getModalidadeCarteira(), 1)); + $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO + if ($boleto->getStatus() == $boleto::STATUS_BAIXA) { + $this->add(109, 110, self::OCORRENCIA_PEDIDO_BAIXA); // BAIXA + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); // ALTERAR VENCIMENTO + } + if ($boleto->getStatus() == $boleto::STATUS_ALTERACAO_DATA) { + $this->add(109, 110, self::OCORRENCIA_ALT_VENCIMENTO); + } + if ($boleto->getStatus() == $boleto::STATUS_CUSTOM) { + $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); + } + $this->add(111, 120, Util::formatCnab('9', $boleto->getNumero(), 10)); + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); + $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(140, 142, $this->getCodigoBanco()); + $this->add(143, 146, Util::formatCnab('9', 0, 4)); + $this->add(147, 147, Util::formatCnab('9', 0, 1)); + $this->add(148, 149, $boleto->getEspecieDocCodigo()); + $this->add(150, 150, $boleto->getAceite()); + $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); + $this->add(157, 158, self::INSTRUCAO_SEM); + $this->add(159, 160, self::INSTRUCAO_SEM); + $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); + $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto(), 13, 2)); + $this->add(193, 205, Util::formatCnab('9', 0, 13, 2)); + $this->add(206, 218, Util::formatCnab('9', 0, 13, 2)); + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); + $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); + $this->add(235, 264, Util::formatCnab('X', $boleto->getPagador()->getNome(), 30)); + $this->add(265, 274, Util::formatCnab('X', '', 10)); + $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); + $this->add(315, 326, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 12)); + $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); + $this->add(335, 349, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 15)); + $this->add(350, 351, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); + $this->add(352, 381, Util::formatCnab('X', $boleto->getSacadorAvalista() ? $boleto->getSacadorAvalista()->getNome() : '', 30)); + $this->add(382, 385, Util::formatCnab('X', '', 3)); + $this->add(386, 391, Util::formatCnab('X', '', 6)); + $this->add(392, 393, Util::formatCnab('9', $boleto->getDiasProtesto('0'), 2)); + $this->add(394, 394, $boleto->getMoeda()); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + if ($chaveNfe = $boleto->getChaveNfe()) { + $this->iniciaDetalhe(); + $this->add(1, 1, '4'); + $this->add(38, 81, Util::formatCnab('9', $chaveNfe, 44)); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + + return $this; + } + + /** + * @return Rendimento + * @throws ValidationException + */ + protected function trailer() + { + $this->iniciaTrailer(); + + $this->add(1, 1, '9'); + $this->add(2, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->getCount(), 6)); + + return $this; + } +} diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Santander.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Santander.php index 70c81213..6d15e915 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Santander.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Santander.php @@ -1,11 +1,13 @@ addCampoObrigatorio('codigoCliente'); } - /** * Código do banco * @@ -104,7 +103,7 @@ public function setCodigoCliente($codigoCliente) * Retorna o codigo de transmissão. * * @return string - * @throws \Exception + * @throws ValidationException */ public function getCodigoTransmissao() { @@ -127,7 +126,7 @@ public function getCodigoTransmissao() /** * @return Santander - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -155,7 +154,7 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Santander $boleto * * @return Santander - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -229,7 +228,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(352, 381, Util::formatCnab('X', $boleto->getSacadorAvalista() ? $boleto->getSacadorAvalista()->getNome() : '', 30)); $this->add(382, 382, ''); $this->add(383, 383, 'I'); - $this->add(384, 385, substr($this->getConta(), -1) . CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta())); + $this->add(384, 385, substr($this->getConta(), -1) . (! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::santanderContaCorrente($this->getAgencia(), $this->getConta()))); if (strlen($this->getConta()) == 9) { $this->add(384, 385, substr($this->getConta(), -2)); } @@ -241,12 +240,36 @@ public function addBoleto(BoletoContract $boleto) $this->add(401, 444, Util::formatCnab('9', $chaveNfe, 44)); } + if ($boleto->validarPix()) { + $tipoChave = [ + $boleto::TIPO_CHAVEPIX_CPF => 1, + $boleto::TIPO_CHAVEPIX_CNPJ => 2, + $boleto::TIPO_CHAVEPIX_CELULAR => 3, + $boleto::TIPO_CHAVEPIX_EMAIL => 4, + $boleto::TIPO_CHAVEPIX_ALEATORIA => 5, + ]; + $this->iniciaDetalhe(); + $this->add(1, 1, '8'); + $this->add(2, 3, '00'); // '00' = Conforme Perfil do Beneficiário; '01' = Aceita qualquer valor; ‘02’ = Entre o mínimo e o máximo; ‘03’ = Não aceita pagamento com o valor divergente + $this->add(4, 5, '01'); // Quantidade de pagamentos + $this->add(6, 6, '2'); // '1' = % (percentual); '2' = valor + $this->add(7, 19, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(20, 24, Util::formatCnab('9', 200, 5, 2)); + $this->add(25, 37, Util::formatCnab('9', $boleto->getValor(), 13, 2)); + $this->add(38, 42, Util::formatCnab('9', 100, 5, 2)); + $this->add(43, 43, Util::formatCnab('9', $tipoChave[$boleto->getPixChaveTipo()], 1)); + $this->add(44, 120, Util::formatCnab('Z', $boleto->getPixChave(), 77)); + $this->add(121, 155, Util::formatCnab('X', $boleto->getID(), 35)); + $this->add(156, 394, ''); + $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); + } + return $this; } /** * @return Santander - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Sicredi.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Sicredi.php index 2e2f4cd6..bd2731fc 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Sicredi.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Sicredi.php @@ -1,11 +1,13 @@ carteira = 'A'; + return $this; } @@ -88,7 +89,7 @@ public function setCarteira($carteira) */ protected $codigoCliente; - /** + /** * Retorna o codigo do cliente. * * @return mixed @@ -114,7 +115,7 @@ public function setCodigoCliente($codigoCliente) /** * @return Sicredi - * @throws \Exception + * @throws ValidationException */ protected function header() { @@ -144,12 +145,12 @@ protected function header() * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Sicredi $boleto * * @return Sicredi - * @throws \Exception + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { $this->boletos[] = $boleto; - if (!$boleto->isComRegistro()) { + if (! $boleto->isComRegistro()) { return $this; } @@ -248,7 +249,7 @@ public function addBoleto(BoletoContract $boleto) /** * @return Sicredi - * @throws \Exception + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Unicred.php b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Unicred.php index 7078d7fc..d53fa78e 100644 --- a/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Unicred.php +++ b/src/Cnab/Remessa/Cnab400/Pagamento/Banco/Unicred.php @@ -1,11 +1,13 @@ addCampoObrigatorio('idremessa'); } - /** * Código do banco * @@ -55,7 +54,6 @@ public function __construct(array $params = []) * * @var array */ - protected $carteiras = ['21']; /** @@ -83,15 +81,15 @@ public function __construct(array $params = []) * Retorna o codigo do cliente. * * @return mixed - * @throws \Exception + * @throws ValidationException */ public function getCodigoCliente() { if (empty($this->codigoCliente)) { $this->codigoCliente = Util::formatCnab('9', $this->getCarteiraNumero(), 4) . - Util::formatCnab('9', $this->getAgencia(), 5) . - Util::formatCnab('9', $this->getConta(), 7) . - Util::formatCnab('9', $this->getContaDv() ?: CalculoDV::unicredContaCorrente($this->getConta()), 1); + Util::formatCnab('9', $this->getAgencia(), 5) . + Util::formatCnab('9', $this->getConta(), 7) . + ! is_null($this->getContaDv()) ? $this->getContaDv() : CalculoDV::unicredContaCorrente($this->getConta()); } return $this->codigoCliente; @@ -102,7 +100,7 @@ public function getCodigoCliente() * * @param mixed $codigoCliente * - * @return Bradesco + * @return Unicred */ public function setCodigoCliente($codigoCliente) { @@ -112,8 +110,8 @@ public function setCodigoCliente($codigoCliente) } /** - * @return $this - * @throws \Exception + * @return Unicred + * @throws ValidationException */ protected function header() { @@ -141,8 +139,8 @@ protected function header() /** * @param \VinicciusGuedes\LaravelCnab\Boleto\Banco\Unicred $boleto * - * @return $this - * @throws \Exception + * @return Unicred + * @throws ValidationException */ public function addBoleto(BoletoContract $boleto) { @@ -151,7 +149,7 @@ public function addBoleto(BoletoContract $boleto) $this->add(1, 1, '1'); $this->add(2, 6, Util::formatCnab('9', $this->getAgencia(), 5)); - $this->add(7, 7, CalculoDv::unicredAgencia($this->getAgencia()) ); + $this->add(7, 7, ! is_null($this->getAgenciaDv()) ? $this->getAgenciaDv() : CalculoDV::unicredAgencia($this->getAgencia())); $this->add(8, 19, Util::formatCnab('9', $this->getConta(), 12)); $this->add(20, 20, Util::formatCnab('9', $this->getContaDv(), 1)); $this->add(21, 21, '0'); @@ -170,25 +168,25 @@ public function addBoleto(BoletoContract $boleto) // ‘3’ = Isento // *OBSERVAÇÃO: // Para boletos com espécie 31 (Cartão de crédito): Deve ser '3' = Isento. - $this->add(94, 94, $boleto->getMulta() > 0 ? '2' : '3' ); //Código da multa 2 = TAXA (%) + $this->add(94, 94, $boleto->getMulta() > 0 ? '2' : '3'); //Código da multa 2 = TAXA (%) $this->add(95, 104, Util::formatCnab('9', $boleto->getMulta() > 0 ? $boleto->getMulta() : '0', 10, 2)); /** Código adotado pela FEBRABAN para identificação do tipo de pagamento de mora de juros. - Domínio: - ‘1’ = Valor Diário (R$) - ‘2’ = Taxa Mensal (%) - ‘3’= Valor Mensal (R$) * - ‘4’ = Taxa diária (%) - ‘5’ = Isento - **/ - $this->add(105, 105, (null!==$boleto->getMoraDia() && $boleto->getMoraDia()) > 0 ? '1' : '5' ); + * Domínio: + * ‘1’ = Valor Diário (R$) + * ‘2’ = Taxa Mensal (%) + * ‘3’= Valor Mensal (R$) * + * ‘4’ = Taxa diária (%) + * ‘5’ = Isento + **/ + $this->add(105, 105, (null !== $boleto->getMoraDia() && $boleto->getMoraDia()) > 0 ? '1' : '5'); /** Indica se o Título pode ou não ser utilizado como garantia de operação de desconto futura. - Domínio: - ‘S’ = Título selecionado para ser utilizado como garantia em uma operação de desconto - futura. - ‘N’ = Título NÃO selecionado para ser utilizado como garantia em uma operação de - desconto futura. - Default: ‘N’ - **/ + * Domínio: + * ‘S’ = Título selecionado para ser utilizado como garantia em uma operação de desconto + * futura. + * ‘N’ = Título NÃO selecionado para ser utilizado como garantia em uma operação de + * desconto futura. + * Default: ‘N’ + **/ $this->add(106, 106, 'N'); // Identificação de Título Descontável. $this->add(107, 108, ''); $this->add(109, 110, self::OCORRENCIA_REMESSA); // REGISTRO @@ -205,56 +203,56 @@ public function addBoleto(BoletoContract $boleto) $this->add(109, 110, sprintf('%2.02s', $boleto->getComando())); } $this->add(111, 120, Util::formatCnab('X', $boleto->getNumeroDocumento(), 10)); - $this->add(121, 126, $boleto->getDataVencimento()->format('dmy'));//DDMMAA + $this->add(121, 126, $boleto->getDataVencimento()->format('dmy')); //DDMMAA $this->add(127, 139, Util::formatCnab('9', $boleto->getValor(), 13, 2)); $this->add(140, 149, '0000000000'); // Código adotado pela FEBRABAN para identificação do desconto. // Domínio: // 0 = Isento // 1 = Valor Fixo - $this->add(150, 150, $boleto->getDesconto() > 0 ? '1' : '0' ); //Código do desconto + $this->add(150, 150, $boleto->getDesconto() > 0 ? '1' : '0'); //Código do desconto $this->add(151, 156, $boleto->getDataDocumento()->format('dmy')); $this->add(157, 157, '0'); // $this->add(158, 158, self::INSTRUCAO_SEM); if ($boleto->getDiasProtesto() > 0) { - // Código adotado pela FEBRABAN para identificar o tipo de prazo a ser considerado para o protesto. - // Domínio: - // 1 = Protestar Dias Corridos - // 2 = Protestar Dias Úteis - // 3 = Não Protestar => PADRAO - $this->add(158, 158, self::INSTRUCAO_PROTESTAR_DIAS_UTEIS);//Código para Protesto + // Código adotado pela FEBRABAN para identificar o tipo de prazo a ser considerado para o protesto. + // Domínio: + // 1 = Protestar Dias Corridos + // 2 = Protestar Dias Úteis + // 3 = Não Protestar => PADRAO + $this->add(158, 158, self::INSTRUCAO_PROTESTAR_DIAS_UTEIS); //Código para Protesto $this->add(159, 160, Util::formatCnab('9', $boleto->getDiasProtesto(), 2)); } else { - $this->add(158, 158, self::INSTRUCAO_NAO_PROTESTAR);//Código para Protesto + $this->add(158, 158, self::INSTRUCAO_NAO_PROTESTAR); //Código para Protesto $this->add(159, 160, Util::formatCnab('9', 0, 2)); } $this->add(161, 173, Util::formatCnab('9', $boleto->getMoraDia(), 13, 2)); $this->add(174, 179, $boleto->getDesconto() > 0 ? $boleto->getDataDesconto()->format('dmy') : '000000'); - $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto()>0?$boleto->getDesconto():'0', 13, 2)); - $this->add(193, 203, Util::formatCnab('9', $boleto->getNossoNumero(), 11));//Nosso Número na UNICRED - $this->add(204, 205, '00');//Valor do Abatimento a ser concedido - $this->add(206, 218, Util::formatCnab('9', 0, 13) );//Valor do Abatimento a ser concedido + $this->add(180, 192, Util::formatCnab('9', $boleto->getDesconto() > 0 ? $boleto->getDesconto() : '0', 13, 2)); + $this->add(193, 203, Util::formatCnab('9', $boleto->getNossoNumero(), 11)); //Nosso Número na UNICRED + $this->add(204, 205, '00'); //Valor do Abatimento a ser concedido + $this->add(206, 218, Util::formatCnab('9', 0, 13)); //Valor do Abatimento a ser concedido // Tipo de inscrição do Pagador // 01 – CPF // 02 - CNPJ - $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01');//Identificação do Tipo de Inscrição do Pagador + $this->add(219, 220, strlen(Util::onlyNumbers($boleto->getPagador()->getDocumento())) == 14 ? '02' : '01'); //Identificação do Tipo de Inscrição do Pagador /** Quando se tratar de CNPJ, adotar o critério de preenchimento da direita para a esquerda,utilizando: - - 2 posições para o controle; - - 4 posições para a filial; - - 8 posições para o CNPJ. - Quando se tratar de CPF, adotar o mesmo critério da direita para a esquerda, utilizando: - - 2 posições para o controle; - - 9 posições para o CPF; - - 3 posições a esquerda zeradas. - **/ + * - 2 posições para o controle; + * - 4 posições para a filial; + * - 8 posições para o CNPJ. + * Quando se tratar de CPF, adotar o mesmo critério da direita para a esquerda, utilizando: + * - 2 posições para o controle; + * - 9 posições para o CPF; + * - 3 posições a esquerda zeradas. + **/ $this->add(221, 234, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getDocumento()), 14)); $this->add(235, 274, Util::formatCnab('X', $boleto->getPagador()->getNome(), 40)); $this->add(275, 314, Util::formatCnab('X', $boleto->getPagador()->getEndereco(), 40)); $this->add(315, 326, Util::formatCnab('X', $boleto->getPagador()->getBairro(), 12)); $this->add(327, 334, Util::formatCnab('9', Util::onlyNumbers($boleto->getPagador()->getCep()), 8)); $this->add(335, 354, Util::formatCnab('X', $boleto->getPagador()->getCidade(), 20)); //Cidade Pagador - $this->add(355, 356, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2 )); //UF pagador + $this->add(355, 356, Util::formatCnab('X', $boleto->getPagador()->getUf(), 2)); //UF pagador $this->add(357, 394, Util::formatCnab('X', $boleto->getSacadorAvalista() ? $boleto->getSacadorAvalista()->getNome() : '', 38)); $this->add(395, 400, Util::formatCnab('9', $this->iRegistros + 1, 6)); //No Sequencial do Registro @@ -262,8 +260,8 @@ public function addBoleto(BoletoContract $boleto) } /** - * @return $this - * @throws \Exception + * @return Unicred + * @throws ValidationException */ protected function trailer() { diff --git a/src/Cnab/Retorno/AbstractRetorno.php b/src/Cnab/Retorno/AbstractRetorno.php index 88d35a00..a807c155 100644 --- a/src/Cnab/Retorno/AbstractRetorno.php +++ b/src/Cnab/Retorno/AbstractRetorno.php @@ -8,19 +8,24 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Detalhe as Detalhe240Contract; +use Countable; +use ReflectionClass; +use SeekableIterator; +use OutOfBoundsException; +use VinicciusGuedes\LaravelCnab\Util; +use Illuminate\Support\Collection; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Header as Header240Contract; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab400\Header as Header400Contract; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Detalhe as Detalhe240Contract; use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Trailer as Trailer240Contract; use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab400\Detalhe as Detalhe400Contract; use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab400\Trailer as Trailer400Contract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab400\Header as Header400Contract; -use Illuminate\Support\Collection; -use VinicciusGuedes\LaravelCnab\Util; -abstract class AbstractRetorno implements \Countable, \SeekableIterator +abstract class AbstractRetorno implements Countable, SeekableIterator { /** - * Se Cnab ja foi processado + * Se cnab ja foi processado * * @var bool */ @@ -34,7 +39,7 @@ abstract class AbstractRetorno implements \Countable, \SeekableIterator protected $codigoBanco; /** - * Incremeto de detalhes + * Incremento de detalhes * * @var int */ @@ -72,22 +77,21 @@ abstract class AbstractRetorno implements \Countable, \SeekableIterator /** * @var int */ - private $_position = 1; + protected $_position = 1; /** - * - * @param String $file - * @throws \Exception + * @param string $file + * @throws ValidationException */ public function __construct($file) { $this->_position = 1; if (!$this->file = Util::file2array($file)) { - throw new \Exception("Arquivo: não existe"); + throw new ValidationException('Arquivo: não existe'); } - $r = new \ReflectionClass('\VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto'); + $r = new ReflectionClass('\VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto'); $constantNames = $r->getConstants(); $bancosDisponiveis = []; foreach ($constantNames as $constantName => $codigoBanco) { @@ -97,12 +101,12 @@ public function __construct($file) } if (!Util::isHeaderRetorno($this->file[0])) { - throw new \Exception(sprintf("Arquivo de retorno inválido")); + throw new ValidationException('Arquivo de retorno inválido'); } $banco = Util::isCnab400($this->file[0]) ? mb_substr($this->file[0], 76, 3) : mb_substr($this->file[0], 0, 3); if (!in_array($banco, $bancosDisponiveis)) { - throw new \Exception(sprintf("Banco: %s, inválido", $banco)); + throw new ValidationException(sprintf('Banco: %s, inválido', $banco)); } } @@ -117,7 +121,7 @@ public function getCodigoBanco() } /** - * @return mixed + * @return string */ public function getBancoNome() { @@ -125,7 +129,7 @@ public function getBancoNome() } /** - * @return mixed + * @return int */ public function getTipo() { @@ -193,7 +197,7 @@ protected function detalheAtual() } /** - * Se esta processado + * Se está processado * * @return bool */ @@ -201,6 +205,7 @@ protected function isProcessado() { return $this->processado; } + /** * Seta cnab como processado * @@ -209,6 +214,7 @@ protected function isProcessado() protected function setProcessado() { $this->processado = true; + return $this; } @@ -239,14 +245,13 @@ abstract protected function toArray(); * @param $array * * @return string - * @throws \Exception + * @throws ValidationException */ protected function rem($i, $f, &$array) { return Util::remove($i, $f, $array); } - public function current() { return $this->detalhe[$this->_position]; @@ -254,7 +259,7 @@ public function current() public function next() { - ++$this->_position; + $this->_position++; } public function key() @@ -277,11 +282,11 @@ public function count() return count($this->detalhe); } - public function seek($position) + public function seek($offset) { - $this->_position = $position; + $this->_position = $offset; if (!$this->valid()) { - throw new \OutOfBoundsException('"Posição inválida "$position"'); + throw new OutOfBoundsException('"Posição inválida "$position"'); } } } diff --git a/src/Cnab/Retorno/Cnab240/AbstractRetorno.php b/src/Cnab/Retorno/Cnab240/AbstractRetorno.php index 5f597025..e442653f 100644 --- a/src/Cnab/Retorno/Cnab240/AbstractRetorno.php +++ b/src/Cnab/Retorno/Cnab240/AbstractRetorno.php @@ -1,19 +1,21 @@ $this->headerLote->toArray(), 'trailerLote' => $this->trailerLote->toArray(), 'trailer' => $this->trailer->toArray(), - 'detalhes' => new Collection() + 'detalhes' => new Collection(), ]; foreach ($this->detalhe as $detalhe) { $array['detalhes']->push($detalhe->toArray()); } + return $array; } diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Ailos.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Ailos.php new file mode 100644 index 00000000..e0d2d45f --- /dev/null +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Ailos.php @@ -0,0 +1,361 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '12' => 'Confirmação Recebimento Instrução de Abatimento', + '13' => 'Confirmação Recebimento Instrução de Cancelamento Abatimento', + '14' => 'Confirmação Recebimento Instrução Alteração de Vencimento', + '17' => 'Liquidação Após Baixa ou Liquidação Título Não Registrado', + '19' => 'Confirmação Recebimento Instrução de Protesto', + '20' => 'Confirmação Recebimento Instrução de Sustação/Cancelamento de Protesto', + '22' => 'Título Enviado ao Cartório', + '23' => 'Remessa a Cartório (Aponte em Cartório)', + '24' => 'Retirada de Cartório e Manutenção em Carteira', + '25' => 'Protestado e Baixado (Baixa por Ter Sido Protestado) ', + '26' => 'Instrução Rejeitada', + '27' => 'Confirmação do Pedido de Alteração de Outros Dados ', + '28' => 'Débito de Tarifas/Custas', + '36' => 'Confirmação de envio de e-mail e SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '42' => 'Confirmação da alteração dos dados do Sacado', + '46' => 'Instrução para cancelar protesto confirmada', + '51' => 'Título DDA reconhecido pelo Pagador (quando o pagador aceitar o boleto depois de ter recusado)', + '52' => 'Título DDA não reconhecido pelo Pagador', + '76' => 'Liquidação CEE (boleto emitido na modalidade Cooperativa Emite e Expede)', + '77' => 'Liquidação após Baixa ou Liquidação Título Não Registrado CEE (boleto emitido na modalidade Cooperativa Emite e Expede)', + '89' => 'Rejeição cartorária (Visualizar motivo na última página deste manual)', + '91' => 'Título em aberto não enviado ao pagador', + '92' => 'Inconsistência Negativação Serasa', + '93' => 'Incluir Serasa', + '94' => 'Excluir Serasa', + '95' => 'Instrução de SMS', + '96' => 'Cancelamento Instrução SMS', + '97' => 'Confirmação de instrução automática de protesto', + '98' => 'Excluir Protesto com carta de anuência', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '01' => "Código do Banco Inválido", + '02' => "Código do Registro Detalhe Inválido", + '03' => "Código do Segmento Inválido", + '04' => "Código de Movimento Não Permitido para Carteira", + '05' => "Código de Movimento Inválido", + '06' => "Tipo/Número de Inscrição do Cedente Inválidos", + '07' => "Agência/Conta/DV Inválido", + '08' => "Nosso Número Inválido", + '09' => "Nosso Número Duplicado", + '10' => "Carteira Inválida", + '11' => "Forma de Cadastramento do Título Inválido", + '12' => "Tipo de Documento Inválido", + '13' => "Identificação da Emissão do Boleto Inválida", + '14' => "Identificação da Distribuição do Boleto Inválida", + '15' => "Características da Cobrança Incompatíveis", + '16' => "Data de Vencimento Inválida", + '17' => "Data de Vencimento Anterior à Data de Emissão", + '18' => "Vencimento Fora do Prazo de Operação", + '19' => "Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias", + '20' => "Valor do Título Inválido", + '21' => "Espécie do Título Inválida", + '22' => "Espécie do Título Não Permitida para a Carteira", + '23' => "Aceite Inválido", + '24' => "Data da Emissão Inválida", + '25' => "Data da Emissão Posterior a Data de Entrada", + '26' => "Código de Juros de Mora Inválido", + '27' => "Vlr/Taxa de Juros de Mora Inválido", + '28' => "Código do Desconto Inválido", + '29' => "Valor do Desconto Maior ou Igual ao Valor do Título", + '30' => "Desconto a Conceder Não Confere", + '31' => "Concessão de Desconto - Já Existe Desconto Anterior", + '33' => "Valor do Abatimento Inválido", + '34' => "Valor do Abatimento Maior ou Igual ao Valor do Título", + '35' => "Valor a Conceder Não Confere", + '36' => "Concessão de Abatimento - Já Existe Abatimento Anterior", + '37' => "Código para Protesto Inválido", + '38' => "Prazo para Protesto Inválido", + '39' => "Pedido de Protesto Não Permitido para o Título", + '40' => "Título com Ordem de Protesto Emitida", + '41' => "Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto", + '42' => "Código para Baixa/Devolução Inválido", + '43' => "Prazo para Baixa/Devolução Inválido", + '44' => "Código da Moeda Inválido", + '45' => "Nome do Sacado Não Informado", + '46' => "Tipo/Número de Inscrição do Sacado Inválidos", + '47' => "Endereço do Sacado Não Informado", + '48' => "CEP Inválido", + '49' => "CEP Sem Praça de Cobrança (Não Localizado)", + '50' => "CEP Referente a um Banco Correspondente", + '51' => "CEP incompatível com a Unidade da Federação", + '52' => "Unidade da Federação Inválida", + '53' => "Tipo/Número de Inscrição do Sacador/Avalista Inválidos", + '54' => "Sacador/Avalista Não Informado", + '55' => "Nosso número no Banco Correspondente Não Informado", + '56' => "Código do Banco Correspondente Não Informado", + '57' => "Código da Multa Inválido", + '58' => "Data da Multa Inválida", + '59' => "Valor/Percentual da Multa Inválido", + '60' => "Movimento para Título Não Cadastrado", + '61' => "Alteração da Agência Cobradora/DV Inválida", + '62' => "Tipo de Impressão Inválido", + '63' => "Entrada para Título já cadastrado", + '64' => "Número da Linha Inválido", + '65' => "Código do Banco para Débito Inválido", + '66' => "Agência/Conta/DV para Débito Inválido", + '79' => "Data Juros de Mora Inválido", + '80' => "Data do Desconto Inválida", + '86' => "Seu Número Inválido", + '89' => "E-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto", + '91' => "E-mail/número do celular do sacado não informado", + '96' => "Número do Convenio invalido", + '97' => "Rejeição da alteração do prazo limite de recebimento", + '98' => "Rejeição de dispensa de prazo limite de recebimento", + '99' => "Rejeição da alteração do número do título dado pelo cedente", + 'A2' => "Rejeição da alteração dos dados do sacado", + 'A4' => "Sacado DDA", + 'A3' => "Rejeição da alteração dos dados do sacador/avalista", + 'A4R1' => "Sacado DDA / Registro online", + 'A4P1' => "Sacado DDA / Envio Cooperativa E/E PJ", + 'A5' => "Registro Rejeitado - Título já Liquidado", + 'A7' => "Título já se encontra na situação Pretendida", + 'A8' => "Título pendente na CIP (Existe uma instrução pendente de processamento na CIP)", + 'A9' => "Título pendente na CIP (título é DDA e não possui número de identificação na CIP)", + 'BI' => "Beneficiário Divergente", + 'B3' => "Tipo de Pagamento Invalido", + 'B4' => "Vlr Max/Perc Invalido", + 'B5' => "Vlr Min/Perc Invalido", + 'B6' => "Parâmetro Pag. Divergente não habilitado no convênio de cobrança", + 'H3' => "Dias para prot. Inv. Min/máx (Número de dias de protesto está fora do limite mínimo e máximo parametrizados)", + 'H4' => "Prazo prot. Inv. (Prazo para protesto inválido)", + 'H6' => "Prot. não habilitado (Cooperado não está habilitado a protestar)", + 'NP' => "Boleto não protestado devido ao CEP do pagador incorreto", + 'P1' => "Enviado Cooperativa Emite e Expede", + 'PC' => "Boleto PCR (pagador não possui DDA ativo)", + 'R1' => "Registro Online", + 'S1' => "Cancelamento de Instrução de negativação não processada", + 'XA' => "Título em processo de registro", + 'XW' => "Serviço de SMS não contratado", + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setCodBanco($this->rem(1, 3, $header)) + ->setLoteServico($this->rem(4, 7, $header)) + ->setTipoRegistro($this->rem(8, 8, $header)) + ->setTipoInscricao($this->rem(18, 18, $header)) + ->setNumeroInscricao($this->rem(19, 32, $header)) + ->setCodigoCedente($this->rem(33, 52, $header)) + ->setAgencia($this->rem(53, 57, $header)) + ->setAgenciaDv($this->rem(58, 58, $header)) + ->setConta($this->rem(59, 70, $header)) + ->setContaDv($this->rem(71, 71, $header)) + ->setNomeEmpresa($this->rem(73, 102, $header)) + ->setNomeBanco($this->rem(103, 132, $header)) + ->setCodigoRemessaRetorno($this->rem(143, 143, $header)) + ->setData($this->rem(144, 151, $header)) + ->setNumeroSequencialArquivo($this->rem(158, 163, $header)) + ->setVersaoLayoutArquivo($this->rem(164, 166, $header)); + + return true; + } + + /** + * @param array $headerLote + * + * @return bool + * @throws ValidationException + */ + protected function processarHeaderLote(array $headerLote) + { + $this->getHeaderLote() + ->setCodBanco($this->rem(1, 3, $headerLote)) + ->setNumeroLoteRetorno($this->rem(4, 7, $headerLote)) + ->setTipoRegistro($this->rem(8, 8, $headerLote)) + ->setTipoOperacao($this->rem(9, 9, $headerLote)) + ->setTipoServico($this->rem(10, 11, $headerLote)) + ->setVersaoLayoutLote($this->rem(14, 16, $headerLote)) + ->setTipoInscricao($this->rem(18, 18, $headerLote)) + ->setNumeroInscricao($this->rem(19, 33, $headerLote)) + ->setCodigoCedente($this->rem(34, 53, $headerLote)) + ->setAgencia($this->rem(54, 58, $headerLote)) + ->setAgenciaDv($this->rem(59, 59, $headerLote)) + ->setConta($this->rem(60, 71, $headerLote)) + ->setContaDv($this->rem(72, 72, $headerLote)) + ->setNomeEmpresa($this->rem(74, 103, $headerLote)) + ->setNumeroRetorno($this->rem(184, 191, $headerLote)) + ->setDataGravacao($this->rem(192, 199, $headerLote)) + ->setDataCredito($this->rem(200, 207, $headerLote)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + if ($this->getSegmentType($detalhe) == 'T') { + $d->setOcorrencia($this->rem(16, 17, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $this->detalheAtual()->getOcorrencia(), 'Desconhecida')) + ->setNossoNumero($this->rem(38, 57, $detalhe)) + ->setCarteira($this->rem(58, 58, $detalhe)) + ->setNumeroDocumento($this->rem(59, 73, $detalhe)) + ->setDataVencimento($this->rem(74, 81, $detalhe)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) + ->setNumeroControle($this->rem(106, 130, $detalhe)) + ->setPagador([ + 'nome' => $this->rem(149, 188, $detalhe), + 'documento' => $this->rem(134, 148, $detalhe), + ]) + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); + + /** + * ocorrencias + */ + $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '17')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + $d->getPagador()->setDda(true); + } + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('25')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('27', '14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '26', '30', '36')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + } + + if ($this->getSegmentType($detalhe) == 'U') { + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setDataOcorrencia($this->rem(138, 145, $detalhe)) + ->setDataCredito($this->rem(146, 153, $detalhe)); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailerLote(array $trailer) + { + $this->getTrailerLote() + ->setLoteServico($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) + ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setNumeroLote($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdLotesArquivo((int) $this->rem(18, 23, $trailer)) + ->setQtdRegistroArquivo((int) $this->rem(24, 29, $trailer)); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bancoob.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bancoob.php index 6d7e710e..15d40bfb 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bancoob.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bancoob.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Bancoob extends AbstractRetorno implements RetornoCnab240 { @@ -201,12 +202,12 @@ class Bancoob extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -214,7 +215,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -244,7 +245,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -274,7 +275,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -293,34 +294,33 @@ protected function processarDetalhe(array $detalhe) * * Para voltar a considerar 10 digitos voltar trecho de código. * ////->setNossoNumero($this->rem(38, 47, $detalhe)) - * */ - if ( $this->rem(38, 39, $detalhe) != "00"){ - throw new \Exception("Verificar arquivo retorno: O nosso número no arquivo de retorno é maior que 7 dígitos."); + if ($this->rem(38, 39, $detalhe) != '00') { + throw new ValidationException('Verificar arquivo retorno: O nosso número no arquivo de retorno é maior que 7 dígitos.'); } $d->setNossoNumero($this->rem(40, 47, $detalhe)) ->setNossoNumero($this->rem(38, 47, $detalhe)) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%010s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17', '50')) { $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); @@ -335,19 +335,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -355,11 +343,11 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -371,7 +359,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -380,13 +368,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); return true; } @@ -395,7 +383,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Banrisul.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Banrisul.php index 88d52a64..2950724f 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Banrisul.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Banrisul.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Banrisul extends AbstractRetorno implements RetornoCnab240 { @@ -49,7 +50,6 @@ class Banrisul extends AbstractRetorno implements RetornoCnab240 'AC' => 'Situação do Título – Cartório', ]; - /** * Array com as possiveis descricoes de baixa e liquidacao. * @@ -71,7 +71,6 @@ class Banrisul extends AbstractRetorno implements RetornoCnab240 'AA' => 'Baixa por Pagamento', ]; - /** * Array com as possiveis rejeicoes do banco. * @@ -151,12 +150,12 @@ class Banrisul extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -164,7 +163,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -193,7 +192,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -223,7 +222,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -236,59 +235,33 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('09')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('25')) { $this->totais['protestados']++; @@ -298,19 +271,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -318,12 +279,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -335,7 +296,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -344,13 +305,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); return true; } @@ -359,7 +320,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bb.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bb.php index 176f1629..a7eb2804 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bb.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bb.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Bb extends AbstractRetorno implements RetornoCnab240 { @@ -207,12 +208,12 @@ class Bb extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -220,7 +221,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -249,7 +250,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -279,7 +280,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -292,59 +293,33 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('09')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('25')) { $this->totais['protestados']++; @@ -354,19 +329,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -374,14 +337,14 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(108, 122, $detalhe)/100, 2, false)) - ->setValorOutrosCreditos(Util::nFloat($this->rem(123, 137, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(108, 122, $detalhe) / 100, 2, false)) + ->setValorOutrosCreditos(Util::nFloat($this->rem(123, 137, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -393,7 +356,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -409,7 +372,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bradesco.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bradesco.php index 0a4498b0..be1798fe 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bradesco.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Bradesco.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Bradesco extends AbstractRetorno implements RetornoCnab240 { @@ -220,12 +221,12 @@ class Bradesco extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -233,7 +234,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -262,7 +263,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -292,7 +293,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -305,17 +306,17 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17')) { $this->totais['liquidados']++; @@ -337,7 +338,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); @@ -387,12 +388,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -404,7 +405,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -413,13 +414,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); return true; } @@ -428,7 +429,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Btg.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Btg.php new file mode 100644 index 00000000..e4384ad8 --- /dev/null +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Btg.php @@ -0,0 +1,465 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Transferência de Carteira/Entrada', + '05' => 'Transferência de Carteira/Baixa', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '11' => 'Títulos em Carteira (Em Ser)', + '12' => 'Confirmação Recebimento Instrução de Abatimento', + '13' => 'Confirmação Recebimento Instrução de Cancelamento Abatimento', + '14' => 'Confirmação Recebimento Instrução Alteração de Vencimento', + '15' => 'Franco de Pagamento', + '17' => 'Liquidação Após Baixa ou Liquidação Título Não Registrado', + '19' => 'Confirmação Recebimento Instrução de Protesto', + '20' => 'Confirmação Recebimento Instrução de Sustação/Cancelamento de Protesto', + '23' => 'Remessa a Cartório (Aponte em Cartório)', + '24' => 'Retirada de Cartório e Manutenção em Carteira', + '25' => 'Protestado e Baixado (Baixa por Ter Sido Protestado)', + '26' => 'Instrução Rejeitada', + '27' => 'Confirmação do Pedido de Alteração de Outros Dados', + '28' => 'Débito de Tarifas/Custas', + '29' => 'Ocorrências do Pagador', + '30' => 'Alteração de Dados Rejeitada', + '33' => 'Confirmação da Alteração dos Dados do Rateio de Crédito', + '34' => 'Confirmação do Cancelamento dos Dados do Rateio de Crédito', + '35' => 'Confirmação do Desagendamento do Débito Automático', + '36' => 'Confirmação de envio de e-mail/SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '38' => 'Confirmação de alteração do Prazo Limite de Recebimento (a data deve ser informada no campo 28.3.p)', + '39' => 'Confirmação de Dispensa de Prazo Limite de Recebimento', + '40' => 'Confirmação da alteração do número do título dado pelo Beneficiário', + '41' => 'Confirmação da alteração do número controle do Participante', + '42' => 'Confirmação da alteração dos dados do Pagador', + '43' => 'Confirmação da alteração dos dados do Sacador/Avalista', + '44' => 'Título pago com cheque devolvido', + '45' => 'Título pago com cheque compensado', + '46' => 'Instrução para cancelar protesto confirmada', + '47' => 'Instrução para protesto para fins falimentares confirmada', + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança', + '49' => 'Alteração de contrato de cobrança', + '50' => 'Título pago com cheque pendente de liquidação', + '51' => 'Título DDA reconhecido pelo Pagador', + '52' => 'Título DDA não reconhecido pelo Pagador', + '53' => 'Título DDA recusado pela CIP', + '54' => 'Confirmação da Instrução de Baixa de Título Negativado sem Protesto', + '55' => 'Confirmação de Pedido de Dispensa de Multa', + '56' => 'Confirmação do Pedido de Cobrança de Multa', + '57' => 'Confirmação do Pedido de Alteração de Cobrança de Juros', + '58' => 'Confirmação do Pedido de Alteração do Valor/Data de Desconto', + '59' => 'Confirmação do Pedido de Alteração do Beneficiário do Título', + '60' => 'Confirmação do Pedido de Dispensa de Juros de Mora', + '61' => 'Confirmação de Alteração do Valor Nominal do Título', + '63' => 'Título Sustado Judicialmente', + '64' => 'Confirmação de alteração do valor mínimo/percentual', + '65' => 'Confirmação de alteração do valor máximo/percentual', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '02032630' => [ + '01' => 'Código do Banco Inválido', + '02' => 'Código do Registro Detalhe Inválido', + '03' => 'Código do Segmento Inválido', + '04' => 'Código de Movimento Não Permitido para Carteira', + '05' => 'Código de Movimento Inválido', + '06' => 'Tipo/Número de Inscrição do Beneficiário Inválidos', + '07' => 'Agência/Conta/DV Inválido', + '08' => 'Nosso Número Inválido', + '09' => 'Nosso Número Duplicado', + '10' => 'Carteira Inválida', + '11' => 'Forma de Cadastramento do Título Inválido', + '12' => 'Tipo de Documento Inválido', + '13' => 'Identificação da Emissão do Boleto de Pagamento Inválida', + '14' => 'Identificação da Distribuição do Boleto de Pagamento Inválida', + '15' => 'Características da Cobrança Incompatíveis', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior a Data de Emissão', + '18' => 'Vencimento Fora do Prazo de Operação', + '19' => 'Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias', + '20' => 'Valor do Título Inválido', + '21' => 'Espécie do Título Inválida', + '22' => 'Espécie do Título Não Permitida para a Carteira', + '23' => 'Aceite Inválido', + '24' => 'Data da Emissão Inválida', + '25' => 'Data da Emissão Posterior a Data de Entrada', + '26' => 'Código de Juros de Mora Inválido', + '27' => 'Valor/Taxa de Juros de Mora Inválido', + '28' => 'Código do Desconto Inválido', + '29' => 'Valor do Desconto Maior ou Igual ao Valor do Título', + '30' => 'Desconto a Conceder Não Confere', + '31' => 'Concessão de Desconto - Já Existe Desconto Anterior', + '32' => 'Valor do IOF Inválido', + '33' => 'Valor do Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do Título', + '35' => 'Valor a Conceder Não Confere', + '36' => 'Concessão de Abatimento - Já Existe Abatimento Anterior', + '37' => 'Código para Protesto Inválido', + '38' => 'Prazo para Protesto Inválido', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto', + '42' => 'Código para Baixa/Devolução Inválido', + '43' => 'Prazo para Baixa/Devolução Inválido', + '44' => 'Código da Moeda Inválido', + '45' => 'Nome do Pagador Não Informado', + '46' => 'Tipo/Número de Inscrição do Pagador Inválidos', + '47' => 'Endereço do Pagador Não Informado', + '48' => 'CEP Inválido', + '49' => 'CEP Sem Praça de Cobrança (Não Localizado)', + '50' => 'CEP Referente a um Banco Correspondente', + '51' => 'CEP incompatível com a Unidade da Federação', + '52' => 'Unidade da Federação Inválida', + '53' => 'Tipo/Número de Inscrição do Sacador/Avalista Inválidos', + '54' => 'Sacador/Avalista Não Informado', + '55' => 'Nosso número no Banco Correspondente Não Informado', + '56' => 'Código do Banco Correspondente Não Informado', + '57' => 'Código da Multa Inválido', + '58' => 'Data da Multa Inválida', + '59' => 'Valor/Percentual da Multa Inválido', + '60' => 'Movimento para Título Não Cadastrado', + '61' => 'Alteração da Agência Cobradora/DV Inválida', + '62' => 'Tipo de Impressão Inválido', + '63' => 'Entrada para Título já Cadastrado', + '64' => 'Número da Linha Inválido', + '65' => 'Código do Banco para Débito Inválido', + '66' => 'Agência/Conta/DV para Débito Inválido', + '67' => 'Dados para Débito incompatível com a Identificação da Emissão do Boleto de Pagamento', + '68' => 'Débito Automático Agendado', + '69' => 'Débito Não Agendado - Erro nos Dados da Remessa', + '70' => 'Débito Não Agendado - Pagador Não Consta do Cadastro de Autorizante', + '71' => 'Débito Não Agendado - Beneficiário Não Autorizado pelo Pagador', + '72' => 'Débito Não Agendado - Beneficiário Não Participa da Modalidade Débito Automático', + '73' => 'Débito Não Agendado - Código de Moeda Diferente de Real (R$)', + '74' => 'Débito Não Agendado - Data Vencimento Inválida', + '75' => 'Débito Não Agendado, Conforme seu Pedido, Título Não Registrado', + '76' => 'Débito Não Agendado, Tipo/Num. Inscrição do Debitado, Inválido', + '77' => 'Transferência para Desconto Não Permitida para a Carteira do Título', + '78' => 'Data Inferior ou Igual ao Vencimento para Débito Automático', + '79' => 'Data Juros de Mora Inválido', + '80' => 'Data do Desconto Inválida', + '81' => 'Tentativas de Débito Esgotadas - Baixado', + '82' => 'Tentativas de Débito Esgotadas - Pendente', + '83' => 'Limite Excedido', + '84' => 'Número Autorização Inexistente', + '85' => 'Título com Pagamento Vinculado', + '86' => 'Seu Número Inválido', + '87' => 'e-mail/SMS enviado', + '88' => 'e-mail Lido', + '89' => 'e-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto', + '90' => 'e-mail devolvido - caixa postal cheia', + '91' => 'e-mail/número do celular do Pagador não informado', + '92' => 'Pagador optante por Boleto de Pagamento Eletrônico - e-mail não enviado', + '93' => 'Código para emissão de Boleto de Pagamento não permite envio de e-mail', + '94' => 'Código da Carteira inválido para envio e-mail.', + '95' => 'Contrato não permite o envio de e-mail', + '96' => 'Número de contrato inválido', + '97' => 'Rejeição da alteração do prazo limite de recebimento (a data deve ser informada no campo 28.3.p)', + '98' => 'Rejeição de dispensa de prazo limite de recebimento', + '99' => 'Rejeição da alteração do número do título dado pelo Beneficiário', + 'A1' => 'Rejeição da alteração do número controle do participante', + 'A2' => 'Rejeição da alteração dos dados do Pagador', + 'A3' => 'Rejeição da alteração dos dados do Sacador/avalista', + 'A4' => 'Pagador DDA', + 'A5' => 'Registro Rejeitado – Título já Liquidado', + 'A6' => 'Código do Convenente Inválido ou Encerrado', + 'A7' => 'Título já se encontra na situação Pretendida', + 'A8' => 'Valor do Abatimento inválido para cancelamento', + 'A9' => 'Não autoriza pagamento parcial', + 'B1' => 'Autoriza recebimento parcial', + 'B2' => 'Valor Nominal do Título Conflitante', + 'B3' => 'Tipo de Pagamento Inválido', + 'B4' => 'Valor Máximo/Percentual Inválido', + 'B5' => 'Valor Mínimo/Percentual Inválido', + ], + '28' => [ + '01' => 'Tarifa de Extrato de Posição', + '02' => 'Tarifa de Manutenção de Título Vencido', + '03' => 'Tarifa de Sustação', + '04' => 'Tarifa de Protesto', + '05' => 'Tarifa de Outras Instruções', + '06' => 'Tarifa de Outras Ocorrências', + '07' => 'Tarifa de Envio de Duplicata ao Pagador', + '08' => 'Custas de Protesto', + '09' => 'Custas de Sustação de Protesto', + '10' => 'Custas de Cartório Distribuidor', + '11' => 'Custas de Edital', + '12' => 'Tarifa Sobre Devolução de Título Vencido', + '13' => 'Tarifa Sobre Registro Cobrada na Baixa/Liquidação', + '14' => 'Tarifa Sobre Reapresentação Automática', + '15' => 'Tarifa Sobre Rateio de Crédito', + '16' => 'Tarifa Sobre Informações Via Fax', + '17' => 'Tarifa Sobre Prorrogação de Vencimento', + '18' => 'Tarifa Sobre Alteração de Abatimento/Desconto', + '19' => 'Tarifa Sobre Arquivo mensal (Em Ser)', + '20' => 'Tarifa Sobre Emissão de Boleto de Pagamento Pré-Emitido pelo Banco', + ], + '060917' => [ + '01' => 'Por Saldo', + '02' => 'Por Conta', + '03' => 'Liquidação no Guichê de Caixa em Dinheiro', + '04' => 'Compensação Eletrônica', + '05' => 'Compensação Convencional', + '06' => 'Por Meio Eletrônico', + '07' => 'Após Feriado Local', + '08' => 'Em Cartório', + '30' => 'Liquidação no Guichê de Caixa em Cheque', + '31' => 'Liquidação em banco correspondente', + '32' => 'Liquidação Terminal de Auto-Atendimento', + '33' => 'Liquidação na Internet (Home banking)', + '34' => 'Liquidado Office Banking', + '35' => 'Liquidado Correspondente em Dinheiro', + '36' => 'Liquidado Correspondente em Cheque', + '37' => 'Liquidado por meio de Central de Atendimento (Telefone)', + '09' => 'Comandada Banco', + '10' => 'Comandada Cliente Arquivo', + '11' => 'Comandada Cliente On-line', + '12' => 'Decurso Prazo - Cliente', + '13' => 'Decurso Prazo - Banco', + '14' => 'Protestado', + '15' => 'Título Excluído', + ], + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setCodBanco($this->rem(1, 3, $header)) + ->setLoteServico($this->rem(4, 7, $header)) + ->setTipoRegistro($this->rem(8, 8, $header)) + ->setTipoInscricao($this->rem(18, 18, $header)) + ->setNumeroInscricao($this->rem(19, 32, $header)) + ->setCodigoCedente($this->rem(33, 52, $header)) + ->setAgencia($this->rem(54, 57, $header)) + ->setAgenciaDv($this->rem(58, 58, $header)) + ->setConta($this->rem(66, 70, $header)) + ->setContaDv($this->rem(72, 72, $header)) + ->setNomeEmpresa($this->rem(73, 102, $header)) + ->setNomeBanco($this->rem(103, 132, $header)) + ->setCodigoRemessaRetorno($this->rem(143, 143, $header)) + ->setData($this->rem(144, 151, $header)) + ->setNumeroSequencialArquivo($this->rem(158, 163, $header)) + ->setVersaoLayoutArquivo($this->rem(164, 166, $header)); + + return true; + } + + /** + * @param array $headerLote + * + * @return bool + * @throws ValidationException + */ + protected function processarHeaderLote(array $headerLote) + { + $this->getHeaderLote() + ->setCodBanco($this->rem(1, 3, $headerLote)) + ->setNumeroLoteRetorno($this->rem(4, 7, $headerLote)) + ->setTipoRegistro($this->rem(8, 8, $headerLote)) + ->setTipoOperacao($this->rem(9, 9, $headerLote)) + ->setTipoServico($this->rem(10, 11, $headerLote)) + ->setVersaoLayoutLote($this->rem(14, 16, $headerLote)) + ->setTipoInscricao($this->rem(18, 18, $headerLote)) + ->setNumeroInscricao($this->rem(19, 33, $headerLote)) + ->setCodigoCedente($this->rem(34, 53, $headerLote)) + ->setAgencia($this->rem(54, 58, $headerLote)) + ->setAgenciaDv($this->rem(59, 59, $headerLote)) + ->setConta($this->rem(60, 71, $headerLote)) + ->setContaDv($this->rem(72, 72, $headerLote)) + ->setNomeEmpresa($this->rem(74, 103, $headerLote)) + ->setNumeroRetorno($this->rem(184, 191, $headerLote)) + ->setDataGravacao($this->rem(192, 199, $headerLote)) + ->setDataCredito($this->rem(200, 207, $headerLote)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + if ($this->getSegmentType($detalhe) == 'T') { + $d->setOcorrencia($this->rem(16, 17, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $this->detalheAtual()->getOcorrencia(), 'Desconhecida')) + ->setNossoNumero($this->rem(38, 57, $detalhe)) + ->setCarteira($this->rem(58, 58, $detalhe)) + ->setNumeroDocumento($this->rem(59, 73, $detalhe)) + ->setDataVencimento($this->rem(74, 81, $detalhe)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) + ->setNumeroControle($this->rem(106, 130, $detalhe)) + ->setPagador([ + 'nome' => $this->rem(149, 188, $detalhe), + 'documento' => $this->rem(134, 148, $detalhe), + ]) + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); + + /** + * ocorrencias + */ + $msgAdicional = str_split(sprintf('%010s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '17')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02', '04', '63')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('05', '09')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('25')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('40', '41', '42', '43', '61', '64', '65')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '26', '30', '37')) { + $this->totais['erros']++; + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + if ($d->hasOcorrencia('51')) { + $d->getPagador()->setDda(true); + } + + if ($d->hasOcorrencia('02', '03', '26', '30')) { + $error = Util::appendStrings( + Arr::get($this->rejeicoes['02032630'], $msgAdicional[0], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[1], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[2], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[3], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[4], '') + ); + $d->setError($error); + } + + if ($d->hasOcorrencia('28')) { + $error = Util::appendStrings( + Arr::get($this->rejeicoes['28'], $msgAdicional[0], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[1], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[2], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[3], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[4], '') + ); + $d->setError($error); + } + + if ($d->hasOcorrencia('06', '09', '17')) { + $error = Util::appendStrings( + Arr::get($this->rejeicoes['060917'], $msgAdicional[0], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[1], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[2], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[3], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[4], '') + ); + $d->setError($error); + } + } + + if ($this->getSegmentType($detalhe) == 'U') { + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setDataOcorrencia($this->rem(138, 145, $detalhe)) + ->setDataCredito($this->rem(146, 153, $detalhe)); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailerLote(array $trailer) + { + $this->getTrailerLote() + ->setLoteServico($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) + ->setQtdTitulosCobrancaSimples((int) $this->rem(18, 23, $trailer)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(24, 41, $trailer) / 100, 2, false)); + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setNumeroLote($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdLotesArquivo((int) $this->rem(18, 23, $trailer)) + ->setQtdRegistroArquivo((int) $this->rem(24, 29, $trailer)); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Caixa.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Caixa.php index 6775234d..1db68f18 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Caixa.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Caixa.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Caixa extends AbstractRetorno implements RetornoCnab240 { @@ -353,12 +354,12 @@ class Caixa extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -366,7 +367,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -393,7 +394,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -421,7 +422,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -434,59 +435,33 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 69, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '46')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('09')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('25')) { $this->totais['protestados']++; @@ -496,19 +471,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30', '39', '40', '41')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -516,12 +479,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -533,7 +496,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -549,7 +512,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Cresol.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Cresol.php new file mode 100644 index 00000000..ca05f9be --- /dev/null +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Cresol.php @@ -0,0 +1,436 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Transferência de carteira/entrada', + '05' => 'Transferência de carteira/baixa', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '11' => 'Em Ser - Títulos em carteira', + '12' => 'Confirmação recebimento instrução de abatimento', + '13' => 'Confirmação recebimento instrução de cancelamento de abatimento', + '14' => 'Confirmação recebimento instrução alteração de vencimento', + '15' => 'Franco de pagamento', + '17' => 'Liquidação após baixa ou liquidação de título não registrado', + '19' => 'Confirmação Receb. Inst. de Protesto', + '20' => 'Confirmação recebimento instrução de sustação/cancelamento de protesto', + '23' => 'Remessa a cartório (aponte em cartório)', + '24' => 'Retirada de cartório e manutenção em carteira', + '25' => 'Protestado e baixado (baixa por ter sido protestado)', + '26' => 'Instrução rejeitada', + '27' => 'Confirmação do pedido de alteração de outros dados', + '28' => 'Débito de tarifas/custas', + '29' => 'Ocorrências do pagador', + '30' => 'Alteração de Outros Dados Rejeitados', + '33' => 'Confirmação da Alteração dos Dados do Rateio de Crédito', + '34' => 'Confirmação do Cancelamento dos Dados do Rateio de Crédito', + '35' => 'Confirmação do Desagendamento do Débito Automático', + '36' => 'Confirmação de envio de e-mail/SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '38' => 'Confirmação de alteração do Prazo Limite de Recebimento', + '39' => 'Confirmação de Dispensa de Prazo Limite de Recebimento', + '40' => 'Confirmação da alteração do número do título dado pelo cedente', + '41' => 'Confirmação da alteração do número controle do Participante', + '42' => 'Confirmação da alteração dos dados do Sacado', + '43' => 'Confirmação da alteração dos dados do Sacador/Avalista', + '44' => 'Título pago com cheque devolvido', + '45' => 'Título pago com cheque compensado', + '46' => 'Instrução para cancelar protesto confirmada', + '47' => 'Instrução para protesto para fins falimentares confirmada', + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança', + '49' => 'Alteração de contrato de cobrança', + '50' => 'Título pago com cheque pendente de liquidação', + '51' => 'Título DDA reconhecido pelo sacado', + '52' => 'Título DDA não reconhecido pelo sacado', + '53' => 'Título DDA recusado pela CIP', + '54' => 'Confirmação da Instrução de Baixa de Título Negativado sem Protesto', + '55' => 'Confirmação de Pedido de Dispensa de Multa', + '56' => 'Confirmação do Pedido de Cobrança de Multa', + '57' => 'Confirmação do Pedido de Alteração de Cobrança de Juros', + '58' => 'Confirmação do Pedido de Alteração do Valor/Data de Desconto', + '59' => 'Confirmação do Pedido de Alteração do Cedente do Título', + '60' => 'Confirmação do Pedido de Dispensa de Juros de Mora', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '1' => 'Código do Banco Inválido', + '2' => 'Código do Registro Detalhe Inválido', + '3' => 'Código do Segmento Inválido', + '4' => 'Código de Movimento Não Permitido para Carteira', + '5' => 'Código de Movimento Inválido', + '6' => 'Tipo/Número de Inscrição do Cedente Inválidos', + '7' => 'Agência/Conta/DV Inválido', + '8' => 'Nosso Número Inválido', + '9' => 'Nosso Número Duplicado', + '10' => 'Carteira Inválida', + '11' => 'Forma de Cadastramento do Título Inválido', + '12' => 'Tipo de Documento Inválido', + '13' => 'Identificação de Emissão do Bloqueto Inválida', + '14' => 'Identificação da Distribuição do Bloqueto Inválida', + '15' => 'Características da Cobrança Incompatíveis', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior a Data de Emissão', + '18' => 'Vencimento Fora do Prazo de Operação', + '19' => 'Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias', + '20' => 'Valor do Título Inválido', + '21' => 'Espécie do Título Inválida', + '22' => 'Espécie do Título Não Permitida para a Carteira', + '23' => 'Aceite Inválido', + '24' => 'Data de Emissão Inválida', + '25' => 'Data da Emissão Posterior a Data de Entrada', + '26' => 'Código de Juros de Mora Inválido', + '27' => 'Valor/Taxa de Juros de Mora Inválido', + '28' => 'Código do Desconto Inválido', + '29' => 'Valor do Desconto Maior ou Igual ao Valor do Título', + '30' => 'Desconto a Conceder Não Confere', + '31' => 'Concessão de Desconto - Já Existe Desconto Anterior', + '32' => 'Valor do IOF Inválido', + '33' => 'Valor do Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do Título', + '35' => 'Valor a Conceder Não Confere', + '36' => 'Concessão de Abatimento - Já Existe Abatimento Anterior', + '37' => 'Código para Protesto Inválido', + '38' => 'Prazo para Protesto Inválido', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto', + '42' => 'Código para Baixa/Devolução Inválido', + '43' => 'Prazo para Baixa/Devolução Inválida', + '44' => 'Código da Moeda Inválido', + '45' => 'Nome do Sacado Não Informado', + '46' => 'Tipo/Número de Inscrição do Sacado Inválido', + '47' => 'Endereço do Sacado Não Informado', + '48' => 'CEP Inválido', + '49' => 'CEP Sem Praça de Cobrança (Não Localizado)', + '50' => 'CEP Referente a um Banco Correspondente', + '51' => 'CEP imcompatível com a Unidade da Federação', + '52' => 'Registro de Título já liquidado Cart. 17', + '53' => 'Tipo/Número de Inscrição do Sacador/Avalista Inválidos', + '54' => 'Sacador/Avalista Não Informado', + '55' => 'Nosso Número no Banco Correspondente Não Informado', + '56' => 'Código do Banco Correspondente Não Informado', + '57' => 'Código da Multa Inválido', + '58' => 'Data da Multa Inválida', + '59' => 'Valor/Percentual da Multa Inválido', + '60' => 'Movimento para Título Não Cadastrado', + '61' => 'Alteração da Agência Cobradora/DV Inválida', + '62' => 'Tipo de Impressão Inválido', + '63' => 'Entrada para Título já Cadastrado', + '64' => 'Número da Linha Inválido', + '65' => 'Código do Banco para Débito Inválido', + '66' => 'Agência/Conta/DV para Débito Inválido', + '67' => 'Dados para Débito incompatível com a Identificação da Emissão do Bloqueto', + '68' => 'Débito Automático Agendado', + '69' => 'Débito Não Agendado - Erro nos Dados da Remessa', + '70' => 'Débito Não Agendado - Sacado Não Consta do Cadastro de Autorizante', + '71' => 'Débito Não Agendado - Cedente Não Autorizado pelo Sacado', + '72' => 'Débito Não Agendado - Cedente Não Participa da Modalidade Débito Automático', + '73' => 'Débito Não Agendado - Código de Moeda Diferente de Reao (R$)', + '74' => 'Débito Não Agendado - Data Vencimento Inválida', + '75' => 'Débito Não Agendado, Conforme seu Pedido, Título Não Registrado', + '76' => 'Débito Não Agendado, Tipo/Num. Inscrição do Debitado, Inválido', + '77' => 'Transferência para Desconto Não Permitida para a Cateira do Título', + '78' => 'Data Inferior ou Igual ao Vencimento para Débito Automático', + '79' => 'Data Juros de Mora Inválido', + '80' => 'Data do Desconto Inválida', + '81' => 'Tentativas de Débito Esgotadas - Baixado', + '82' => 'Tentativas de Débito Esgotadas - Pendente', + '83' => 'Limite Excedido', + '84' => 'Número Autorização Inexistente', + '85' => 'Título com Pagamento Vinculado', + '86' => 'Seu Número Inválido', + '87' => 'e-mail/SMS enviado', + '88' => 'e-mail Lido', + '89' => 'e-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto', + '90' => 'e-mail devolvido - caixa postal cheia', + '91' => 'e-mail/número do celular do sacado não informado', + '92' => 'Sacado optante por Bloqueto Eletrônico - e-mail não enviado', + '93' => 'Código para emissão de bloqueto não permite envio de e-mail', + '94' => 'Código da Carteira inválido para envio e-mail', + '95' => 'Contrato não permite o envio de e-mail', + '96' => 'Número de contrato inválido', + '97' => 'Rejeição da alteração do prazo limite de recebimento', + '98' => 'Rejeição de dispensa de prazo limite de recebimento', + '99' => 'Rejeição da alteração do número do título dado pelo cedente', + 'A1' => 'Rejeição da alteração do número controle do participante', + 'A2' => 'Rejeição da alteração dos dados do sacado', + 'A3' => 'Rejeição da alteração dos dados do sacador/avalista', + 'A4' => 'Sacado DDA', + 'A5' => 'Registro Rejeitado - Título já Liquidado', + 'A6' => 'Código do Convenente Inválido ou Encerrado', + 'A7' => 'Título se já encontra na situação Pretendida', + 'A8' => 'Valor do Abatimento inválido para cancelamento', + 'A9' => 'Não autoriza pagamento parcial', + 'B1' => 'Autoriza recebimento parcial', + ]; + + /** + * Array com as possiveis descricoes de baixa e liquidacao. + * + * @var array + */ + private $baixa_liquidacao = [ + '01' => 'Por Saldo', + '02' => 'Por Conta', + '03' => 'Liquidação no Guichê de Caixa em Dinheiro', + '04' => 'Compensação Eletrônica', + '05' => 'Compensação Convencional', + '06' => 'Por Meio Eletrônico', + '07' => 'Após Feriado Local', + '08' => 'Em Cartório', + '30' => 'Liquidação no Guichê de Caixa em Cheque', + '31' => 'Liquidação em banco correspondente', + '32' => 'Liquidação Terminal de Auto-Atendimento', + '33' => 'Liquidação na Internet (Home banking)', + '34' => 'Liquidado Office Banking', + '35' => 'Liquidado Correspondente em Dinheiro', + '36' => 'Liquidado Correspondente em Cheque', + '37' => 'Liquidado por meio de Central de Atendimento (Telefone) Baixa: PELO BANCO)', + '09' => 'Comandada Banco', + '10' => 'Comandada Cliente Arquivo', + '11' => 'Comandada Cliente On-line', + '12' => 'Decurso Prazo - Cliente', + '13' => 'Decurso Prazo - Banco', + '14' => 'Protestado', + '15' => 'Título Excluído', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws \Exception + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setCodBanco($this->rem(1, 3, $header)) + ->setLoteServico($this->rem(4, 7, $header)) + ->setTipoRegistro($this->rem(8, 8, $header)) + ->setTipoInscricao($this->rem(18, 18, $header)) + ->setNumeroInscricao($this->rem(19, 32, $header)) + ->setAgencia($this->rem(53, 57, $header)) + ->setAgenciaDv($this->rem(58, 58, $header)) + ->setConta($this->rem(59, 70, $header)) + ->setContaDv($this->rem(71, 71, $header)) +// ->setContaDv($this->rem(72, 72, $header)) + ->setNomeEmpresa($this->rem(73, 102, $header)) + ->setNomeBanco($this->rem(103, 132, $header)) + ->setCodigoRemessaRetorno($this->rem(143, 143, $header)) + ->setData($this->rem(144, 151, $header)) + ->setNumeroSequencialArquivo($this->rem(158, 163, $header)) + ->setVersaoLayoutArquivo($this->rem(164, 166, $header)); + + return true; + } + + /** + * @param array $headerLote + * + * @return bool + * @throws \Exception + */ + protected function processarHeaderLote(array $headerLote) + { + $this->getHeaderLote() + ->setCodBanco($this->rem(1, 3, $headerLote)) + ->setNumeroLoteRetorno($this->rem(4, 7, $headerLote)) + ->setTipoRegistro($this->rem(8, 8, $headerLote)) + ->setTipoOperacao($this->rem(9, 9, $headerLote)) + ->setTipoServico($this->rem(10, 11, $headerLote)) + ->setVersaoLayoutLote($this->rem(14, 16, $headerLote)) + ->setTipoInscricao($this->rem(18, 18, $headerLote)) + ->setNumeroInscricao($this->rem(19, 33, $headerLote)) + ->setAgencia($this->rem(54, 58, $headerLote)) + ->setAgenciaDv($this->rem(59, 59, $headerLote)) + ->setConta($this->rem(60, 71, $headerLote)) + ->setContaDv($this->rem(72, 72, $headerLote)) +// ->setContaDv($this->rem(73, 73, $headerLote)) + ->setNomeEmpresa($this->rem(74, 103, $headerLote)) + ->setNumeroRetorno($this->rem(184, 191, $headerLote)) + ->setDataGravacao($this->rem(192, 199, $headerLote)) + ->setDataCredito($this->rem(200, 207, $headerLote)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws \Exception + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + if ($this->getSegmentType($detalhe) == 'T') { + $d->setOcorrencia($this->rem(16, 17, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $this->detalheAtual()->getOcorrencia(), 'Desconhecida')) + ->setNossoNumero($this->rem(38, 57, $detalhe)) + ->setCarteira($this->rem(58, 58, $detalhe)) + ->setNumeroDocumento($this->rem(59, 73, $detalhe)) + ->setDataVencimento($this->rem(74, 81, $detalhe)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) + ->setNumeroControle($this->rem(106, 130, $detalhe)) + ->setPagador([ + 'nome' => $this->rem(149, 188, $detalhe), + 'documento' => $this->rem(134, 148, $detalhe), + ]) + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); + + /** + * ocorrencias + */ + $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '17')) { + $this->totais['liquidados']++; + $ocorrencia = Util::appendStrings( + $d->getOcorrenciaDescricao(), + Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') + ); + $d->setOcorrenciaDescricao($ocorrencia); + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + $d->getPagador()->setDda(true); + } + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09')) { + $this->totais['baixados']++; + $ocorrencia = Util::appendStrings( + $d->getOcorrenciaDescricao(), + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + $d->setOcorrenciaDescricao($ocorrencia); + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('25')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('33', '38', '40', '41', '42', '43', '49')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '26', '30')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + } + + if ($this->getSegmentType($detalhe) == 'U') { + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setDataOcorrencia($this->rem(138, 145, $detalhe)) + ->setDataCredito($this->rem(146, 153, $detalhe)); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws \Exception + */ + protected function processarTrailerLote(array $trailer) + { + $this->getTrailerLote() + ->setLoteServico($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) + ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws \Exception + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setNumeroLote($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdLotesArquivo((int) $this->rem(18, 23, $trailer)) + ->setQtdRegistroArquivo((int) $this->rem(24, 29, $trailer)); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Itau.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Itau.php index 5e0ee008..76b84c82 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Itau.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Itau.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Itau extends AbstractRetorno implements RetornoCnab240 { @@ -225,7 +226,7 @@ class Itau extends AbstractRetorno implements RetornoCnab240 '40' => 'Não aprovada devido ao impacto na elegibilidade de garantias', '41' => 'Automaticamente rejeitada', '42' => 'Confirma recebimento de instrução – pendente de análise', - ] + ], ]; /** @@ -234,12 +235,12 @@ class Itau extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -247,7 +248,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -274,7 +275,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -302,7 +303,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -315,24 +316,24 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(38, 40, $detalhe)) ->setNumeroDocumento($this->rem(59, 68, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 221, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '08', '10')) { $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); @@ -366,12 +367,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -383,7 +384,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -392,9 +393,9 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)); return true; } @@ -403,7 +404,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Santander.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Santander.php index 7bd66000..d73805e4 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Santander.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Santander.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Santander extends AbstractRetorno implements RetornoCnab240 { @@ -130,12 +131,12 @@ class Santander extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -143,7 +144,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -172,7 +173,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -200,7 +201,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -212,24 +213,24 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(54, 54, $detalhe)) ->setNumeroDocumento($this->rem(55, 69, $detalhe)) ->setDataVencimento($this->rem(70, 77, $detalhe)) - ->setValor(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(101, 125, $detalhe)) ->setPagador([ - 'nome' => $this->rem(144, 183, $detalhe), + 'nome' => $this->rem(144, 183, $detalhe), 'documento' => $this->rem(129, 143, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(194, 208, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(194, 208, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%010s', $this->rem(209, 218, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '09', '17')) { $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); @@ -264,11 +265,11 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -291,7 +292,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -300,13 +301,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)) ->setNumeroAvisoLancamento($this->rem(116, 123, $trailer)); return true; @@ -316,7 +317,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Sicredi.php b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Sicredi.php index fd693cc6..9d5b4aa7 100644 --- a/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Sicredi.php +++ b/src/Cnab/Retorno/Cnab240/Cobranca/Banco/Sicredi.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Cobranca\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Sicredi extends AbstractRetorno implements RetornoCnab240 { @@ -103,12 +104,12 @@ class Sicredi extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -116,7 +117,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -145,7 +146,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -175,7 +176,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -188,24 +189,24 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17')) { $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); @@ -220,19 +221,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30', '36')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -240,12 +229,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -257,7 +246,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -266,13 +255,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); return true; } @@ -281,7 +270,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Detalhe.php b/src/Cnab/Retorno/Cnab240/Detalhe.php index fca803f0..869b473c 100644 --- a/src/Cnab/Retorno/Cnab240/Detalhe.php +++ b/src/Cnab/Retorno/Cnab240/Detalhe.php @@ -3,15 +3,15 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240; use Carbon\Carbon; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Detalhe as DetalheContract; -use VinicciusGuedes\LaravelCnab\Contracts\Pessoa as PessoaContract; -use VinicciusGuedes\LaravelCnab\MagicTrait; use VinicciusGuedes\LaravelCnab\Util; -use Exception; +use VinicciusGuedes\LaravelCnab\Pessoa; +use VinicciusGuedes\LaravelCnab\MagicTrait; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; +use VinicciusGuedes\LaravelCnab\Contracts\Pessoa as PessoaContract; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Detalhe as DetalheContract; class Detalhe implements DetalheContract { - use MagicTrait; /** @@ -68,6 +68,7 @@ class Detalhe implements DetalheContract * @var Carbon */ protected $dataOcorrencia; + /** * @var Carbon */ @@ -102,18 +103,22 @@ class Detalhe implements DetalheContract * @var string */ protected $valorIOF; + /** * @var string */ protected $valorAbatimento; + /** * @var string */ protected $valorDesconto; + /** * @var string */ protected $valorMora; + /** * @var string */ @@ -129,6 +134,21 @@ class Detalhe implements DetalheContract */ protected $cheques = []; + /** + * @var + */ + protected $id; + + /** + * @var + */ + protected $pixQrCode; + + /** + * @var + */ + protected $pixLocation; + /** * @var string */ @@ -143,7 +163,7 @@ public function getOcorrencia() } /** - * @return boolean + * @return bool */ public function hasOcorrencia() { @@ -167,7 +187,7 @@ public function hasOcorrencia() /** * @param string $ocorrencia * - * @return $this + * @return Detalhe */ public function setOcorrencia($ocorrencia) { @@ -187,7 +207,7 @@ public function getOcorrenciaTipo() /** * @param string $ocorrenciaTipo * - * @return $this + * @return Detalhe */ public function setOcorrenciaTipo($ocorrenciaTipo) { @@ -207,7 +227,7 @@ public function getOcorrenciaDescricao() /** * @param string $ocorrenciaDescricao * - * @return $this + * @return Detalhe */ public function setOcorrenciaDescricao($ocorrenciaDescricao) { @@ -248,7 +268,7 @@ public function getNumeroControle() /** * @param int $numeroControle * - * @return $this + * @return Detalhe */ public function setNumeroControle($numeroControle) { @@ -268,7 +288,7 @@ public function getNumeroDocumento() /** * @param string $numeroDocumento * - * @return $this + * @return Detalhe */ public function setNumeroDocumento($numeroDocumento) { @@ -288,7 +308,7 @@ public function getNossoNumero() /** * @param string $nossoNumero * - * @return $this + * @return Detalhe */ public function setNossoNumero($nossoNumero) { @@ -308,7 +328,7 @@ public function getCarteira() /** * @param string $carteira * - * @return $this + * @return Detalhe */ public function setCarteira($carteira) { @@ -334,7 +354,7 @@ public function getDataVencimento($format = 'd/m/Y') * * @param string $format * - * @return $this + * @return Detalhe */ public function setDataVencimento($dataVencimento, $format = 'dmY') { @@ -360,7 +380,7 @@ public function getDataCredito($format = 'd/m/Y') * * @param string $format * - * @return $this + * @return Detalhe */ public function setDataCredito($dataCredito, $format = 'dmY') { @@ -386,7 +406,7 @@ public function getDataOcorrencia($format = 'd/m/Y') * * @param string $format * - * @return $this + * @return Detalhe */ public function setDataOcorrencia($dataOcorrencia, $format = 'dmY') { @@ -406,7 +426,7 @@ public function getValor() /** * @param string $valor * - * @return $this + * @return Detalhe */ public function setValor($valor) { @@ -426,7 +446,7 @@ public function getValorIOF() /** * @param string $valorIOF * - * @return $this + * @return Detalhe */ public function setValorIOF($valorIOF) { @@ -446,7 +466,7 @@ public function getValorAbatimento() /** * @param string $valorAbatimento * - * @return $this + * @return Detalhe */ public function setValorAbatimento($valorAbatimento) { @@ -466,7 +486,7 @@ public function getValorDesconto() /** * @param string $valorDesconto * - * @return $this + * @return Detalhe */ public function setValorDesconto($valorDesconto) { @@ -486,7 +506,7 @@ public function getValorMora() /** * @param string $valorMora * - * @return $this + * @return Detalhe */ public function setValorMora($valorMora) { @@ -506,7 +526,7 @@ public function getValorMulta() /** * @param string $valorMulta * - * @return $this + * @return Detalhe */ public function setValorMulta($valorMulta) { @@ -526,7 +546,7 @@ public function getValorRecebido() /** * @param string $valorRecebido * - * @return $this + * @return Detalhe */ public function setValorRecebido($valorRecebido) { @@ -546,7 +566,7 @@ public function getValorTarifa() /** * @param string $valorTarifa * - * @return $this + * @return Detalhe */ public function setValorTarifa($valorTarifa) { @@ -566,7 +586,7 @@ public function getValorOutrasDespesas() /** * @param string $valorOutrasDespesas * - * @return $this + * @return Detalhe */ public function setValorOutrasDespesas($valorOutrasDespesas) { @@ -586,7 +606,7 @@ public function getValorOutrosCreditos() /** * @param string $valorOutrosCreditos * - * @return $this + * @return Detalhe */ public function setValorOutrosCreditos($valorOutrosCreditos) { @@ -606,8 +626,8 @@ public function getPagador() /** * @param $pagador * - * @return $this - * @throws Exception + * @return Detalhe + * @throws ValidationException */ public function setPagador($pagador) { @@ -646,7 +666,6 @@ public function setCheques(array $cheques) return $this; } - /** * @return string */ @@ -658,7 +677,7 @@ public function getError() /** * @param string $error * - * @return $this + * @return Detalhe */ public function setError($error) { @@ -687,4 +706,81 @@ public function setRejeicao($rejeicao) return $this; } + + /** + * @return mixed + */ + public function getId() + { + return $this->id; + } + + /** + * @param mixed $id + * @return Detalhe + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * @return mixed + */ + public function getPixQrCode() + { + return $this->pixQrCode; + } + + /** + * @param mixed $pixQrCode + * @return Detalhe + */ + public function setPixQrCode($pixQrCode) + { + $this->pixQrCode = $pixQrCode; + + return $this; + } + + /** + * @return mixed + */ + public function getPixLocation() + { + return $this->pixLocation; + } + + /** + * @param mixed $pixLocation + * @return Detalhe + */ + public function setPixLocation($pixLocation) + { + $this->pixLocation = $pixLocation; + + return $this; + } + + /** + * @param $nome + * @param $cidade + * @param bool $force + * @return string|null + * @throws ValidationException + */ + public function gerarPixCopiaECola($nome, $cidade, $force = false) + { + if ($this->getPixQrCode() && ! $force) { + return $this->getPixQrCode(); + } + + if ($this->getPixLocation() && $this->getValor() && $this->getID()) { + $this->setPixQrCode(Util::gerarPixCopiaECola($this->getPixLocation(), $this->getValor(), $this->getID(), new Pessoa(['nome' => Util::normalizeChars($nome), 'cidade' => Util::normalizeChars($cidade)]))); + } + + return $this->getPixQrCode(); + } } diff --git a/src/Cnab/Retorno/Cnab240/Header.php b/src/Cnab/Retorno/Cnab240/Header.php index 302cce66..e4f49156 100644 --- a/src/Cnab/Retorno/Cnab240/Header.php +++ b/src/Cnab/Retorno/Cnab240/Header.php @@ -3,14 +3,15 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240; use Carbon\Carbon; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Header as HeaderContract; use VinicciusGuedes\LaravelCnab\MagicTrait; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Header as HeaderContract; class Header implements HeaderContract { use MagicTrait; + /** - * @var integer + * @var int */ protected $codBanco; @@ -20,7 +21,7 @@ class Header implements HeaderContract protected $nomeBanco; /** - * @var integer + * @var int */ protected $codigoRemessaRetorno; @@ -48,6 +49,7 @@ class Header implements HeaderContract * @var string */ protected $agencia; + /** * @var string */ @@ -109,7 +111,7 @@ public function getLoteServico() /** * @param string $loteServico * - * @return $this + * @return Header */ public function setLoteServico($loteServico) { @@ -129,7 +131,7 @@ public function getTipoRegistro() /** * @param string $tipoRegistro * - * @return $this + * @return Header */ public function setTipoRegistro($tipoRegistro) { @@ -149,7 +151,7 @@ public function getTipoInscricao() /** * @param string $tipoInscricao * - * @return $this + * @return Header */ public function setTipoInscricao($tipoInscricao) { @@ -169,7 +171,7 @@ public function getAgencia() /** * @param string $agencia * - * @return $this + * @return Header */ public function setAgencia($agencia) { @@ -189,7 +191,7 @@ public function getAgenciaDv() /** * @param string $agenciaDv * - * @return $this + * @return Header */ public function setAgenciaDv($agenciaDv) { @@ -209,7 +211,7 @@ public function getNomeEmpresa() /** * @param string $nomeEmpresa * - * @return $this + * @return Header */ public function setNomeEmpresa($nomeEmpresa) { @@ -229,7 +231,7 @@ public function getHoraGeracao() /** * @param string $horaGeracao * - * @return $this + * @return Header */ public function setHoraGeracao($horaGeracao) { @@ -247,9 +249,8 @@ public function getNumeroSequencialArquivo() } /** - * * @param string $numeroSequencialArquivo - * @return $this + * @return Header */ public function setNumeroSequencialArquivo($numeroSequencialArquivo) { @@ -269,7 +270,7 @@ public function getVersaoLayoutArquivo() /** * @param string $versaoLayoutArquivo * - * @return $this + * @return Header */ public function setVersaoLayoutArquivo($versaoLayoutArquivo) { @@ -289,7 +290,7 @@ public function getNumeroInscricao() /** * @param string $numeroInscricao * - * @return $this + * @return Header */ public function setNumeroInscricao($numeroInscricao) { @@ -309,7 +310,7 @@ public function getConta() /** * @param string $conta * - * @return $this + * @return Header */ public function setConta($conta) { @@ -329,7 +330,7 @@ public function getContaDv() /** * @param string $contaDv * - * @return $this + * @return Header */ public function setContaDv($contaDv) { @@ -349,7 +350,7 @@ public function getCodigoCedente() /** * @param string $codigoCedente * - * @return $this + * @return Header */ public function setCodigoCedente($codigoCedente) { @@ -375,7 +376,7 @@ public function getData($format = 'd/m/Y') * * @param string $format * - * @return $this + * @return Header */ public function setData($data, $format = 'dmY') { @@ -395,7 +396,7 @@ public function getConvenio() /** * @param string $convenio * - * @return $this + * @return Header */ public function setConvenio($convenio) { @@ -415,7 +416,7 @@ public function getCodBanco() /** * @param int $codBanco * - * @return $this + * @return Header */ public function setCodBanco($codBanco) { @@ -435,7 +436,7 @@ public function getCodigoRemessaRetorno() /** * @param int $codigoRemessaRetorno * - * @return $this + * @return Header */ public function setCodigoRemessaRetorno($codigoRemessaRetorno) { @@ -455,7 +456,7 @@ public function getNomeBanco() /** * @param string $nomeBanco * - * @return $this + * @return Header */ public function setNomeBanco($nomeBanco) { diff --git a/src/Cnab/Retorno/Cnab240/HeaderLote.php b/src/Cnab/Retorno/Cnab240/HeaderLote.php index 2d4aaf9f..43895291 100644 --- a/src/Cnab/Retorno/Cnab240/HeaderLote.php +++ b/src/Cnab/Retorno/Cnab240/HeaderLote.php @@ -3,12 +3,13 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240; use Carbon\Carbon; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\HeaderLote as HeaderLoteContract; use VinicciusGuedes\LaravelCnab\MagicTrait; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\HeaderLote as HeaderLoteContract; class HeaderLote implements HeaderLoteContract { use MagicTrait; + /** * @var string */ @@ -120,7 +121,7 @@ public function getCodigoBanco() /** * @param string $codigoBanco * - * @return $this + * @return HeaderLote */ public function setCodigoBanco($codigoBanco) { @@ -140,7 +141,7 @@ public function getTipoRegistro() /** * @param string $tipoRegistro * - * @return $this + * @return HeaderLote */ public function setTipoRegistro($tipoRegistro) { @@ -160,7 +161,7 @@ public function getCodBanco() /** * @param string $codBanco * - * @return $this + * @return HeaderLote */ public function setCodBanco($codBanco) { @@ -180,7 +181,7 @@ public function getNumeroLoteRetorno() /** * @param string $numeroLoteRetorno * - * @return $this + * @return HeaderLote */ public function setNumeroLoteRetorno($numeroLoteRetorno) { @@ -198,9 +199,8 @@ public function getTipoOperacao() } /** - * * @param string $tipoOperacao - * @return $this + * @return HeaderLote */ public function setTipoOperacao($tipoOperacao) { @@ -209,7 +209,6 @@ public function setTipoOperacao($tipoOperacao) return $this; } - /** * @return string */ @@ -221,7 +220,7 @@ public function getTipoServico() /** * @param string $tipoServico * - * @return $this + * @return HeaderLote */ public function setTipoServico($tipoServico) { @@ -230,7 +229,6 @@ public function setTipoServico($tipoServico) return $this; } - /** * @return string */ @@ -242,7 +240,7 @@ public function getVersaoLayoutLote() /** * @param string $versaoLayoutLote * - * @return $this + * @return HeaderLote */ public function setVersaoLayoutLote($versaoLayoutLote) { @@ -251,7 +249,6 @@ public function setVersaoLayoutLote($versaoLayoutLote) return $this; } - /** * @return string */ @@ -261,10 +258,9 @@ public function getTipoInscricao() } /** - * * @param $tipoInscricao * - * @return $this + * @return HeaderLote */ public function setTipoInscricao($tipoInscricao) { @@ -273,7 +269,6 @@ public function setTipoInscricao($tipoInscricao) return $this; } - /** * @return string */ @@ -285,7 +280,7 @@ public function getNumeroInscricao() /** * @param string $numeroInscricao * - * @return $this + * @return HeaderLote */ public function setNumeroInscricao($numeroInscricao) { @@ -305,7 +300,7 @@ public function getCodigoCedente() /** * @param string $codigoCedente * - * @return $this + * @return HeaderLote */ public function setCodigoCedente($codigoCedente) { @@ -325,7 +320,7 @@ public function getConvenio() /** * @param string $convenio * - * @return $this + * @return HeaderLote */ public function setConvenio($convenio) { @@ -345,7 +340,7 @@ public function getNomeEmpresa() /** * @param string $nomeEmpresa * - * @return $this + * @return HeaderLote */ public function setNomeEmpresa($nomeEmpresa) { @@ -379,7 +374,7 @@ public function getDataGravacao($format = 'd/m/Y') * * @param string $format * - * @return $this + * @return HeaderLote */ public function setDataGravacao($dataGravacao, $format = 'dmY') { @@ -405,7 +400,7 @@ public function getDataCredito($format = 'd/m/Y') * * @param string $format * - * @return $this + * @return HeaderLote */ public function setDataCredito($dataCredito, $format = 'dmY') { @@ -425,7 +420,7 @@ public function getAgencia() /** * @param string $agencia * - * @return $this + * @return HeaderLote */ public function setAgencia($agencia) { @@ -434,7 +429,6 @@ public function setAgencia($agencia) return $this; } - /** * @return string */ @@ -446,7 +440,7 @@ public function getAgenciaDv() /** * @param string $agenciaDv * - * @return $this + * @return HeaderLote */ public function setAgenciaDv($agenciaDv) { @@ -466,7 +460,7 @@ public function getConta() /** * @param string $conta * - * @return $this + * @return HeaderLote */ public function setConta($conta) { @@ -486,7 +480,7 @@ public function getNumeroRetorno() /** * @param string $numeroRetorno * - * @return $this + * @return HeaderLote */ public function setNumeroRetorno($numeroRetorno) { @@ -506,7 +500,7 @@ public function getContaDv() /** * @param string $contaDv * - * @return $this + * @return HeaderLote */ public function setContaDv($contaDv) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Ailos.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Ailos.php new file mode 100644 index 00000000..86d65c28 --- /dev/null +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Ailos.php @@ -0,0 +1,361 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '12' => 'Confirmação Recebimento Instrução de Abatimento', + '13' => 'Confirmação Recebimento Instrução de Cancelamento Abatimento', + '14' => 'Confirmação Recebimento Instrução Alteração de Vencimento', + '17' => 'Liquidação Após Baixa ou Liquidação Título Não Registrado', + '19' => 'Confirmação Recebimento Instrução de Protesto', + '20' => 'Confirmação Recebimento Instrução de Sustação/Cancelamento de Protesto', + '22' => 'Título Enviado ao Cartório', + '23' => 'Remessa a Cartório (Aponte em Cartório)', + '24' => 'Retirada de Cartório e Manutenção em Carteira', + '25' => 'Protestado e Baixado (Baixa por Ter Sido Protestado) ', + '26' => 'Instrução Rejeitada', + '27' => 'Confirmação do Pedido de Alteração de Outros Dados ', + '28' => 'Débito de Tarifas/Custas', + '36' => 'Confirmação de envio de e-mail e SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '42' => 'Confirmação da alteração dos dados do Sacado', + '46' => 'Instrução para cancelar protesto confirmada', + '51' => 'Título DDA reconhecido pelo Pagador (quando o pagador aceitar o boleto depois de ter recusado)', + '52' => 'Título DDA não reconhecido pelo Pagador', + '76' => 'Liquidação CEE (boleto emitido na modalidade Cooperativa Emite e Expede)', + '77' => 'Liquidação após Baixa ou Liquidação Título Não Registrado CEE (boleto emitido na modalidade Cooperativa Emite e Expede)', + '89' => 'Rejeição cartorária (Visualizar motivo na última página deste manual)', + '91' => 'Título em aberto não enviado ao pagador', + '92' => 'Inconsistência Negativação Serasa', + '93' => 'Incluir Serasa', + '94' => 'Excluir Serasa', + '95' => 'Instrução de SMS', + '96' => 'Cancelamento Instrução SMS', + '97' => 'Confirmação de instrução automática de protesto', + '98' => 'Excluir Protesto com carta de anuência', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '01' => "Código do Banco Inválido", + '02' => "Código do Registro Detalhe Inválido", + '03' => "Código do Segmento Inválido", + '04' => "Código de Movimento Não Permitido para Carteira", + '05' => "Código de Movimento Inválido", + '06' => "Tipo/Número de Inscrição do Cedente Inválidos", + '07' => "Agência/Conta/DV Inválido", + '08' => "Nosso Número Inválido", + '09' => "Nosso Número Duplicado", + '10' => "Carteira Inválida", + '11' => "Forma de Cadastramento do Título Inválido", + '12' => "Tipo de Documento Inválido", + '13' => "Identificação da Emissão do Boleto Inválida", + '14' => "Identificação da Distribuição do Boleto Inválida", + '15' => "Características da Cobrança Incompatíveis", + '16' => "Data de Vencimento Inválida", + '17' => "Data de Vencimento Anterior à Data de Emissão", + '18' => "Vencimento Fora do Prazo de Operação", + '19' => "Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias", + '20' => "Valor do Título Inválido", + '21' => "Espécie do Título Inválida", + '22' => "Espécie do Título Não Permitida para a Carteira", + '23' => "Aceite Inválido", + '24' => "Data da Emissão Inválida", + '25' => "Data da Emissão Posterior a Data de Entrada", + '26' => "Código de Juros de Mora Inválido", + '27' => "Vlr/Taxa de Juros de Mora Inválido", + '28' => "Código do Desconto Inválido", + '29' => "Valor do Desconto Maior ou Igual ao Valor do Título", + '30' => "Desconto a Conceder Não Confere", + '31' => "Concessão de Desconto - Já Existe Desconto Anterior", + '33' => "Valor do Abatimento Inválido", + '34' => "Valor do Abatimento Maior ou Igual ao Valor do Título", + '35' => "Valor a Conceder Não Confere", + '36' => "Concessão de Abatimento - Já Existe Abatimento Anterior", + '37' => "Código para Protesto Inválido", + '38' => "Prazo para Protesto Inválido", + '39' => "Pedido de Protesto Não Permitido para o Título", + '40' => "Título com Ordem de Protesto Emitida", + '41' => "Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto", + '42' => "Código para Baixa/Devolução Inválido", + '43' => "Prazo para Baixa/Devolução Inválido", + '44' => "Código da Moeda Inválido", + '45' => "Nome do Sacado Não Informado", + '46' => "Tipo/Número de Inscrição do Sacado Inválidos", + '47' => "Endereço do Sacado Não Informado", + '48' => "CEP Inválido", + '49' => "CEP Sem Praça de Cobrança (Não Localizado)", + '50' => "CEP Referente a um Banco Correspondente", + '51' => "CEP incompatível com a Unidade da Federação", + '52' => "Unidade da Federação Inválida", + '53' => "Tipo/Número de Inscrição do Sacador/Avalista Inválidos", + '54' => "Sacador/Avalista Não Informado", + '55' => "Nosso número no Banco Correspondente Não Informado", + '56' => "Código do Banco Correspondente Não Informado", + '57' => "Código da Multa Inválido", + '58' => "Data da Multa Inválida", + '59' => "Valor/Percentual da Multa Inválido", + '60' => "Movimento para Título Não Cadastrado", + '61' => "Alteração da Agência Cobradora/DV Inválida", + '62' => "Tipo de Impressão Inválido", + '63' => "Entrada para Título já cadastrado", + '64' => "Número da Linha Inválido", + '65' => "Código do Banco para Débito Inválido", + '66' => "Agência/Conta/DV para Débito Inválido", + '79' => "Data Juros de Mora Inválido", + '80' => "Data do Desconto Inválida", + '86' => "Seu Número Inválido", + '89' => "E-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto", + '91' => "E-mail/número do celular do sacado não informado", + '96' => "Número do Convenio invalido", + '97' => "Rejeição da alteração do prazo limite de recebimento", + '98' => "Rejeição de dispensa de prazo limite de recebimento", + '99' => "Rejeição da alteração do número do título dado pelo cedente", + 'A2' => "Rejeição da alteração dos dados do sacado", + 'A4' => "Sacado DDA", + 'A3' => "Rejeição da alteração dos dados do sacador/avalista", + 'A4R1' => "Sacado DDA / Registro online", + 'A4P1' => "Sacado DDA / Envio Cooperativa E/E PJ", + 'A5' => "Registro Rejeitado - Título já Liquidado", + 'A7' => "Título já se encontra na situação Pretendida", + 'A8' => "Título pendente na CIP (Existe uma instrução pendente de processamento na CIP)", + 'A9' => "Título pendente na CIP (título é DDA e não possui número de identificação na CIP)", + 'BI' => "Beneficiário Divergente", + 'B3' => "Tipo de Pagamento Invalido", + 'B4' => "Vlr Max/Perc Invalido", + 'B5' => "Vlr Min/Perc Invalido", + 'B6' => "Parâmetro Pag. Divergente não habilitado no convênio de cobrança", + 'H3' => "Dias para prot. Inv. Min/máx (Número de dias de protesto está fora do limite mínimo e máximo parametrizados)", + 'H4' => "Prazo prot. Inv. (Prazo para protesto inválido)", + 'H6' => "Prot. não habilitado (Cooperado não está habilitado a protestar)", + 'NP' => "Boleto não protestado devido ao CEP do pagador incorreto", + 'P1' => "Enviado Cooperativa Emite e Expede", + 'PC' => "Boleto PCR (pagador não possui DDA ativo)", + 'R1' => "Registro Online", + 'S1' => "Cancelamento de Instrução de negativação não processada", + 'XA' => "Título em processo de registro", + 'XW' => "Serviço de SMS não contratado", + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setCodBanco($this->rem(1, 3, $header)) + ->setLoteServico($this->rem(4, 7, $header)) + ->setTipoRegistro($this->rem(8, 8, $header)) + ->setTipoInscricao($this->rem(18, 18, $header)) + ->setNumeroInscricao($this->rem(19, 32, $header)) + ->setCodigoCedente($this->rem(33, 52, $header)) + ->setAgencia($this->rem(53, 57, $header)) + ->setAgenciaDv($this->rem(58, 58, $header)) + ->setConta($this->rem(59, 70, $header)) + ->setContaDv($this->rem(71, 71, $header)) + ->setNomeEmpresa($this->rem(73, 102, $header)) + ->setNomeBanco($this->rem(103, 132, $header)) + ->setCodigoRemessaRetorno($this->rem(143, 143, $header)) + ->setData($this->rem(144, 151, $header)) + ->setNumeroSequencialArquivo($this->rem(158, 163, $header)) + ->setVersaoLayoutArquivo($this->rem(164, 166, $header)); + + return true; + } + + /** + * @param array $headerLote + * + * @return bool + * @throws ValidationException + */ + protected function processarHeaderLote(array $headerLote) + { + $this->getHeaderLote() + ->setCodBanco($this->rem(1, 3, $headerLote)) + ->setNumeroLoteRetorno($this->rem(4, 7, $headerLote)) + ->setTipoRegistro($this->rem(8, 8, $headerLote)) + ->setTipoOperacao($this->rem(9, 9, $headerLote)) + ->setTipoServico($this->rem(10, 11, $headerLote)) + ->setVersaoLayoutLote($this->rem(14, 16, $headerLote)) + ->setTipoInscricao($this->rem(18, 18, $headerLote)) + ->setNumeroInscricao($this->rem(19, 33, $headerLote)) + ->setCodigoCedente($this->rem(34, 53, $headerLote)) + ->setAgencia($this->rem(54, 58, $headerLote)) + ->setAgenciaDv($this->rem(59, 59, $headerLote)) + ->setConta($this->rem(60, 71, $headerLote)) + ->setContaDv($this->rem(72, 72, $headerLote)) + ->setNomeEmpresa($this->rem(74, 103, $headerLote)) + ->setNumeroRetorno($this->rem(184, 191, $headerLote)) + ->setDataGravacao($this->rem(192, 199, $headerLote)) + ->setDataCredito($this->rem(200, 207, $headerLote)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + if ($this->getSegmentType($detalhe) == 'T') { + $d->setOcorrencia($this->rem(16, 17, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $this->detalheAtual()->getOcorrencia(), 'Desconhecida')) + ->setNossoNumero($this->rem(38, 57, $detalhe)) + ->setCarteira($this->rem(58, 58, $detalhe)) + ->setNumeroDocumento($this->rem(59, 73, $detalhe)) + ->setDataVencimento($this->rem(74, 81, $detalhe)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) + ->setNumeroControle($this->rem(106, 130, $detalhe)) + ->setPagador([ + 'nome' => $this->rem(149, 188, $detalhe), + 'documento' => $this->rem(134, 148, $detalhe), + ]) + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); + + /** + * ocorrencias + */ + $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '17')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + $d->getPagador()->setDda(true); + } + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('25')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('27', '14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '26', '30', '36')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + } + + if ($this->getSegmentType($detalhe) == 'U') { + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setDataOcorrencia($this->rem(138, 145, $detalhe)) + ->setDataCredito($this->rem(146, 153, $detalhe)); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailerLote(array $trailer) + { + $this->getTrailerLote() + ->setLoteServico($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) + ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setNumeroLote($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdLotesArquivo((int) $this->rem(18, 23, $trailer)) + ->setQtdRegistroArquivo((int) $this->rem(24, 29, $trailer)); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bancoob.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bancoob.php index 4c074af3..6b545e23 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bancoob.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bancoob.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Bancoob extends AbstractRetorno implements RetornoCnab240 { @@ -201,12 +202,12 @@ class Bancoob extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -214,7 +215,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -244,7 +245,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -274,7 +275,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -293,34 +294,33 @@ protected function processarDetalhe(array $detalhe) * * Para voltar a considerar 10 digitos voltar trecho de código. * ////->setNossoNumero($this->rem(38, 47, $detalhe)) - * */ - if ( $this->rem(38, 39, $detalhe) != "00"){ - throw new \Exception("Verificar arquivo retorno: O nosso número no arquivo de retorno é maior que 7 dígitos."); + if ($this->rem(38, 39, $detalhe) != '00') { + throw new ValidationException('Verificar arquivo retorno: O nosso número no arquivo de retorno é maior que 7 dígitos.'); } $d->setNossoNumero($this->rem(40, 47, $detalhe)) ->setNossoNumero($this->rem(38, 47, $detalhe)) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%010s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17', '50')) { $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); @@ -335,19 +335,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -355,11 +343,11 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -371,7 +359,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -380,13 +368,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); return true; } @@ -395,7 +383,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Banrisul.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Banrisul.php index 317d704d..1df29a43 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Banrisul.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Banrisul.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Banrisul extends AbstractRetorno implements RetornoCnab240 { @@ -49,7 +50,6 @@ class Banrisul extends AbstractRetorno implements RetornoCnab240 'AC' => 'Situação do Título – Cartório', ]; - /** * Array com as possiveis descricoes de baixa e liquidacao. * @@ -71,7 +71,6 @@ class Banrisul extends AbstractRetorno implements RetornoCnab240 'AA' => 'Baixa por Pagamento', ]; - /** * Array com as possiveis rejeicoes do banco. * @@ -151,12 +150,12 @@ class Banrisul extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -164,7 +163,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -193,7 +192,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -223,7 +222,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -236,59 +235,33 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('09')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('25')) { $this->totais['protestados']++; @@ -298,19 +271,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -318,12 +279,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -335,7 +296,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -344,13 +305,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); return true; } @@ -359,7 +320,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bb.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bb.php index cb3d83fb..ddef8fc0 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bb.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bb.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Bb extends AbstractRetorno implements RetornoCnab240 { @@ -207,12 +208,12 @@ class Bb extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -220,7 +221,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -249,7 +250,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -279,7 +280,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -292,59 +293,33 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('09')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('25')) { $this->totais['protestados']++; @@ -354,19 +329,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -374,14 +337,14 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(108, 122, $detalhe)/100, 2, false)) - ->setValorOutrosCreditos(Util::nFloat($this->rem(123, 137, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(108, 122, $detalhe) / 100, 2, false)) + ->setValorOutrosCreditos(Util::nFloat($this->rem(123, 137, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -393,7 +356,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -409,7 +372,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bradesco.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bradesco.php index 39887cc9..6974405f 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bradesco.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Bradesco.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Bradesco extends AbstractRetorno implements RetornoCnab240 { @@ -173,12 +174,12 @@ class Bradesco extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -186,7 +187,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -215,7 +216,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -245,7 +246,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -317,7 +318,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -341,7 +342,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Btg.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Btg.php new file mode 100644 index 00000000..afe536c6 --- /dev/null +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Btg.php @@ -0,0 +1,465 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Transferência de Carteira/Entrada', + '05' => 'Transferência de Carteira/Baixa', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '11' => 'Títulos em Carteira (Em Ser)', + '12' => 'Confirmação Recebimento Instrução de Abatimento', + '13' => 'Confirmação Recebimento Instrução de Cancelamento Abatimento', + '14' => 'Confirmação Recebimento Instrução Alteração de Vencimento', + '15' => 'Franco de Pagamento', + '17' => 'Liquidação Após Baixa ou Liquidação Título Não Registrado', + '19' => 'Confirmação Recebimento Instrução de Protesto', + '20' => 'Confirmação Recebimento Instrução de Sustação/Cancelamento de Protesto', + '23' => 'Remessa a Cartório (Aponte em Cartório)', + '24' => 'Retirada de Cartório e Manutenção em Carteira', + '25' => 'Protestado e Baixado (Baixa por Ter Sido Protestado)', + '26' => 'Instrução Rejeitada', + '27' => 'Confirmação do Pedido de Alteração de Outros Dados', + '28' => 'Débito de Tarifas/Custas', + '29' => 'Ocorrências do Pagador', + '30' => 'Alteração de Dados Rejeitada', + '33' => 'Confirmação da Alteração dos Dados do Rateio de Crédito', + '34' => 'Confirmação do Cancelamento dos Dados do Rateio de Crédito', + '35' => 'Confirmação do Desagendamento do Débito Automático', + '36' => 'Confirmação de envio de e-mail/SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '38' => 'Confirmação de alteração do Prazo Limite de Recebimento (a data deve ser informada no campo 28.3.p)', + '39' => 'Confirmação de Dispensa de Prazo Limite de Recebimento', + '40' => 'Confirmação da alteração do número do título dado pelo Beneficiário', + '41' => 'Confirmação da alteração do número controle do Participante', + '42' => 'Confirmação da alteração dos dados do Pagador', + '43' => 'Confirmação da alteração dos dados do Sacador/Avalista', + '44' => 'Título pago com cheque devolvido', + '45' => 'Título pago com cheque compensado', + '46' => 'Instrução para cancelar protesto confirmada', + '47' => 'Instrução para protesto para fins falimentares confirmada', + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança', + '49' => 'Alteração de contrato de cobrança', + '50' => 'Título pago com cheque pendente de liquidação', + '51' => 'Título DDA reconhecido pelo Pagador', + '52' => 'Título DDA não reconhecido pelo Pagador', + '53' => 'Título DDA recusado pela CIP', + '54' => 'Confirmação da Instrução de Baixa de Título Negativado sem Protesto', + '55' => 'Confirmação de Pedido de Dispensa de Multa', + '56' => 'Confirmação do Pedido de Cobrança de Multa', + '57' => 'Confirmação do Pedido de Alteração de Cobrança de Juros', + '58' => 'Confirmação do Pedido de Alteração do Valor/Data de Desconto', + '59' => 'Confirmação do Pedido de Alteração do Beneficiário do Título', + '60' => 'Confirmação do Pedido de Dispensa de Juros de Mora', + '61' => 'Confirmação de Alteração do Valor Nominal do Título', + '63' => 'Título Sustado Judicialmente', + '64' => 'Confirmação de alteração do valor mínimo/percentual', + '65' => 'Confirmação de alteração do valor máximo/percentual', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '02032630' => [ + '01' => 'Código do Banco Inválido', + '02' => 'Código do Registro Detalhe Inválido', + '03' => 'Código do Segmento Inválido', + '04' => 'Código de Movimento Não Permitido para Carteira', + '05' => 'Código de Movimento Inválido', + '06' => 'Tipo/Número de Inscrição do Beneficiário Inválidos', + '07' => 'Agência/Conta/DV Inválido', + '08' => 'Nosso Número Inválido', + '09' => 'Nosso Número Duplicado', + '10' => 'Carteira Inválida', + '11' => 'Forma de Cadastramento do Título Inválido', + '12' => 'Tipo de Documento Inválido', + '13' => 'Identificação da Emissão do Boleto de Pagamento Inválida', + '14' => 'Identificação da Distribuição do Boleto de Pagamento Inválida', + '15' => 'Características da Cobrança Incompatíveis', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior a Data de Emissão', + '18' => 'Vencimento Fora do Prazo de Operação', + '19' => 'Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias', + '20' => 'Valor do Título Inválido', + '21' => 'Espécie do Título Inválida', + '22' => 'Espécie do Título Não Permitida para a Carteira', + '23' => 'Aceite Inválido', + '24' => 'Data da Emissão Inválida', + '25' => 'Data da Emissão Posterior a Data de Entrada', + '26' => 'Código de Juros de Mora Inválido', + '27' => 'Valor/Taxa de Juros de Mora Inválido', + '28' => 'Código do Desconto Inválido', + '29' => 'Valor do Desconto Maior ou Igual ao Valor do Título', + '30' => 'Desconto a Conceder Não Confere', + '31' => 'Concessão de Desconto - Já Existe Desconto Anterior', + '32' => 'Valor do IOF Inválido', + '33' => 'Valor do Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do Título', + '35' => 'Valor a Conceder Não Confere', + '36' => 'Concessão de Abatimento - Já Existe Abatimento Anterior', + '37' => 'Código para Protesto Inválido', + '38' => 'Prazo para Protesto Inválido', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto', + '42' => 'Código para Baixa/Devolução Inválido', + '43' => 'Prazo para Baixa/Devolução Inválido', + '44' => 'Código da Moeda Inválido', + '45' => 'Nome do Pagador Não Informado', + '46' => 'Tipo/Número de Inscrição do Pagador Inválidos', + '47' => 'Endereço do Pagador Não Informado', + '48' => 'CEP Inválido', + '49' => 'CEP Sem Praça de Cobrança (Não Localizado)', + '50' => 'CEP Referente a um Banco Correspondente', + '51' => 'CEP incompatível com a Unidade da Federação', + '52' => 'Unidade da Federação Inválida', + '53' => 'Tipo/Número de Inscrição do Sacador/Avalista Inválidos', + '54' => 'Sacador/Avalista Não Informado', + '55' => 'Nosso número no Banco Correspondente Não Informado', + '56' => 'Código do Banco Correspondente Não Informado', + '57' => 'Código da Multa Inválido', + '58' => 'Data da Multa Inválida', + '59' => 'Valor/Percentual da Multa Inválido', + '60' => 'Movimento para Título Não Cadastrado', + '61' => 'Alteração da Agência Cobradora/DV Inválida', + '62' => 'Tipo de Impressão Inválido', + '63' => 'Entrada para Título já Cadastrado', + '64' => 'Número da Linha Inválido', + '65' => 'Código do Banco para Débito Inválido', + '66' => 'Agência/Conta/DV para Débito Inválido', + '67' => 'Dados para Débito incompatível com a Identificação da Emissão do Boleto de Pagamento', + '68' => 'Débito Automático Agendado', + '69' => 'Débito Não Agendado - Erro nos Dados da Remessa', + '70' => 'Débito Não Agendado - Pagador Não Consta do Cadastro de Autorizante', + '71' => 'Débito Não Agendado - Beneficiário Não Autorizado pelo Pagador', + '72' => 'Débito Não Agendado - Beneficiário Não Participa da Modalidade Débito Automático', + '73' => 'Débito Não Agendado - Código de Moeda Diferente de Real (R$)', + '74' => 'Débito Não Agendado - Data Vencimento Inválida', + '75' => 'Débito Não Agendado, Conforme seu Pedido, Título Não Registrado', + '76' => 'Débito Não Agendado, Tipo/Num. Inscrição do Debitado, Inválido', + '77' => 'Transferência para Desconto Não Permitida para a Carteira do Título', + '78' => 'Data Inferior ou Igual ao Vencimento para Débito Automático', + '79' => 'Data Juros de Mora Inválido', + '80' => 'Data do Desconto Inválida', + '81' => 'Tentativas de Débito Esgotadas - Baixado', + '82' => 'Tentativas de Débito Esgotadas - Pendente', + '83' => 'Limite Excedido', + '84' => 'Número Autorização Inexistente', + '85' => 'Título com Pagamento Vinculado', + '86' => 'Seu Número Inválido', + '87' => 'e-mail/SMS enviado', + '88' => 'e-mail Lido', + '89' => 'e-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto', + '90' => 'e-mail devolvido - caixa postal cheia', + '91' => 'e-mail/número do celular do Pagador não informado', + '92' => 'Pagador optante por Boleto de Pagamento Eletrônico - e-mail não enviado', + '93' => 'Código para emissão de Boleto de Pagamento não permite envio de e-mail', + '94' => 'Código da Carteira inválido para envio e-mail.', + '95' => 'Contrato não permite o envio de e-mail', + '96' => 'Número de contrato inválido', + '97' => 'Rejeição da alteração do prazo limite de recebimento (a data deve ser informada no campo 28.3.p)', + '98' => 'Rejeição de dispensa de prazo limite de recebimento', + '99' => 'Rejeição da alteração do número do título dado pelo Beneficiário', + 'A1' => 'Rejeição da alteração do número controle do participante', + 'A2' => 'Rejeição da alteração dos dados do Pagador', + 'A3' => 'Rejeição da alteração dos dados do Sacador/avalista', + 'A4' => 'Pagador DDA', + 'A5' => 'Registro Rejeitado – Título já Liquidado', + 'A6' => 'Código do Convenente Inválido ou Encerrado', + 'A7' => 'Título já se encontra na situação Pretendida', + 'A8' => 'Valor do Abatimento inválido para cancelamento', + 'A9' => 'Não autoriza pagamento parcial', + 'B1' => 'Autoriza recebimento parcial', + 'B2' => 'Valor Nominal do Título Conflitante', + 'B3' => 'Tipo de Pagamento Inválido', + 'B4' => 'Valor Máximo/Percentual Inválido', + 'B5' => 'Valor Mínimo/Percentual Inválido', + ], + '28' => [ + '01' => 'Tarifa de Extrato de Posição', + '02' => 'Tarifa de Manutenção de Título Vencido', + '03' => 'Tarifa de Sustação', + '04' => 'Tarifa de Protesto', + '05' => 'Tarifa de Outras Instruções', + '06' => 'Tarifa de Outras Ocorrências', + '07' => 'Tarifa de Envio de Duplicata ao Pagador', + '08' => 'Custas de Protesto', + '09' => 'Custas de Sustação de Protesto', + '10' => 'Custas de Cartório Distribuidor', + '11' => 'Custas de Edital', + '12' => 'Tarifa Sobre Devolução de Título Vencido', + '13' => 'Tarifa Sobre Registro Cobrada na Baixa/Liquidação', + '14' => 'Tarifa Sobre Reapresentação Automática', + '15' => 'Tarifa Sobre Rateio de Crédito', + '16' => 'Tarifa Sobre Informações Via Fax', + '17' => 'Tarifa Sobre Prorrogação de Vencimento', + '18' => 'Tarifa Sobre Alteração de Abatimento/Desconto', + '19' => 'Tarifa Sobre Arquivo mensal (Em Ser)', + '20' => 'Tarifa Sobre Emissão de Boleto de Pagamento Pré-Emitido pelo Banco', + ], + '060917' => [ + '01' => 'Por Saldo', + '02' => 'Por Conta', + '03' => 'Liquidação no Guichê de Caixa em Dinheiro', + '04' => 'Compensação Eletrônica', + '05' => 'Compensação Convencional', + '06' => 'Por Meio Eletrônico', + '07' => 'Após Feriado Local', + '08' => 'Em Cartório', + '30' => 'Liquidação no Guichê de Caixa em Cheque', + '31' => 'Liquidação em banco correspondente', + '32' => 'Liquidação Terminal de Auto-Atendimento', + '33' => 'Liquidação na Internet (Home banking)', + '34' => 'Liquidado Office Banking', + '35' => 'Liquidado Correspondente em Dinheiro', + '36' => 'Liquidado Correspondente em Cheque', + '37' => 'Liquidado por meio de Central de Atendimento (Telefone)', + '09' => 'Comandada Banco', + '10' => 'Comandada Cliente Arquivo', + '11' => 'Comandada Cliente On-line', + '12' => 'Decurso Prazo - Cliente', + '13' => 'Decurso Prazo - Banco', + '14' => 'Protestado', + '15' => 'Título Excluído', + ], + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setCodBanco($this->rem(1, 3, $header)) + ->setLoteServico($this->rem(4, 7, $header)) + ->setTipoRegistro($this->rem(8, 8, $header)) + ->setTipoInscricao($this->rem(18, 18, $header)) + ->setNumeroInscricao($this->rem(19, 32, $header)) + ->setCodigoCedente($this->rem(33, 52, $header)) + ->setAgencia($this->rem(54, 57, $header)) + ->setAgenciaDv($this->rem(58, 58, $header)) + ->setConta($this->rem(66, 70, $header)) + ->setContaDv($this->rem(72, 72, $header)) + ->setNomeEmpresa($this->rem(73, 102, $header)) + ->setNomeBanco($this->rem(103, 132, $header)) + ->setCodigoRemessaRetorno($this->rem(143, 143, $header)) + ->setData($this->rem(144, 151, $header)) + ->setNumeroSequencialArquivo($this->rem(158, 163, $header)) + ->setVersaoLayoutArquivo($this->rem(164, 166, $header)); + + return true; + } + + /** + * @param array $headerLote + * + * @return bool + * @throws ValidationException + */ + protected function processarHeaderLote(array $headerLote) + { + $this->getHeaderLote() + ->setCodBanco($this->rem(1, 3, $headerLote)) + ->setNumeroLoteRetorno($this->rem(4, 7, $headerLote)) + ->setTipoRegistro($this->rem(8, 8, $headerLote)) + ->setTipoOperacao($this->rem(9, 9, $headerLote)) + ->setTipoServico($this->rem(10, 11, $headerLote)) + ->setVersaoLayoutLote($this->rem(14, 16, $headerLote)) + ->setTipoInscricao($this->rem(18, 18, $headerLote)) + ->setNumeroInscricao($this->rem(19, 33, $headerLote)) + ->setCodigoCedente($this->rem(34, 53, $headerLote)) + ->setAgencia($this->rem(54, 58, $headerLote)) + ->setAgenciaDv($this->rem(59, 59, $headerLote)) + ->setConta($this->rem(60, 71, $headerLote)) + ->setContaDv($this->rem(72, 72, $headerLote)) + ->setNomeEmpresa($this->rem(74, 103, $headerLote)) + ->setNumeroRetorno($this->rem(184, 191, $headerLote)) + ->setDataGravacao($this->rem(192, 199, $headerLote)) + ->setDataCredito($this->rem(200, 207, $headerLote)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + if ($this->getSegmentType($detalhe) == 'T') { + $d->setOcorrencia($this->rem(16, 17, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $this->detalheAtual()->getOcorrencia(), 'Desconhecida')) + ->setNossoNumero($this->rem(38, 57, $detalhe)) + ->setCarteira($this->rem(58, 58, $detalhe)) + ->setNumeroDocumento($this->rem(59, 73, $detalhe)) + ->setDataVencimento($this->rem(74, 81, $detalhe)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) + ->setNumeroControle($this->rem(106, 130, $detalhe)) + ->setPagador([ + 'nome' => $this->rem(149, 188, $detalhe), + 'documento' => $this->rem(134, 148, $detalhe), + ]) + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); + + /** + * ocorrencias + */ + $msgAdicional = str_split(sprintf('%010s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '17')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02', '04', '63')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('05', '09')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('25')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('40', '41', '42', '43', '61', '64', '65')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '26', '30', '37')) { + $this->totais['erros']++; + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + if ($d->hasOcorrencia('51')) { + $d->getPagador()->setDda(true); + } + + if ($d->hasOcorrencia('02', '03', '26', '30')) { + $error = Util::appendStrings( + Arr::get($this->rejeicoes['02032630'], $msgAdicional[0], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[1], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[2], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[3], ''), + Arr::get($this->rejeicoes['02032630'], $msgAdicional[4], '') + ); + $d->setError($error); + } + + if ($d->hasOcorrencia('28')) { + $error = Util::appendStrings( + Arr::get($this->rejeicoes['28'], $msgAdicional[0], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[1], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[2], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[3], ''), + Arr::get($this->rejeicoes['28'], $msgAdicional[4], '') + ); + $d->setError($error); + } + + if ($d->hasOcorrencia('06', '09', '17')) { + $error = Util::appendStrings( + Arr::get($this->rejeicoes['060917'], $msgAdicional[0], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[1], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[2], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[3], ''), + Arr::get($this->rejeicoes['060917'], $msgAdicional[4], '') + ); + $d->setError($error); + } + } + + if ($this->getSegmentType($detalhe) == 'U') { + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setDataOcorrencia($this->rem(138, 145, $detalhe)) + ->setDataCredito($this->rem(146, 153, $detalhe)); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailerLote(array $trailer) + { + $this->getTrailerLote() + ->setLoteServico($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) + ->setQtdTitulosCobrancaSimples((int) $this->rem(18, 23, $trailer)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(24, 41, $trailer) / 100, 2, false)); + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setNumeroLote($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdLotesArquivo((int) $this->rem(18, 23, $trailer)) + ->setQtdRegistroArquivo((int) $this->rem(24, 29, $trailer)); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Caixa.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Caixa.php index cd578ddc..fe5d3009 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Caixa.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Caixa.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Caixa extends AbstractRetorno implements RetornoCnab240 { @@ -353,12 +354,12 @@ class Caixa extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -366,7 +367,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -393,7 +394,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -421,7 +422,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -434,59 +435,33 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 69, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '46')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('09')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('25')) { $this->totais['protestados']++; @@ -496,19 +471,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30', '39', '40', '41')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -516,12 +479,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -533,7 +496,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -549,7 +512,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Cresol.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Cresol.php new file mode 100644 index 00000000..9850a3ca --- /dev/null +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Cresol.php @@ -0,0 +1,436 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Transferência de carteira/entrada', + '05' => 'Transferência de carteira/baixa', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '11' => 'Em Ser - Títulos em carteira', + '12' => 'Confirmação recebimento instrução de abatimento', + '13' => 'Confirmação recebimento instrução de cancelamento de abatimento', + '14' => 'Confirmação recebimento instrução alteração de vencimento', + '15' => 'Franco de pagamento', + '17' => 'Liquidação após baixa ou liquidação de título não registrado', + '19' => 'Confirmação Receb. Inst. de Protesto', + '20' => 'Confirmação recebimento instrução de sustação/cancelamento de protesto', + '23' => 'Remessa a cartório (aponte em cartório)', + '24' => 'Retirada de cartório e manutenção em carteira', + '25' => 'Protestado e baixado (baixa por ter sido protestado)', + '26' => 'Instrução rejeitada', + '27' => 'Confirmação do pedido de alteração de outros dados', + '28' => 'Débito de tarifas/custas', + '29' => 'Ocorrências do pagador', + '30' => 'Alteração de Outros Dados Rejeitados', + '33' => 'Confirmação da Alteração dos Dados do Rateio de Crédito', + '34' => 'Confirmação do Cancelamento dos Dados do Rateio de Crédito', + '35' => 'Confirmação do Desagendamento do Débito Automático', + '36' => 'Confirmação de envio de e-mail/SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '38' => 'Confirmação de alteração do Prazo Limite de Recebimento', + '39' => 'Confirmação de Dispensa de Prazo Limite de Recebimento', + '40' => 'Confirmação da alteração do número do título dado pelo cedente', + '41' => 'Confirmação da alteração do número controle do Participante', + '42' => 'Confirmação da alteração dos dados do Sacado', + '43' => 'Confirmação da alteração dos dados do Sacador/Avalista', + '44' => 'Título pago com cheque devolvido', + '45' => 'Título pago com cheque compensado', + '46' => 'Instrução para cancelar protesto confirmada', + '47' => 'Instrução para protesto para fins falimentares confirmada', + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança', + '49' => 'Alteração de contrato de cobrança', + '50' => 'Título pago com cheque pendente de liquidação', + '51' => 'Título DDA reconhecido pelo sacado', + '52' => 'Título DDA não reconhecido pelo sacado', + '53' => 'Título DDA recusado pela CIP', + '54' => 'Confirmação da Instrução de Baixa de Título Negativado sem Protesto', + '55' => 'Confirmação de Pedido de Dispensa de Multa', + '56' => 'Confirmação do Pedido de Cobrança de Multa', + '57' => 'Confirmação do Pedido de Alteração de Cobrança de Juros', + '58' => 'Confirmação do Pedido de Alteração do Valor/Data de Desconto', + '59' => 'Confirmação do Pedido de Alteração do Cedente do Título', + '60' => 'Confirmação do Pedido de Dispensa de Juros de Mora', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '1' => 'Código do Banco Inválido', + '2' => 'Código do Registro Detalhe Inválido', + '3' => 'Código do Segmento Inválido', + '4' => 'Código de Movimento Não Permitido para Carteira', + '5' => 'Código de Movimento Inválido', + '6' => 'Tipo/Número de Inscrição do Cedente Inválidos', + '7' => 'Agência/Conta/DV Inválido', + '8' => 'Nosso Número Inválido', + '9' => 'Nosso Número Duplicado', + '10' => 'Carteira Inválida', + '11' => 'Forma de Cadastramento do Título Inválido', + '12' => 'Tipo de Documento Inválido', + '13' => 'Identificação de Emissão do Bloqueto Inválida', + '14' => 'Identificação da Distribuição do Bloqueto Inválida', + '15' => 'Características da Cobrança Incompatíveis', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior a Data de Emissão', + '18' => 'Vencimento Fora do Prazo de Operação', + '19' => 'Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias', + '20' => 'Valor do Título Inválido', + '21' => 'Espécie do Título Inválida', + '22' => 'Espécie do Título Não Permitida para a Carteira', + '23' => 'Aceite Inválido', + '24' => 'Data de Emissão Inválida', + '25' => 'Data da Emissão Posterior a Data de Entrada', + '26' => 'Código de Juros de Mora Inválido', + '27' => 'Valor/Taxa de Juros de Mora Inválido', + '28' => 'Código do Desconto Inválido', + '29' => 'Valor do Desconto Maior ou Igual ao Valor do Título', + '30' => 'Desconto a Conceder Não Confere', + '31' => 'Concessão de Desconto - Já Existe Desconto Anterior', + '32' => 'Valor do IOF Inválido', + '33' => 'Valor do Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do Título', + '35' => 'Valor a Conceder Não Confere', + '36' => 'Concessão de Abatimento - Já Existe Abatimento Anterior', + '37' => 'Código para Protesto Inválido', + '38' => 'Prazo para Protesto Inválido', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto', + '42' => 'Código para Baixa/Devolução Inválido', + '43' => 'Prazo para Baixa/Devolução Inválida', + '44' => 'Código da Moeda Inválido', + '45' => 'Nome do Sacado Não Informado', + '46' => 'Tipo/Número de Inscrição do Sacado Inválido', + '47' => 'Endereço do Sacado Não Informado', + '48' => 'CEP Inválido', + '49' => 'CEP Sem Praça de Cobrança (Não Localizado)', + '50' => 'CEP Referente a um Banco Correspondente', + '51' => 'CEP imcompatível com a Unidade da Federação', + '52' => 'Registro de Título já liquidado Cart. 17', + '53' => 'Tipo/Número de Inscrição do Sacador/Avalista Inválidos', + '54' => 'Sacador/Avalista Não Informado', + '55' => 'Nosso Número no Banco Correspondente Não Informado', + '56' => 'Código do Banco Correspondente Não Informado', + '57' => 'Código da Multa Inválido', + '58' => 'Data da Multa Inválida', + '59' => 'Valor/Percentual da Multa Inválido', + '60' => 'Movimento para Título Não Cadastrado', + '61' => 'Alteração da Agência Cobradora/DV Inválida', + '62' => 'Tipo de Impressão Inválido', + '63' => 'Entrada para Título já Cadastrado', + '64' => 'Número da Linha Inválido', + '65' => 'Código do Banco para Débito Inválido', + '66' => 'Agência/Conta/DV para Débito Inválido', + '67' => 'Dados para Débito incompatível com a Identificação da Emissão do Bloqueto', + '68' => 'Débito Automático Agendado', + '69' => 'Débito Não Agendado - Erro nos Dados da Remessa', + '70' => 'Débito Não Agendado - Sacado Não Consta do Cadastro de Autorizante', + '71' => 'Débito Não Agendado - Cedente Não Autorizado pelo Sacado', + '72' => 'Débito Não Agendado - Cedente Não Participa da Modalidade Débito Automático', + '73' => 'Débito Não Agendado - Código de Moeda Diferente de Reao (R$)', + '74' => 'Débito Não Agendado - Data Vencimento Inválida', + '75' => 'Débito Não Agendado, Conforme seu Pedido, Título Não Registrado', + '76' => 'Débito Não Agendado, Tipo/Num. Inscrição do Debitado, Inválido', + '77' => 'Transferência para Desconto Não Permitida para a Cateira do Título', + '78' => 'Data Inferior ou Igual ao Vencimento para Débito Automático', + '79' => 'Data Juros de Mora Inválido', + '80' => 'Data do Desconto Inválida', + '81' => 'Tentativas de Débito Esgotadas - Baixado', + '82' => 'Tentativas de Débito Esgotadas - Pendente', + '83' => 'Limite Excedido', + '84' => 'Número Autorização Inexistente', + '85' => 'Título com Pagamento Vinculado', + '86' => 'Seu Número Inválido', + '87' => 'e-mail/SMS enviado', + '88' => 'e-mail Lido', + '89' => 'e-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto', + '90' => 'e-mail devolvido - caixa postal cheia', + '91' => 'e-mail/número do celular do sacado não informado', + '92' => 'Sacado optante por Bloqueto Eletrônico - e-mail não enviado', + '93' => 'Código para emissão de bloqueto não permite envio de e-mail', + '94' => 'Código da Carteira inválido para envio e-mail', + '95' => 'Contrato não permite o envio de e-mail', + '96' => 'Número de contrato inválido', + '97' => 'Rejeição da alteração do prazo limite de recebimento', + '98' => 'Rejeição de dispensa de prazo limite de recebimento', + '99' => 'Rejeição da alteração do número do título dado pelo cedente', + 'A1' => 'Rejeição da alteração do número controle do participante', + 'A2' => 'Rejeição da alteração dos dados do sacado', + 'A3' => 'Rejeição da alteração dos dados do sacador/avalista', + 'A4' => 'Sacado DDA', + 'A5' => 'Registro Rejeitado - Título já Liquidado', + 'A6' => 'Código do Convenente Inválido ou Encerrado', + 'A7' => 'Título se já encontra na situação Pretendida', + 'A8' => 'Valor do Abatimento inválido para cancelamento', + 'A9' => 'Não autoriza pagamento parcial', + 'B1' => 'Autoriza recebimento parcial', + ]; + + /** + * Array com as possiveis descricoes de baixa e liquidacao. + * + * @var array + */ + private $baixa_liquidacao = [ + '01' => 'Por Saldo', + '02' => 'Por Conta', + '03' => 'Liquidação no Guichê de Caixa em Dinheiro', + '04' => 'Compensação Eletrônica', + '05' => 'Compensação Convencional', + '06' => 'Por Meio Eletrônico', + '07' => 'Após Feriado Local', + '08' => 'Em Cartório', + '30' => 'Liquidação no Guichê de Caixa em Cheque', + '31' => 'Liquidação em banco correspondente', + '32' => 'Liquidação Terminal de Auto-Atendimento', + '33' => 'Liquidação na Internet (Home banking)', + '34' => 'Liquidado Office Banking', + '35' => 'Liquidado Correspondente em Dinheiro', + '36' => 'Liquidado Correspondente em Cheque', + '37' => 'Liquidado por meio de Central de Atendimento (Telefone) Baixa: PELO BANCO)', + '09' => 'Comandada Banco', + '10' => 'Comandada Cliente Arquivo', + '11' => 'Comandada Cliente On-line', + '12' => 'Decurso Prazo - Cliente', + '13' => 'Decurso Prazo - Banco', + '14' => 'Protestado', + '15' => 'Título Excluído', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws \Exception + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setCodBanco($this->rem(1, 3, $header)) + ->setLoteServico($this->rem(4, 7, $header)) + ->setTipoRegistro($this->rem(8, 8, $header)) + ->setTipoInscricao($this->rem(18, 18, $header)) + ->setNumeroInscricao($this->rem(19, 32, $header)) + ->setAgencia($this->rem(53, 57, $header)) + ->setAgenciaDv($this->rem(58, 58, $header)) + ->setConta($this->rem(59, 70, $header)) + ->setContaDv($this->rem(71, 71, $header)) +// ->setContaDv($this->rem(72, 72, $header)) + ->setNomeEmpresa($this->rem(73, 102, $header)) + ->setNomeBanco($this->rem(103, 132, $header)) + ->setCodigoRemessaRetorno($this->rem(143, 143, $header)) + ->setData($this->rem(144, 151, $header)) + ->setNumeroSequencialArquivo($this->rem(158, 163, $header)) + ->setVersaoLayoutArquivo($this->rem(164, 166, $header)); + + return true; + } + + /** + * @param array $headerLote + * + * @return bool + * @throws \Exception + */ + protected function processarHeaderLote(array $headerLote) + { + $this->getHeaderLote() + ->setCodBanco($this->rem(1, 3, $headerLote)) + ->setNumeroLoteRetorno($this->rem(4, 7, $headerLote)) + ->setTipoRegistro($this->rem(8, 8, $headerLote)) + ->setTipoOperacao($this->rem(9, 9, $headerLote)) + ->setTipoServico($this->rem(10, 11, $headerLote)) + ->setVersaoLayoutLote($this->rem(14, 16, $headerLote)) + ->setTipoInscricao($this->rem(18, 18, $headerLote)) + ->setNumeroInscricao($this->rem(19, 33, $headerLote)) + ->setAgencia($this->rem(54, 58, $headerLote)) + ->setAgenciaDv($this->rem(59, 59, $headerLote)) + ->setConta($this->rem(60, 71, $headerLote)) + ->setContaDv($this->rem(72, 72, $headerLote)) +// ->setContaDv($this->rem(73, 73, $headerLote)) + ->setNomeEmpresa($this->rem(74, 103, $headerLote)) + ->setNumeroRetorno($this->rem(184, 191, $headerLote)) + ->setDataGravacao($this->rem(192, 199, $headerLote)) + ->setDataCredito($this->rem(200, 207, $headerLote)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws \Exception + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + if ($this->getSegmentType($detalhe) == 'T') { + $d->setOcorrencia($this->rem(16, 17, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $this->detalheAtual()->getOcorrencia(), 'Desconhecida')) + ->setNossoNumero($this->rem(38, 57, $detalhe)) + ->setCarteira($this->rem(58, 58, $detalhe)) + ->setNumeroDocumento($this->rem(59, 73, $detalhe)) + ->setDataVencimento($this->rem(74, 81, $detalhe)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) + ->setNumeroControle($this->rem(106, 130, $detalhe)) + ->setPagador([ + 'nome' => $this->rem(149, 188, $detalhe), + 'documento' => $this->rem(134, 148, $detalhe), + ]) + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); + + /** + * ocorrencias + */ + $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '17')) { + $this->totais['liquidados']++; + $ocorrencia = Util::appendStrings( + $d->getOcorrenciaDescricao(), + Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), + Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') + ); + $d->setOcorrenciaDescricao($ocorrencia); + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + $d->getPagador()->setDda(true); + } + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09')) { + $this->totais['baixados']++; + $ocorrencia = Util::appendStrings( + $d->getOcorrenciaDescricao(), + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + $d->setOcorrenciaDescricao($ocorrencia); + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('25')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('33', '38', '40', '41', '42', '43', '49')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '26', '30')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + } + + if ($this->getSegmentType($detalhe) == 'U') { + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) + ->setDataOcorrencia($this->rem(138, 145, $detalhe)) + ->setDataCredito($this->rem(146, 153, $detalhe)); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws \Exception + */ + protected function processarTrailerLote(array $trailer) + { + $this->getTrailerLote() + ->setLoteServico($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) + ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) + ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws \Exception + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setNumeroLote($this->rem(4, 7, $trailer)) + ->setTipoRegistro($this->rem(8, 8, $trailer)) + ->setQtdLotesArquivo((int) $this->rem(18, 23, $trailer)) + ->setQtdRegistroArquivo((int) $this->rem(24, 29, $trailer)); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Itau.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Itau.php index c1ce72aa..13198159 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Itau.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Itau.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Itau extends AbstractRetorno implements RetornoCnab240 { @@ -153,12 +154,12 @@ class Itau extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -166,7 +167,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -193,7 +194,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -221,7 +222,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -293,7 +294,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -313,7 +314,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Santander.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Santander.php index 6b94e514..5120c5c2 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Santander.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Santander.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Santander extends AbstractRetorno implements RetornoCnab240 { @@ -185,12 +186,12 @@ class Santander extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -198,7 +199,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -227,7 +228,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -255,7 +256,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -338,7 +339,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -363,7 +364,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Sicredi.php b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Sicredi.php index 713f148f..f3969262 100644 --- a/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Sicredi.php +++ b/src/Cnab/Retorno/Cnab240/Pagamento/Banco/Sicredi.php @@ -2,11 +2,12 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\Pagamento\Banco; +use Illuminate\Support\Arr; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240\AbstractRetorno; use VinicciusGuedes\LaravelCnab\Contracts\Boleto\Boleto as BoletoContract; -use VinicciusGuedes\LaravelCnab\Contracts\Cnab\RetornoCnab240; -use VinicciusGuedes\LaravelCnab\Util; -use Illuminate\Support\Arr; class Sicredi extends AbstractRetorno implements RetornoCnab240 { @@ -103,12 +104,12 @@ class Sicredi extends AbstractRetorno implements RetornoCnab240 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -116,7 +117,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -145,7 +146,7 @@ protected function processarHeader(array $header) * @param array $headerLote * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeaderLote(array $headerLote) { @@ -175,7 +176,7 @@ protected function processarHeaderLote(array $headerLote) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -188,24 +189,24 @@ protected function processarDetalhe(array $detalhe) ->setCarteira($this->rem(58, 58, $detalhe)) ->setNumeroDocumento($this->rem(59, 73, $detalhe)) ->setDataVencimento($this->rem(74, 81, $detalhe)) - ->setValor(Util::nFloat($this->rem(82, 96, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(82, 96, $detalhe) / 100, 2, false)) ->setNumeroControle($this->rem(106, 130, $detalhe)) ->setPagador([ - 'nome' => $this->rem(149, 188, $detalhe), + 'nome' => $this->rem(149, 188, $detalhe), 'documento' => $this->rem(134, 148, $detalhe), ]) - ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe)/100, 2, false)); + ->setValorTarifa(Util::nFloat($this->rem(199, 213, $detalhe) / 100, 2, false)); /** * ocorrencias - */ + */ $msgAdicional = str_split(sprintf('%08s', $this->rem(214, 223, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '17')) { $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { $this->totais['entradas']++; - if(array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { + if (array_search('a4', array_map('strtolower', $msgAdicional)) !== false) { $d->getPagador()->setDda(true); } $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); @@ -220,19 +221,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '26', '30', '36')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -240,12 +229,12 @@ protected function processarDetalhe(array $detalhe) } if ($this->getSegmentType($detalhe) == 'U') { - $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe)/100, 2, false)) - ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe)/100, 2, false)) + $d->setValorMulta(Util::nFloat($this->rem(18, 32, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(33, 47, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(48, 62, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(63, 77, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(78, 92, $detalhe) / 100, 2, false)) + ->setValorTarifa($d->getValorRecebido() - Util::nFloat($this->rem(93, 107, $detalhe) / 100, 2, false)) ->setDataOcorrencia($this->rem(138, 145, $detalhe)) ->setDataCredito($this->rem(146, 153, $detalhe)); } @@ -257,7 +246,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailerLote(array $trailer) { @@ -266,13 +255,13 @@ protected function processarTrailerLote(array $trailer) ->setTipoRegistro($this->rem(8, 8, $trailer)) ->setQtdRegistroLote((int) $this->rem(18, 23, $trailer)) ->setQtdTitulosCobrancaSimples((int) $this->rem(24, 29, $trailer)) - ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaSimples(Util::nFloat($this->rem(30, 46, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaVinculada((int) $this->rem(47, 52, $trailer)) - ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaVinculada(Util::nFloat($this->rem(53, 69, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaCaucionada((int) $this->rem(70, 75, $trailer)) - ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer)/100, 2, false)) + ->setValorTotalTitulosCobrancaCaucionada(Util::nFloat($this->rem(76, 92, $trailer) / 100, 2, false)) ->setQtdTitulosCobrancaDescontada((int) $this->rem(93, 98, $trailer)) - ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer)/100, 2, false)); + ->setValorTotalTitulosCobrancaDescontada(Util::nFloat($this->rem(99, 115, $trailer) / 100, 2, false)); return true; } @@ -281,7 +270,7 @@ protected function processarTrailerLote(array $trailer) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab240/Trailer.php b/src/Cnab/Retorno/Cnab240/Trailer.php index c92648d2..308a56ae 100644 --- a/src/Cnab/Retorno/Cnab240/Trailer.php +++ b/src/Cnab/Retorno/Cnab240/Trailer.php @@ -2,29 +2,30 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240; -use \VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Trailer as TrailerContract; use VinicciusGuedes\LaravelCnab\MagicTrait; +use \VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\Trailer as TrailerContract; class Trailer implements TrailerContract { use MagicTrait; + /** - * @var integer + * @var int */ protected $numeroLote; /** - * @var integer + * @var int */ protected $tipoRegistro; /** - * @var integer + * @var int */ protected $qtdLotesArquivo; /** - * @var integer + * @var int */ protected $qtdRegistroArquivo; @@ -39,7 +40,7 @@ public function getTipoRegistro() /** * @param mixed $numeroLote * - * @return $this + * @return Trailer */ public function setNumeroLote($numeroLote) { @@ -59,7 +60,7 @@ public function getNumeroLoteRemessa() /** * @param mixed $qtdLotesArquivo * - * @return $this + * @return Trailer */ public function setQtdLotesArquivo($qtdLotesArquivo) { @@ -79,7 +80,7 @@ public function getQtdLotesArquivo() /** * @param mixed $qtdRegistroArquivo * - * @return $this + * @return Trailer */ public function setQtdRegistroArquivo($qtdRegistroArquivo) { @@ -99,7 +100,7 @@ public function getQtdRegistroArquivo() /** * @param mixed $tipoRegistro * - * @return $this + * @return Trailer */ public function setTipoRegistro($tipoRegistro) { diff --git a/src/Cnab/Retorno/Cnab240/TrailerLote.php b/src/Cnab/Retorno/Cnab240/TrailerLote.php index 7ee3bf4e..d41f3932 100644 --- a/src/Cnab/Retorno/Cnab240/TrailerLote.php +++ b/src/Cnab/Retorno/Cnab240/TrailerLote.php @@ -2,29 +2,30 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab240; -use \VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\TrailerLote as TrailerLoteContract; use VinicciusGuedes\LaravelCnab\MagicTrait; +use \VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab240\TrailerLote as TrailerLoteContract; class TrailerLote implements TrailerLoteContract { use MagicTrait; + /** - * @var integer + * @var int */ protected $loteServico; /** - * @var integer + * @var int */ protected $TipoRegistro; /** - * @var integer + * @var int */ protected $qtdRegistroLote; /** - * @var integer + * @var int */ protected $qtdTitulosCobrancaSimples; @@ -34,7 +35,7 @@ class TrailerLote implements TrailerLoteContract protected $valorTotalTitulosCobranca; /** - * @var integer + * @var int */ protected $qtdTitulosCobrancaVinculada; @@ -44,7 +45,7 @@ class TrailerLote implements TrailerLoteContract protected $valorTotalTitulosCobrancaVinculada; /** - * @var integer + * @var int */ protected $qtdTitulosCobrancaCaucionada; @@ -54,7 +55,7 @@ class TrailerLote implements TrailerLoteContract protected $valorTotalTitulosCobrancaCaucionada; /** - * @var integer + * @var int */ protected $qtdTitulosCobrancaDescontada; @@ -64,7 +65,7 @@ class TrailerLote implements TrailerLoteContract protected $valorTotalTitulosCobrancaDescontada; /** - * @var integer + * @var int */ protected $numeroAvisoLancamento; @@ -79,7 +80,7 @@ public function getLoteServico() /** * @param mixed $loteServico * - * @return $this + * @return TrailerLote */ public function setLoteServico($loteServico) { @@ -99,7 +100,7 @@ public function getNumeroAvisoLancamento() /** * @param mixed $numeroAvisoLancamento * - * @return $this + * @return TrailerLote */ public function setNumeroAvisoLancamento($numeroAvisoLancamento) { @@ -119,7 +120,7 @@ public function getQtdRegistroLote() /** * @param mixed $qtdRegistroLote * - * @return $this + * @return TrailerLote */ public function setQtdRegistroLote($qtdRegistroLote) { @@ -139,7 +140,7 @@ public function getQtdTitulosCobrancaCaucionada() /** * @param mixed $qtdTitulosCobrancaCaucionada * - * @return $this + * @return TrailerLote */ public function setQtdTitulosCobrancaCaucionada($qtdTitulosCobrancaCaucionada) { @@ -159,7 +160,7 @@ public function getQtdTitulosCobrancaDescontada() /** * @param mixed $qtdTitulosCobrancaDescontada * - * @return $this + * @return TrailerLote */ public function setQtdTitulosCobrancaDescontada($qtdTitulosCobrancaDescontada) { @@ -179,7 +180,7 @@ public function getQtdTitulosCobrancaSimples() /** * @param mixed $qtdTitulosCobrancaSimples * - * @return $this + * @return TrailerLote */ public function setQtdTitulosCobrancaSimples($qtdTitulosCobrancaSimples) { @@ -199,7 +200,7 @@ public function getQtdTitulosCobrancaVinculada() /** * @param mixed $qtdTitulosCobrancaVinculada * - * @return $this + * @return TrailerLote */ public function setQtdTitulosCobrancaVinculada($qtdTitulosCobrancaVinculada) { @@ -219,7 +220,7 @@ public function getTipoRegistro() /** * @param mixed $TipoRegistro * - * @return $this + * @return TrailerLote */ public function setTipoRegistro($TipoRegistro) { @@ -239,7 +240,7 @@ public function getValorTotalTitulosCobrancaSimples() /** * @param mixed $valorTotalTitulosCobranca * - * @return $this + * @return TrailerLote */ public function setValorTotalTitulosCobrancaSimples($valorTotalTitulosCobranca) { @@ -259,7 +260,7 @@ public function getValorTotalTitulosCobrancaCaucionada() /** * @param mixed $valorTotalTitulosCobrancaCaucionada * - * @return $this + * @return TrailerLote */ public function setValorTotalTitulosCobrancaCaucionada($valorTotalTitulosCobrancaCaucionada) { @@ -279,7 +280,7 @@ public function getValorTotalTitulosCobrancaDescontada() /** * @param mixed $valorTotalTitulosCobrancaDescontada * - * @return $this + * @return TrailerLote */ public function setValorTotalTitulosCobrancaDescontada($valorTotalTitulosCobrancaDescontada) { @@ -299,7 +300,7 @@ public function getValorTotalTitulosCobrancaVinculada() /** * @param mixed $valorTotalTitulosCobrancaVinculada * - * @return $this + * @return TrailerLote */ public function setValorTotalTitulosCobrancaVinculada($valorTotalTitulosCobrancaVinculada) { diff --git a/src/Cnab/Retorno/Cnab400/AbstractRetorno.php b/src/Cnab/Retorno/Cnab400/AbstractRetorno.php index a21161f9..f90dda4c 100644 --- a/src/Cnab/Retorno/Cnab400/AbstractRetorno.php +++ b/src/Cnab/Retorno/Cnab400/AbstractRetorno.php @@ -1,27 +1,25 @@ $this->header->toArray(), 'trailer' => $this->trailer->toArray(), - 'detalhes' => new Collection() + 'detalhes' => new Collection(), ]; foreach ($this->detalhe as $detalhe) { $array['detalhes']->push($detalhe->toArray()); } + return $array; } } diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bancoob.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bancoob.php index 0026b67f..6f0e5826 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bancoob.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bancoob.php @@ -1,11 +1,13 @@ 'Confirmação Entrada Título', '05' => 'Liquidação Sem Registro: Identifica a liquidação de título da modalidade ""SEM REGISTRO""', @@ -33,8 +34,9 @@ class Bancoob extends AbstractRetorno implements RetornoCnab400 '15' => 'Liquidação em Cartório: Identifica as liquidações dos títulos ocorridas em cartórios de protesto', '23' => 'Encaminhado a Protesto: Identifica o recebimento da instrução de protesto', '27' => 'Confirmação Alteração Dados.', - '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança"' + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança"', ]; + /** * Array com as possiveis rejeicoes do banco. * @@ -67,7 +69,7 @@ class Bancoob extends AbstractRetorno implements RetornoCnab400 '73' => 'Débito não agendado – Data de vencimento inválida', '74' => 'Débito não agendado – Conforme seu pedido, Título não registrado', '75' => 'Débito não agendado – Tipo de número de inscrição do debitado inválido', -]; + ]; /** * Roda antes dos metodos de processar @@ -75,11 +77,11 @@ class Bancoob extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -87,7 +89,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -110,7 +112,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -125,14 +127,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(176, 181, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('05', '06')) { @@ -150,21 +152,9 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('14')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { + } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -177,7 +167,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Banrisul.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Banrisul.php index e69d0ca7..c9f41f4c 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Banrisul.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Banrisul.php @@ -1,15 +1,16 @@ 'Cancelamento dos dados do rateio', ]; - /** * Array com as possiveis descricoes de baixa e liquidacao. * @@ -146,12 +146,12 @@ class Banrisul extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'erros' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'erros' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -159,7 +159,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -179,7 +179,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -194,13 +194,13 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(296, 301, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); /** * ocorrencias @@ -208,42 +208,16 @@ protected function processarDetalhe(array $detalhe) $msgAdicional = str_split(sprintf('%010s', $this->rem(383, 392, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '25', '08')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02', '47')) { $this->totais['entradas']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('04', '08', '10')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('40')) { $this->totais['protestados']++; @@ -265,16 +239,16 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeTitulos((int) $this->rem(18, 25, $trailer)) ->setQuantidadeErros((int) $this->totais['erros']) - ->setQuantidadeEntradas((int) $this->rem(49, 55, $trailer)) - ->setQuantidadeLiquidados((int) $this->rem(71, 77, $trailer)) + ->setQuantidadeEntradas((int) $this->rem(49, 55, $trailer)) + ->setQuantidadeLiquidados((int) $this->rem(71, 77, $trailer)) ->setQuantidadeBaixados((int) $this->totais['baixados']) ->setQuantidadeAlterados((int) $this->totais['alterados']); diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bb.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bb.php index bd26df67..c40a470e 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bb.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bb.php @@ -1,11 +1,13 @@ totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -174,7 +176,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -197,7 +199,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -216,15 +218,15 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(176, 181, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); if ($d->hasOcorrencia('05', '06', '07', '08', '15')) { $this->totais['liquidados']++; @@ -255,12 +257,12 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeTitulos((int) $this->rem(18, 25, $trailer)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bnb.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bnb.php index c3db215b..18a38c2d 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bnb.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bnb.php @@ -1,11 +1,13 @@ 'Erro ocorrencia 19', '70' => 'Erro ocorrencia 20', '71' => 'Erro ocorrencia 21', - '72' => 'Erro ocorrencia 22' + '72' => 'Erro ocorrencia 22', ]; /** @@ -65,12 +67,12 @@ class Bnb extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -78,7 +80,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -99,14 +101,14 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { $d = $this->detalheAtual(); // Verifica data de crédotp (não vem no retorno mas uso pra saber se foi liquidado) if ($this->rem(254, 266, $detalhe) == '0000000000000') { - $dataCredito = ""; + $dataCredito = ''; } else { $dataCredito = $this->rem(111, 116, $detalhe); } @@ -119,13 +121,13 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($dataCredito) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) ->setValorIOF(Util::nFloat(0.00, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) ->setValorMulta(Util::nFloat(0.00, 2, false)); if ($d->hasOcorrencia('06', '07', '08')) { @@ -157,13 +159,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos((int) $this->rem(18, 25, $trailer)) - ->setValorTitulos((float) Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos((float) Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bradesco.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bradesco.php index 0c380d59..8f955ae4 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bradesco.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Bradesco.php @@ -1,11 +1,13 @@ "Entrada Confirmada", - "03" => "Entrada Rejeitada", - "06" => "Liquidação normal (sem motivo)", - "09" => "Baixado Automat. via Arquivo", - "10" => "Baixado conforme instruções da Agência", - "11" => "Em Ser - Arquivo de Títulos pendentes (sem motivo)", - "12" => "Abatimento Concedido (sem motivo)", - "13" => "Abatimento Cancelado (sem motivo)", - "14" => "Vencimento Alterado (sem motivo)", - "15" => "Liquidação em Cartório (sem motivo)", - "16" => "Título Pago em Cheque - Vinculado", - "17" => "Liquidação após baixa ou Título não registrado (sem motivo)", - "18" => "Acerto de Depositária (sem motivo)", - "19" => "Confirmação Receb. Inst. de Protesto", - "20" => "Confirmação Recebimento Instrução Sustação de Protesto (sem motivo)", - "21" => "Acerto do Controle do Participante (sem motivo)", - "22" => "Título Com Pagamento Cancelado", - "23" => "Entrada do Título em Cartório (sem motivo)", - "24" => "Entrada rejeitada por CEP Irregular", - "27" => "Baixa Rejeitada", - "28" => "Débito de tarifas/custas", - "30" => "Alteração de Outros Dados Rejeitados", - "32" => "Instrução Rejeitada", - "33" => "Confirmação Pedido Alteração Outros Dados (sem motivo)", - "34" => "Retirado de Cartório e Manutenção Carteira (sem motivo)", - "35" => "Desagendamento do débito automático", - "40" => "Estorno de pagamento (Novo)", - "55" => "Sustado judicial (Novo)", - "68" => "Acerto dos dados do rateio de Crédito", - "69" => "Cancelamento dos dados do rateio", + '02' => 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '06' => 'Liquidação normal (sem motivo)', + '09' => 'Baixado Automat. via Arquivo', + '10' => 'Baixado conforme instruções da Agência', + '11' => 'Em Ser - Arquivo de Títulos pendentes (sem motivo)', + '12' => 'Abatimento Concedido (sem motivo)', + '13' => 'Abatimento Cancelado (sem motivo)', + '14' => 'Vencimento Alterado (sem motivo)', + '15' => 'Liquidação em Cartório (sem motivo)', + '16' => 'Título Pago em Cheque - Vinculado', + '17' => 'Liquidação após baixa ou Título não registrado (sem motivo)', + '18' => 'Acerto de Depositária (sem motivo)', + '19' => 'Confirmação Receb. Inst. de Protesto', + '20' => 'Confirmação Recebimento Instrução Sustação de Protesto (sem motivo)', + '21' => 'Acerto do Controle do Participante (sem motivo)', + '22' => 'Título Com Pagamento Cancelado', + '23' => 'Entrada do Título em Cartório (sem motivo)', + '24' => 'Entrada rejeitada por CEP Irregular', + '27' => 'Baixa Rejeitada', + '28' => 'Débito de tarifas/custas', + '30' => 'Alteração de Outros Dados Rejeitados', + '32' => 'Instrução Rejeitada', + '33' => 'Confirmação Pedido Alteração Outros Dados (sem motivo)', + '34' => 'Retirado de Cartório e Manutenção Carteira (sem motivo)', + '35' => 'Desagendamento do débito automático', + '40' => 'Estorno de pagamento (Novo)', + '55' => 'Sustado judicial (Novo)', + '68' => 'Acerto dos dados do rateio de Crédito', + '69' => 'Cancelamento dos dados do rateio', ]; /** @@ -102,12 +104,12 @@ class Bradesco extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -115,7 +117,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -134,7 +136,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -145,6 +147,10 @@ protected function processarDetalhe(array $detalhe) ->setContaDv($this->rem(37, 37, $detalhe)); } + if ($this->rem(1, 1, $detalhe) == 4) { + return $this->processarPix($detalhe); + } + $d = $this->detalheAtual(); $d->setCarteira($this->rem(108, 108, $detalhe)) ->setNossoNumero($this->rem(71, 82, $detalhe)) @@ -155,14 +161,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(296, 301, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '15', '17')) { @@ -182,24 +188,12 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - if($d->hasOcorrencia('03')) { - if(isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ - $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); - } + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } } - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -212,13 +206,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) @@ -227,4 +221,18 @@ protected function processarTrailer(array $trailer) return true; } + + /** + * @param array $detalhe + * @return bool + * @throws ValidationException + */ + private function processarPix(array $detalhe) + { + $d = $this->getDetalhe($this->increment - 1); + $d->setPixLocation($this->rem(29, 105, $detalhe)); + $d->setId($this->rem(106, 140, $detalhe)); + + return false; + } } diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/C6.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/C6.php new file mode 100644 index 00000000..fe2a8a6b --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/C6.php @@ -0,0 +1,385 @@ + 'Entrada confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Alteração de Dados (Entrada)', + '05' => 'Alteração de Dados (Baixa)', + '06' => 'Liquidação Normal', + '07' => 'Liquidação após Baixa', + '08' => 'Liquidação em Cartório', + '09' => 'Baixa Simples', + '10' => 'Baixa comandada do cliente arquivo', + '12' => 'Abatimento concedido', + '13' => 'Abatimento cancelado', + '14' => 'Vencimento alterado', + '15' => 'Baixa rejeitada', + '16' => 'Instrução rejeitada', + '17' => 'Alterações de dados rejeitados', + '19' => 'Confirma instrução de protesto', + '20' => 'Confirma instrução de sustação de protesto', + '21' => 'Confirma instrução de não protestar', + '23' => 'Protesto enviado a cartório', + '29' => 'Sacado nao retirou boleto eletronicamente,enviado para correio', + '32' => 'Baixa por ter sido protestado', + '35' => 'Alegações do sacado', + '36' => 'Custas de Edital', + '37' => 'Custas de sustação judicial', + '38' => 'Título sustado judicialmente', + '65' => 'Pagamento com Cheque - Aguardando compensação', + '69' => 'Cancelamento de Liquidação por Cheque Devolvido', + '71' => 'Protesto cancelado pelo Cartório', + '72' => 'Baixa Operacional', + '74' => 'Cancelamento da Baixa Operacional', + '75' => 'Pagamento Parcial', + '90' => 'Instrução de Protesto Rejeitada', + '95' => 'Troca Uso Empresa', + '96' => 'Emissão Extrato Mov. Carteira', + '97' => 'Tarifa de sustação de protesto', + '98' => 'Tarifa de protesto', + '99' => 'Custas de protesto', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '1818' => 'boleto não retirado pelo sacado. reenviado pelo correio para carteiras com emissão pelo banco', + '9000' => 'data vencimento menor que o prazo de aceitação do título', + '9001' => 'sacado bloqueado por atraso', + '9002' => 'registro opcional inválido', + '9003' => 'cep sem praça de cobrança', + '9004' => 'prazo insuficiente para cobrança do título', + '9005' => 'Campo numérico inválido', + '9006' => 'Campo texto inválido', + '9007' => 'Campo tipo data inválido', + '9008' => 'Caractere inválido', + '9009' => 'cpf/cnpj do sacado e emitente devem ser diferentes', + '9010' => 'data vencimento menor que a data de emissão', + '9011' => 'data emissão maior que a data atual', + '9012' => 'uf sacado inválido', + '9013' => 'uf emitente inválido', + '9014' => 'Campo obrigatório não preenchido', + '9015' => 'cpf do sacado inválido', + '9016' => 'cnpj do sacado inválido', + '9017' => 'o nome do sacado enviado não confere com o nome do sacado cadastrado no sistema para este cnpj/cpf', + '9018' => 'tipo do sacado inválido', + '9019' => 'o sacado está bloqueado', + '9020' => 'o endereço do sacado esta com o tamanho esta maior que o permitido', + '9021' => 'digito do nosso numero inválido', + '9022' => 'não existe faixa cadastrada para o banco e a conta', + '9023' => 'o nosso numero esta fora da faixa cadastrada para o cedente', + '9024' => 'identificação do título inválida', + '9025' => 'ocorrência não permitida pois o título esta baixado', + '9026' => 'ocorrência não permitida pois o título esta liquidado', + '9027' => 'ocorrência não permitida pois o título esta em protesto', + '9028' => 'não é permitida alteração de vencimento para carteira de desconto', + '9029' => 'situação do título inválida', + '9030' => 'não foi possível conceder o abatimento', + '9031' => 'não existe abatimento a ser cancelado', + '9032' => 'não foi possível prorrogar a data de vencimento do título', + '9033' => 'evento não permitido para situação do título', + '9034' => 'evento não permitido para cheques', + '9035' => 'o código do registro esta diferente de 1', + '9036' => 'Agência inválida', + '9037' => 'Número da Conta Corrente para depósito Inválido', + '9038' => 'o cnpj do cedente passado para o arquivo não confere com o cnpj do cedente cadastrado para o arquivo', + '9040' => 'cnpj do cedente não encontrado no cadastro', + '9041' => 'tipo do emitente inválido', + '9042' => 'cnpj do emitente inválido', + '9045' => 'campo nosso numero deve ter um valor de, no máximo , 10 digitos quando a carteira de cobrança não é direta', + '9046' => 'no campo nosso número a identificação do título esta inválida', + '9047' => 'banco e conta de cobrança direta não informados', + '9049' => 'campo aceite enviado com valor nulo ou inválido', + '9050' => 'data de emisão inválida', + '9051' => 'data de vencimento inválida', + '9052' => 'Data de desconto 2 inválida', + '9053' => 'especie de titulo invalida', + '9054' => 'especie de titulo não encontrada', + '9055' => 'valor de título inválido', + '9056' => 'prazo de cartorio invalido', + '9057' => 'valor de abatimento inválido', + '9058' => 'valor de desconto inválido', + '9059' => 'código de ocorrência inválida ou inexistente', + '9060' => 'tipo de mora inválido', + '9062' => 'valor de juros ao dia inválido', + '9063' => 'a data de juros mora é anterior à data de vencimento. favor verificar estes campos.', + '9064' => 'a data de juros mora inválida', + '9065' => 'número da sequência diferente do esperado', + '9066' => 'numero de sequencia inválido', + '9067' => 'registro inválido', + '9068' => 'cpf do emitente inválido', + '9070' => 'nome do emitente inválido', + '9071' => 'endereço do emitente inválido', + '9072' => 'cidade do emitente inválida', + '9073' => 'cep do emitente inválido', + '9074' => 'este contrato não está cadastrado para o cedente', + '9075' => 'não é permitida a entrada de títulos vencidos', + '9078' => 'não existe endereço, uf e cidade para o título', + '9079' => 'nosso número inválido', + '9081' => 'prazo insuficiente para cobrança do título neste cep', + '9083' => 'o cedente não pode enviar esse tipo de título com esta carteira', + '9084' => 'seu número do registro opcional diferente da linha do registro do título', + '9085' => 'data de vencimento do registro opcional diferente da linha do registro do título.', + '9086' => 'valor do título no vencimento do registro opcional diferente da linha do registro do título.', + '9087' => 'os títulos de carteira de cobrança direta só podem ser enviados para contas de cobrnaça direta. acao: confira a carteira e a conta cobrança que está sendo enviada/atribuida ao título.', + '9089' => 'código cmc7 invalido', + '9090' => 'entrada - nosso número já está sendo utilizado para mesmo banco / conta', + '9091' => 'cep do sacado não pertence ao estado da federação (uf) informado', + '9092' => 'tipo de multa inválido', + '9093' => 'registro opcional de emitente inválido', + '9097' => 'O campo Nosso Número não foi informado ou não foi possivel identificar o titulo.', + '9098' => 'foi encontrado mais de um título para esse nosso número.', + '9099' => 'preencha o campo de "conta de cobrança" no cadastro de carteira por cedente.', + '9100' => 'título possui registro opcional de emitente e a sua configuração não permite envio de títulos de terceiros.', + '9101' => 'título possui emitente, porém seus dados não foram informados.', + '9103' => 'ja existe titulo em aberto cadastrado para este cedente/seu numero/data vencimento/valor e emitente', + '9104' => 'impedido pela legislação vigente', + '9105' => 'crédito retido', + '9106' => 'nosso numero nao informado', + '9107' => 'tamanho máximo do nosso número para cobrança direta é 10 posições + digito(layout padrao matera/bradesco).', + '9108' => 'título pertence a uma espécie que não pode ser protestada.', + '9109' => 'protesto não permitido para título com moeda diferente de real.', + '9110' => 'cep do sacado não atendido pelos cartórios cadastrados.', + '9113' => 'Não permitimos troca de carteira no evento de Alteração de Outros Dados.', + '9114' => 'Não permitimos troca de tipo titulo no evento de Alteração de Outros Dados.', + '9201' => 'liquidação em cartório', + '9202' => 'baixa decurso prazo - banco', + '9203' => 'baixa protestado', + '9204' => 'Tarifa de Sustacao de protesto', + '9205' => 'tarifa de protesto', + '9206' => 'custas de protesto', + '9207' => 'custas de edital', + '9208' => 'custas de sustação de protesto título sustado judicialmente', + '9210' => 'liquidação em cheque', + '9213' => 'tarifa de manutenção de título vencido', + '9216' => 'liquidação no guichê de caixa em dinheiro', + '9217' => 'liquidação em banco correspondente', + '9218' => 'liquidação por compensação eletrônica', + '9219' => 'liquidação por conta', + '9222' => 'emissão extrato mov. carteira', + '9223' => 'Liquidação por STR', + '9224' => 'Carteira do Tipo G não pode inserir titulos.', + '9230' => 'Valor desconto 2 inválido', + '9232' => 'Sacado pertence a empresa do grupo (coligada)', + '9233' => 'Por solicitação da diretoria de crédito/comercial', + '9234' => 'Inexistência de relação com o cedente', + '9235' => 'Outros', + '9236' => 'Recusado - Outros Motivos', + '9237' => 'Baixa por Outros Motivos', + '9238' => 'Pagador Rejeita Boleto', + '9239' => 'Pagador Aceita Boleto', + '9240' => 'Data multa menor que data de vencimento do título', + '9242' => 'Baixa Integral Interbancária', + '9243' => 'Baixa Integral Intrabancária', + '9244' => 'Baixa Parcial Intrabancária', + '9245' => 'Baixa Parcial Interbancária', + '9250' => 'Tipo de autorização para recebimento de valor divergente inválido', + '9251' => 'Indicativo Tipo de valor ou percentual inválido', + '9252' => 'Quantidade de pagamento parcial inválido', + '9253' => 'Quantidade de pagamento parcial inválido, somente é permitido um valor maior ou igual a quantidade de pagamentos já recebido', + '9254' => 'Mínimo não aceito para o título', + '9255' => 'Máximo não aceito para o título', + '9258' => 'Data de desconto 3 inválida', + '9259' => 'Valor desconto 3 inválido', + '9260' => 'Mínimo é obrigatório quando informado o tipo valor ou percentual', + '9261' => 'Tipo de autorização de recebimento de valor divergente não permitio para tipo de título 31', + '9262' => 'Para especie de título diferente de fatura de cartão de crédito não é possível informar o tipo aceita qualquer valor com range mínimo e máximo preenchido', + '9263' => 'Mínimo e Máximo tem que ser informado para o tipo de autorização de valor divergente igual a 2', + '9264' => 'Mínimo e Máximo não devem ser informados para o tipo de autorização de valor divergente igual a 3', + '9265' => 'Mínimo deve ser informado e Máximo não pode ser informado para o tipo de autorização de valor divergente igual a 4', + '9266' => 'Valor não permitido para tipo de título fatura de cartão de crédito', + '9267' => 'Não é permitido ter juros, multa, abatimento, desconto ou protesto tipo de título fatura de cartão de crédito', + '9999' => 'cep do sacado inválido', + ]; + + /** + * Campos com possíveis erros + * @var string[] + */ + private $campoInvalido = [ + '004' => 'CNPJ da Empresa', + '018' => 'Código da Empresa', + '063' => 'Nosso Número', + '074' => 'Digito Verificador nosso número', + '107' => 'Código da Carteira', + '109' => 'Código Ocorrência Remessa', + '111' => 'Seu Número', + '121' => 'Data Vencimento', + '127' => 'Valor Título', + '148' => 'Espécie do Título', + '150' => 'Aceite', + '151' => 'Data Emissão Título', + '157' => 'Instrução 1', + '159' => 'Instrução 2', + '161' => 'Juros ao Dia', + '174' => 'Data Desconto ', + '180' => 'Valor Desconto ', + '193' => 'Data Multa', + '206' => 'Valor Abatimento', + '219' => 'Tipo Sacado', + '221' => 'CNPJ / CPF Sacado', + '235' => 'Nome do Sacado', + '275' => 'Endereço Sacado', + '315' => 'Bairro Sacado', + '327' => 'CEP Sacado', + '335' => 'Cidade Sacado', + '350' => 'UF Sacado', + '352' => 'Sacador', + '382' => 'Tipo de Multa', + '383' => 'Percentual de Multa', + '386' => 'Data Juros Mora', + '392' => 'Prazo dias para Cartório', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 19, $header)) + ->setConta($this->rem(27, 38, $header)) + ->setCodigoCliente($this->rem(39, 50, $header)) + ->setData($this->rem(125, 130, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + $d->setCarteira($this->rem(107, 108, $detalhe)) + ->setNossoNumero($this->rem(63, 73, $detalhe)) + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setDataCredito($this->rem(296, 301, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); + + $codErro = str_split(sprintf('%016s', $this->rem(378, 393, $detalhe)), 4) + array_fill(0, 4, ''); + + if ($d->hasOcorrencia('06', '08')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('07', '09', '10', '32', '72')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('23')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('04', '05', '14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '15', '16', '17', '90')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $codErro[0], ''), + Arr::get($this->rejeicoes, $codErro[1], ''), + Arr::get($this->rejeicoes, $codErro[2], ''), + Arr::get($this->rejeicoes, $codErro[3], '') + ); + if (in_array($codErro[0], ['9005', '9006', '9007', '9008']) + || in_array($codErro[1], ['9005', '9006', '9007', '9008']) + || in_array($codErro[2], ['9005', '9006', '9007', '9008']) + || in_array($codErro[3], ['9005', '9006', '9007', '9008'])) { + $posicaoInvalida = str_split(sprintf('%012s', $this->rem(366, 377, $detalhe)), 3) + array_fill(0, 4, ''); + $error .= Util::appendStrings( + Arr::get($this->campoInvalido, $posicaoInvalida[0], ''), + Arr::get($this->campoInvalido, $posicaoInvalida[1], ''), + Arr::get($this->campoInvalido, $posicaoInvalida[2], ''), + Arr::get($this->campoInvalido, $posicaoInvalida[3], '') + ); + } + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->rem(17, 22, $trailer)) + ->setValorTitulos(Util::nFloat($this->rem(3, 16, $trailer) / 100, 2, false)) + ->setQuantidadeErros((int) $this->totais['erros']) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->rem(37, 42, $trailer)) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Caixa.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Caixa.php index ab4f38b1..d0423721 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Caixa.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Caixa.php @@ -1,11 +1,13 @@ 'Estorno de Baixa/Liquidação', '34' => 'Transferência de Carteira/Entrada', '35' => 'Transferência de Carteira/Baixa', - '99' => 'Rejeição do Título – Cód. Rejeição informado nas POS 80 a 82' + '99' => 'Rejeição do Título – Cód. Rejeição informado nas POS 80 a 82', ]; /** @@ -93,12 +95,12 @@ protected function init() { $this->totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -106,7 +108,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -130,7 +132,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -144,14 +146,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(294, 299, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $this->totais['valor_recebido'] += $d->getValorRecebido(); diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Cresol.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Cresol.php new file mode 100644 index 00000000..a2b87bc2 --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Cresol.php @@ -0,0 +1,323 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Transferência de carteira/entrada', + '05' => 'Transferência de carteira/baixa', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '11' => 'Em Ser - Títulos em carteira', + '12' => 'Confirmação recebimento instrução de abatimento', + '13' => 'Confirmação recebimento instrução de cancelamento de abatimento', + '14' => 'Confirmação recebimento instrução alteração de vencimento', + '15' => 'Franco de pagamento', + '17' => 'Liquidação após baixa ou liquidação de título não registrado', + '19' => 'Confirmação Receb. Inst. de Protesto', + '20' => 'Confirmação recebimento instrução de sustação/cancelamento de protesto', + '23' => 'Remessa a cartório (aponte em cartório)', + '24' => 'Retirada de cartório e manutenção em carteira', + '25' => 'Protestado e baixado (baixa por ter sido protestado)', + '26' => 'Instrução rejeitada', + '27' => 'Confirmação do pedido de alteração de outros dados', + '28' => 'Débito de tarifas/custas', + '29' => 'Ocorrências do pagador', + '30' => 'Alteração de Outros Dados Rejeitados', + '33' => 'Confirmação da Alteração dos Dados do Rateio de Crédito', + '34' => 'Confirmação do Cancelamento dos Dados do Rateio de Crédito', + '35' => 'Confirmação do Desagendamento do Débito Automático', + '36' => 'Confirmação de envio de e-mail/SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '38' => 'Confirmação de alteração do Prazo Limite de Recebimento', + '39' => 'Confirmação de Dispensa de Prazo Limite de Recebimento', + '40' => 'Confirmação da alteração do número do título dado pelo cedente', + '41' => 'Confirmação da alteração do número controle do Participante', + '42' => 'Confirmação da alteração dos dados do Sacado', + '43' => 'Confirmação da alteração dos dados do Sacador/Avalista', + '44' => 'Título pago com cheque devolvido', + '45' => 'Título pago com cheque compensado', + '46' => 'Instrução para cancelar protesto confirmada', + '47' => 'Instrução para protesto para fins falimentares confirmada', + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança', + '49' => 'Alteração de contrato de cobrança', + '50' => 'Título pago com cheque pendente de liquidação', + '51' => 'Título DDA reconhecido pelo sacado', + '52' => 'Título DDA não reconhecido pelo sacado', + '53' => 'Título DDA recusado pela CIP', + '54' => 'Confirmação da Instrução de Baixa de Título Negativado sem Protesto', + '55' => 'Confirmação de Pedido de Dispensa de Multa', + '56' => 'Confirmação do Pedido de Cobrança de Multa', + '57' => 'Confirmação do Pedido de Alteração de Cobrança de Juros', + '58' => 'Confirmação do Pedido de Alteração do Valor/Data de Desconto', + '59' => 'Confirmação do Pedido de Alteração do Cedente do Título', + '60' => 'Confirmação do Pedido de Dispensa de Juros de Mora', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '1' => 'Código do Banco Inválido', + '2' => 'Código do Registro Detalhe Inválido', + '3' => 'Código do Segmento Inválido', + '4' => 'Código de Movimento Não Permitido para Carteira', + '5' => 'Código de Movimento Inválido', + '6' => 'Tipo/Número de Inscrição do Cedente Inválidos', + '7' => 'Agência/Conta/DV Inválido', + '8' => 'Nosso Número Inválido', + '9' => 'Nosso Número Duplicado', + '10' => 'Carteira Inválida', + '11' => 'Forma de Cadastramento do Título Inválido', + '12' => 'Tipo de Documento Inválido', + '13' => 'Identificação de Emissão do Bloqueto Inválida', + '14' => 'Identificação da Distribuição do Bloqueto Inválida', + '15' => 'Características da Cobrança Incompatíveis', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior a Data de Emissão', + '18' => 'Vencimento Fora do Prazo de Operação', + '19' => 'Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias', + '20' => 'Valor do Título Inválido', + '21' => 'Espécie do Título Inválida', + '22' => 'Espécie do Título Não Permitida para a Carteira', + '23' => 'Aceite Inválido', + '24' => 'Data de Emissão Inválida', + '25' => 'Data da Emissão Posterior a Data de Entrada', + '26' => 'Código de Juros de Mora Inválido', + '27' => 'Valor/Taxa de Juros de Mora Inválido', + '28' => 'Código do Desconto Inválido', + '29' => 'Valor do Desconto Maior ou Igual ao Valor do Título', + '30' => 'Desconto a Conceder Não Confere', + '31' => 'Concessão de Desconto - Já Existe Desconto Anterior', + '32' => 'Valor do IOF Inválido', + '33' => 'Valor do Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do Título', + '35' => 'Valor a Conceder Não Confere', + '36' => 'Concessão de Abatimento - Já Existe Abatimento Anterior', + '37' => 'Código para Protesto Inválido', + '38' => 'Prazo para Protesto Inválido', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto', + '42' => 'Código para Baixa/Devolução Inválido', + '43' => 'Prazo para Baixa/Devolução Inválida', + '44' => 'Código da Moeda Inválido', + '45' => 'Nome do Sacado Não Informado', + '46' => 'Tipo/Número de Inscrição do Sacado Inválido', + '47' => 'Endereço do Sacado Não Informado', + '48' => 'CEP Inválido', + '49' => 'CEP Sem Praça de Cobrança (Não Localizado)', + '50' => 'CEP Referente a um Banco Correspondente', + '51' => 'CEP imcompatível com a Unidade da Federação', + '52' => 'Registro de Título já liquidado Cart. 17', + '53' => 'Tipo/Número de Inscrição do Sacador/Avalista Inválidos', + '54' => 'Sacador/Avalista Não Informado', + '55' => 'Nosso Número no Banco Correspondente Não Informado', + '56' => 'Código do Banco Correspondente Não Informado', + '57' => 'Código da Multa Inválido', + '58' => 'Data da Multa Inválida', + '59' => 'Valor/Percentual da Multa Inválido', + '60' => 'Movimento para Título Não Cadastrado', + '61' => 'Alteração da Agência Cobradora/DV Inválida', + '62' => 'Tipo de Impressão Inválido', + '63' => 'Entrada para Título já Cadastrado', + '64' => 'Número da Linha Inválido', + '65' => 'Código do Banco para Débito Inválido', + '66' => 'Agência/Conta/DV para Débito Inválido', + '67' => 'Dados para Débito incompatível com a Identificação da Emissão do Bloqueto', + '68' => 'Débito Automático Agendado', + '69' => 'Débito Não Agendado - Erro nos Dados da Remessa', + '70' => 'Débito Não Agendado - Sacado Não Consta do Cadastro de Autorizante', + '71' => 'Débito Não Agendado - Cedente Não Autorizado pelo Sacado', + '72' => 'Débito Não Agendado - Cedente Não Participa da Modalidade Débito Automático', + '73' => 'Débito Não Agendado - Código de Moeda Diferente de Reao (R$)', + '74' => 'Débito Não Agendado - Data Vencimento Inválida', + '75' => 'Débito Não Agendado, Conforme seu Pedido, Título Não Registrado', + '76' => 'Débito Não Agendado, Tipo/Num. Inscrição do Debitado, Inválido', + '77' => 'Transferência para Desconto Não Permitida para a Cateira do Título', + '78' => 'Data Inferior ou Igual ao Vencimento para Débito Automático', + '79' => 'Data Juros de Mora Inválido', + '80' => 'Data do Desconto Inválida', + '81' => 'Tentativas de Débito Esgotadas - Baixado', + '82' => 'Tentativas de Débito Esgotadas - Pendente', + '83' => 'Limite Excedido', + '84' => 'Número Autorização Inexistente', + '85' => 'Título com Pagamento Vinculado', + '86' => 'Seu Número Inválido', + '87' => 'e-mail/SMS enviado', + '88' => 'e-mail Lido', + '89' => 'e-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto', + '90' => 'e-mail devolvido - caixa postal cheia', + '91' => 'e-mail/número do celular do sacado não informado', + '92' => 'Sacado optante por Bloqueto Eletrônico - e-mail não enviado', + '93' => 'Código para emissão de bloqueto não permite envio de e-mail', + '94' => 'Código da Carteira inválido para envio e-mail', + '95' => 'Contrato não permite o envio de e-mail', + '96' => 'Número de contrato inválido', + '97' => 'Rejeição da alteração do prazo limite de recebimento', + '98' => 'Rejeição de dispensa de prazo limite de recebimento', + '99' => 'Rejeição da alteração do número do título dado pelo cedente', + 'A1' => 'Rejeição da alteração do número controle do participante', + 'A2' => 'Rejeição da alteração dos dados do sacado', + 'A3' => 'Rejeição da alteração dos dados do sacador/avalista', + 'A4' => 'Sacado DDA', + 'A5' => 'Registro Rejeitado - Título já Liquidado', + 'A6' => 'Código do Convenente Inválido ou Encerrado', + 'A7' => 'Título se já encontra na situação Pretendida', + 'A8' => 'Valor do Abatimento inválido para cancelamento', + 'A9' => 'Não autoriza pagamento parcial', + 'B1' => 'Autoriza recebimento parcial', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws \Exception + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 26, $header)) + ->setCodigoCliente($this->rem(27, 46, $header)) + ->setData($this->rem(95, 100, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws \Exception + */ + protected function processarDetalhe(array $detalhe) + { + if ($this->count() == 1) { + $this->getHeader() + ->setAgencia($this->rem(25, 29, $detalhe)) + ->setConta($this->rem(30, 36, $detalhe)) + ->setContaDv($this->rem(37, 37, $detalhe)); + } + + $d = $this->detalheAtual(); + $d->setCarteira($this->rem(108, 108, $detalhe)) + ->setNossoNumero($this->rem(71, 82, $detalhe)) + //71 - 81 Identificação do Título no Banco / 82 Digito N/N + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setDataCredito($this->rem(296, 301, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); //outros creditos + + $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '15', '17')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09', '10')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('23')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } + } + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws \Exception + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) + ->setQuantidadeErros((int) $this->totais['erros']) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->totais['liquidados']) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Delbank.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Delbank.php index dcab86d2..1e2a76e2 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Delbank.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Delbank.php @@ -1,11 +1,13 @@ "Confirma Entrada Título na CIP", - "02" => "Entrada Confirmada", - "03" => "Entrada Rejeitada", - "05" => "Campo Livre Alterado", - "06" => "Liquidação Normal", - "08" => "Liquidação em Cartório", - "09" => "Baixa Automática", - "10" => "Baixa por ter sido liquidado", - "12" => "Confirma Abatimento", - "13" => "Abatimento Cancelado", - "14" => "Vencimento Alterado", - "15" => "Baixa Rejeitada", - "16" => "Instrução Rejeitada", - "19" => "Confirma Recebimento de Ordem de Protesto", - "20" => "Confirma Recebimento de Ordem de Sustação", - "22" => "Seu número alterado", - "23" => "Título enviado para cartório", - "24" => "Confirma recebimento de ordem de não protestar", - "28" => "Débito de Tarifas/Custas – Correspondentes", - "40" => "Tarifa de Entrada (debitada na Liquidação)", - "43" => "Baixado por ter sido protestado", - "96" => "Tarifa Sobre Instruções – Mês anterior", - "97" => "Tarifa Sobre Baixas – Mês Anterior", - "98" => "Tarifa Sobre Entradas – Mês Anterior", - "99" => "Tarifa Sobre Instruções de Protesto/Sustação – Mês Anterio" + '01' => 'Confirma Entrada Título na CIP', + '02' => 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '05' => 'Campo Livre Alterado', + '06' => 'Liquidação Normal', + '08' => 'Liquidação em Cartório', + '09' => 'Baixa Automática', + '10' => 'Baixa por ter sido liquidado', + '12' => 'Confirma Abatimento', + '13' => 'Abatimento Cancelado', + '14' => 'Vencimento Alterado', + '15' => 'Baixa Rejeitada', + '16' => 'Instrução Rejeitada', + '19' => 'Confirma Recebimento de Ordem de Protesto', + '20' => 'Confirma Recebimento de Ordem de Sustação', + '22' => 'Seu número alterado', + '23' => 'Título enviado para cartório', + '24' => 'Confirma recebimento de ordem de não protestar', + '28' => 'Débito de Tarifas/Custas – Correspondentes', + '40' => 'Tarifa de Entrada (debitada na Liquidação)', + '43' => 'Baixado por ter sido protestado', + '96' => 'Tarifa Sobre Instruções – Mês anterior', + '97' => 'Tarifa Sobre Baixas – Mês Anterior', + '98' => 'Tarifa Sobre Entradas – Mês Anterior', + '99' => 'Tarifa Sobre Instruções de Protesto/Sustação – Mês Anterio', ]; /** @@ -55,47 +57,47 @@ class Delbank extends AbstractRetorno implements RetornoCnab400 * @var array */ private $rejeicoes = [ - "04" => "Data de vencimento não numérica ou inválida", - "05" => "Data de Vencimento inválida ou fora do prazo mínimo", - "14" => "Registro em duplicidade", - "19" => "Data de desconto inválida ou maior que a data de vencimento", - "20" => "Campo livre não informado", - "21" => "Título não registrado no sistema", - "22" => "Título baixado ou liquidado", - "26" => "Espécie de documento inválida", - "27" => "Instrução não aceita, por não ter sido emitida ordem de protesto ao cartório", - "28" => "Título tem instrução de cartório ativa", - "29" => "Título não tem instrução de carteira ativa", - "30" => "Existe instrução de não protestar, ativa para o título", - "36" => "Valor de permanência (mora) não numérico ", - "37" => "Título Descontado – Instrução não permitida para a carteira", - "38" => "Valor do abatimento não numérico ou maior que a soma do valor do título + permanência + multa", - "39" => "Título em cartório", - "40" => "Instrução recusada – Reprovado no Represamento para Análise", - "44" => "Título zerado ou em branco; ou não numérico na remessa", - "51" => "Tipo/Número de Inscrição Sacador/Avalista Inválido", - "53" => "Prazo de vencimento do título excede ao da contratação", - "57" => "Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.", - "AA" => "Serviço de cobrança inválido", - "AE" => "Título não possui abatimento", - "AG" => "Movimento não permitido – Título à vista ou contra apresentação", - "AH" => "Cancelamento de valores inválidos", - "AI" => "Nossa carteira inválida", - "AK" => "Título pertence a outro cliente", - "AU" => "Data da ocorrência inválida", - "AY" => "Título deve estar em aberto e vencido para acatar protesto", - "BA" => "Banco Correspondente Recebedor não é o Cobrador Atual", - "BB" => "Título deve estar em cartório para baixar", - "CB" => "Título possui protesto efetivado/a efetivar hoje", - "CT" => "Título já baixado", - "CW" => "Título já transferido", - "DO" => "Título em Prejuízo", - "IX" => "Título de Cartão de Crédito não aceita instruções", - "JK" => "Produto não permite alteração de valor de título", - "JQ" => "Título em Correspondente – Não alterar Valor", - "JS" => "Título possui Descontos/Abto/Mora/Multa", - "JT" => "Título possui Agenda de Protesto/Devolução", - "99" => "Ocorrência desconhecida na remessa" + '04' => 'Data de vencimento não numérica ou inválida', + '05' => 'Data de Vencimento inválida ou fora do prazo mínimo', + '14' => 'Registro em duplicidade', + '19' => 'Data de desconto inválida ou maior que a data de vencimento', + '20' => 'Campo livre não informado', + '21' => 'Título não registrado no sistema', + '22' => 'Título baixado ou liquidado', + '26' => 'Espécie de documento inválida', + '27' => 'Instrução não aceita, por não ter sido emitida ordem de protesto ao cartório', + '28' => 'Título tem instrução de cartório ativa', + '29' => 'Título não tem instrução de carteira ativa', + '30' => 'Existe instrução de não protestar, ativa para o título', + '36' => 'Valor de permanência (mora) não numérico ', + '37' => 'Título Descontado – Instrução não permitida para a carteira', + '38' => 'Valor do abatimento não numérico ou maior que a soma do valor do título + permanência + multa', + '39' => 'Título em cartório', + '40' => 'Instrução recusada – Reprovado no Represamento para Análise', + '44' => 'Título zerado ou em branco; ou não numérico na remessa', + '51' => 'Tipo/Número de Inscrição Sacador/Avalista Inválido', + '53' => 'Prazo de vencimento do título excede ao da contratação', + '57' => 'Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.', + 'AA' => 'Serviço de cobrança inválido', + 'AE' => 'Título não possui abatimento', + 'AG' => 'Movimento não permitido – Título à vista ou contra apresentação', + 'AH' => 'Cancelamento de valores inválidos', + 'AI' => 'Nossa carteira inválida', + 'AK' => 'Título pertence a outro cliente', + 'AU' => 'Data da ocorrência inválida', + 'AY' => 'Título deve estar em aberto e vencido para acatar protesto', + 'BA' => 'Banco Correspondente Recebedor não é o Cobrador Atual', + 'BB' => 'Título deve estar em cartório para baixar', + 'CB' => 'Título possui protesto efetivado/a efetivar hoje', + 'CT' => 'Título já baixado', + 'CW' => 'Título já transferido', + 'DO' => 'Título em Prejuízo', + 'IX' => 'Título de Cartão de Crédito não aceita instruções', + 'JK' => 'Produto não permite alteração de valor de título', + 'JQ' => 'Título em Correspondente – Não alterar Valor', + 'JS' => 'Título possui Descontos/Abto/Mora/Multa', + 'JT' => 'Título possui Agenda de Protesto/Devolução', + '99' => 'Ocorrência desconhecida na remessa', ]; /** @@ -104,12 +106,12 @@ class Delbank extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -117,7 +119,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -136,7 +138,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -157,14 +159,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(386, 391, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '08')) { @@ -184,24 +186,12 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '15', '16')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - if($d->hasOcorrencia('03')) { - if(isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ - $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); - } + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } } - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -214,13 +204,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Fibra.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Fibra.php index 991c4f02..51999acb 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Fibra.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Fibra.php @@ -1,11 +1,13 @@ 'Confirma Entrada Título na CIP', '02' => 'Entrada Confirmada', @@ -211,7 +212,7 @@ class Fibra extends AbstractRetorno implements RetornoCnab400 'JS' => 'Título possui Descontos/Abto/Mora/Multa', 'JT' => 'Título possui Agenda de Protesto/Devolução', '99' => 'Ocorrência desconhecida na remessa', - ] + ], ]; /** @@ -220,11 +221,11 @@ class Fibra extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -232,7 +233,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -252,7 +253,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -266,13 +267,13 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(378, 385, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '08', '10')) { @@ -290,21 +291,9 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('05', '14', '22')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03', '15', '16')) { + } elseif ($d->hasOcorrencia('03', '15', '16')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -317,7 +306,6 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Hsbc.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Hsbc.php index bacab663..213ad42d 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Hsbc.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Hsbc.php @@ -1,11 +1,13 @@ totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -171,7 +173,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -192,7 +194,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -205,12 +207,12 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); $this->totais['valor_recebido'] += $d->getValorRecebido(); diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Inter.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Inter.php index a6d342cc..89a8982e 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Inter.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Inter.php @@ -1,11 +1,13 @@ totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -56,7 +58,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -74,7 +76,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -95,8 +97,8 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(92, 97, $detalhe)) ->setDataVencimento($this->rem(119, 124, $detalhe)) ->setDataCredito($this->rem(173, 178, $detalhe)) - ->setValor(Util::nFloat(((float) $this->rem(125, 137, $detalhe))/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(160, 172, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat(((float) $this->rem(125, 137, $detalhe)) / 100, 2, false)) + ->setValorRecebido(Util::nFloat(((float) $this->rem(160, 172, $detalhe)) / 100, 2, false)); if ($d->hasOcorrencia('06')) { $this->totais['liquidados']++; @@ -109,10 +111,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('03')) { $this->totais['erros']++; - $error = Util::appendStrings( - 'Entrada rejeitada', - $this->rem(241, 380, $detalhe) - ); + $error = Util::appendStrings('Entrada rejeitada', $this->rem(241, 380, $detalhe)); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -125,13 +124,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) - ->setValorTitulos(Util::nFloat($this->rem(121, 132, $trailer)/100, 2, false)) //Total dos valores dos títulos Pagos + ->setValorTitulos(Util::nFloat($this->rem(121, 132, $trailer) / 100, 2, false)) //Total dos valores dos títulos Pagos ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Itau.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Itau.php index 6b7b1911..2e102e04 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Itau.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Itau.php @@ -1,11 +1,13 @@ detalheAtual(); + if ($this->rem(1, 1, $detalhe) == 3) { + return $this->processarPix($detalhe); + } + $d = $this->detalheAtual(); $d->setCarteira($this->rem(83, 85, $detalhe)) ->setNossoNumero($this->rem(86, 94, $detalhe)) ->setNumeroDocumento($this->rem(117, 126, $detalhe)) @@ -251,18 +256,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '15', '16', '17', '18', '60')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -275,7 +269,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { @@ -290,4 +284,39 @@ protected function processarTrailer(array $trailer) return true; } + + /** + * @param array $detalhe + * @return bool + * @throws ValidationException + */ + private function processarPix(array $detalhe) + { + $d = $this->getDetalhe($this->increment - 1); + + $aErrorPix = [ + '000' => null, + '001' => 'VALOR MAIOR QUE O MÁXIMO PERMITIDO', + '002' => 'NÃO É COMPATÍVEL COM O CNPJ INFORMADO', + '003' => 'CHAVE INVÁLIDA', + '004' => 'CHAVE SEM CADASTRO NA DICT', + '005' => 'CHAVE NÃO CADASTRADA NO MESMO CNPJ DA AG/CONTA DA REMESSA.', + '006' => 'EMISSÃO DE QR CODE NÃO PERMITIDA', + '007' => 'DATA DE DESCONTO MAIOR QUE A DATA DE VENCIMENTO', + '008' => 'IDLOCATION JÁ ESTÁ SENDO UTILIZADO POR OUTRA COBRANÇA PIX.', + '009' => 'LOCATION CRIADA PARA TIPO “COBRANÇA COM VENCIMENTO”', + '010' => 'BOLETO COM PIX NÃO É PERMITIDO PARA BOLETO COM PAGAMENTO PARCIAL', + '011' => 'BOLETO COM PIX NÃO É PERMITIDO PARA A CARTEIRA DO BOLETO', + '999' => 'PIX NÃO EMITIDO POR PROLEMAS NA PLATAFORMA. ENTRE EM CONTATO COM AS ÁREAS DE SUPORTE DO ITAÚ UNIBANCO', + ]; + + $d->setPixQrCode(trim($this->rem(2, 391, $detalhe))); + if ($decoded = Util::decodePixCopiaECola($d->getPixQrCode())) { + $d->setPixLocation(Arr::get($decoded, '26.25')); + $d->setId(Arr::get($decoded, '62.05')); + } + $d->appendError($aErrorPix[sprintf('%03s', $this->rem(392, 394, $detalhe))]); + + return false; + } } diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Ourinvest.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Ourinvest.php new file mode 100644 index 00000000..28ef80e1 --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Ourinvest.php @@ -0,0 +1,178 @@ + 'Nenhuma ocorrência informada', + '06' => 'Liquidação normal (sem motivo)', + '09' => 'Baixado Automat. via Arquivo', + '10' => 'Baixado conforme instruções da Agência', + '12' => 'Abatimento Concedido (sem motivo)', + '13' => 'Abatimento Cancelado (sem motivo)', + '14' => 'Vencimento Alterado (sem motivo)', + '15' => 'Liquidação em Cartório (sem motivo)', + '16' => 'Título Pago em Cheque - Vinculado', + '17' => 'Liquidação após baixa ou Título não registrado (sem motivo)', + '20' => 'Confirmação Recebimento Instrução Sustação de Protesto (sem motivo)', + '23' => 'Entrada do Título em Cartório (sem motivo)', + '28' => 'Débito de tarifas/custas', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '00' => 'Confirmação da ocorrência', + '02' => 'Tarifa de permanência título cadastrado', + '03' => 'Tarifa de sustação/Excl Negativação', + '04' => 'Tarifa de protesto/Incl Negativação', + '05' => 'Tarifa de outras instruções', + '06' => 'Tarifa de outras ocorrências', + '08' => 'Custas de protesto', + '10' => 'Baixa Comandada pelo cliente', + '15' => 'Título pago com cheque', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 26, $header)) + ->setCodigoCliente($this->rem(27, 46, $header)) + ->setData($this->rem(95, 100, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + if ($this->count() == 1) { + $this->getHeader() + ->setAgencia($this->rem(25, 29, $detalhe)) + ->setConta($this->rem(30, 36, $detalhe)) + ->setContaDv($this->rem(37, 37, $detalhe)); + } + + $d = $this->detalheAtual(); + $d->setCarteira($this->rem(22, 24, $detalhe)) + ->setNossoNumero($this->rem(71, 82, $detalhe)) + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setDataCredito($this->rem(296, 301, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); + + $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '15', '17', '20')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09', '10')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('23')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03')) { + $this->totais['erros']++; + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } + } + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) + ->setQuantidadeErros((int) $this->totais['erros']) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->totais['liquidados']) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Pine.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Pine.php index dc1f84c9..3f3cae49 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Pine.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Pine.php @@ -1,11 +1,13 @@ 'Confirma Entrada Título na CIP', '02' => 'Entrada Confirmada', @@ -211,7 +212,7 @@ class Pine extends AbstractRetorno implements RetornoCnab400 'JS' => 'Título possui Descontos/Abto/Mora/Multa', 'JT' => 'Título possui Agenda de Protesto/Devolução', '99' => 'Ocorrência desconhecida na remessa', - ] + ], ]; /** @@ -220,11 +221,11 @@ class Pine extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -232,7 +233,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -252,7 +253,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -266,13 +267,13 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(378, 385, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '08', '10')) { @@ -290,21 +291,9 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('05', '14', '22')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03', '15', '16')) { + } elseif ($d->hasOcorrencia('03', '15', '16')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -317,7 +306,6 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Rendimento.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Rendimento.php new file mode 100644 index 00000000..d9d0645a --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Rendimento.php @@ -0,0 +1,323 @@ + 'Confirma Entrada Título na CIP', + '02' => 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '05' => 'Campo Livre Alterado', + '06' => 'Liquidação Normal', + '08' => 'Liquidação em Cartório', + '09' => 'Baixa Automática', + '10' => 'Baixa por ter sido liquidado', + '12' => 'Confirma Abatimento', + '13' => 'Abatimento Cancelado', + '14' => 'Vencimento Alterado', + '15' => 'Baixa Rejeitada', + '16' => 'Instrução Rejeitada', + '19' => 'Confirma Recebimento de Ordem de Protesto', + '20' => 'Confirma Recebimento de Ordem de Sustação', + '22' => 'Seu número alterado', + '23' => 'Título enviado para cartório', + '24' => 'Confirma recebimento de ordem de não protestar', + '28' => 'Débito de Tarifas/Custas – Correspondentes', + '40' => 'Tarifa de Entrada (debitada na Liquidação)', + '43' => 'Baixado por ter sido protestado', + '96' => 'Tarifa Sobre Instruções – Mês anterior', + '97' => 'Tarifa Sobre Baixas – Mês Anterior', + '98' => 'Tarifa Sobre Entradas – Mês Anterior', + '99' => 'Tarifa Sobre Instruções de Protesto/Sustação – Mês Anterior', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '03' => [ + '03' => 'CEP inválido – Não temos cobrador – Cobrador não Localizado', + '04' => 'Sigla do Estado inválida', + '05' => 'Data de Vencimento inválida ou fora do prazo mínimo', + '06' => 'Código do Banco inválido', + '08' => 'Nome do sacado não informado', + '10' => 'Logradouro não informado', + '14' => 'Registro em duplicidade', + '19' => 'Data de desconto inválida ou maior que a data de vencimento', + '20' => 'Valor de IOF não numérico', + '21' => 'Movimento para título não cadastrado no sistema', + '22' => 'Valor de desconto + abatimento maior que o valor do título', + '25' => 'CNPJ ou CPF do sacado inválido (aceito com restrições)', + '26' => 'Espécie de documento inválida', + '27' => 'Data de emissão do título inválida', + '28' => 'Seu número não informado', + '29' => 'CEP é igual a espaço ou zeros; ou não numérico', + '30' => 'Valor do título não numérico ou inválido', + '36' => 'Valor de permanência (mora) não numérico', + '37' => 'Valor de permanência inconsistente, pois, dentro de um mês, será maior que o valor do título', + '38' => 'Valor de desconto/abatimento não numérico ou inválido', + '39' => 'Valor de abatimento não numérico', + '42' => 'Título já existente em nossos registros. Nosso número não aceito', + '43' => 'Título enviado em duplicidade nesse movimento', + '44' => 'Título zerado ou em branco; ou não numérico na remessa', + '46' => 'Título enviado fora da faixa de Nosso Número, estipulada para o cliente.', + '51' => 'Tipo/Número de Inscrição Sacador/Avalista Inválido', + '52' => 'Sacador/Avalista não informado', + '53' => 'Prazo de vencimento do título excede ao da contratação', + '54' => 'Banco informado não é nosso correspondente 140-142', + '55' => 'Banco correspondente informado não cobra este CEP ou não possui faixas de CEP cadastradas', + '56' => 'Nosso número no correspondente não foi informado', + '57' => 'Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.', + '58' => 'Entradas Rejeitadas – Reprovado no Represamento para Análise', + '60' => 'CNPJ/CPF do sacado inválido – título recusado', + '87' => 'Excede Prazo máximo entre emissão e vencimento', + 'AA' => 'Serviço de cobrança inválido', + 'AB' => 'Serviço de "0" ou "5" e banco cobrador <> zeros', + 'AE' => 'Título não possui abatimento', + 'AI' => 'Nossa carteira inválida', + 'AJ' => 'Modalidade com bancos correspondentes inválida', + 'AL' => 'Sacado impedido de entrar nesta cobrança', + 'AU' => 'Data da ocorrência inválida', + 'AV' => 'Valor da tarifa de cobrança inválida', + 'AX' => 'Título em pagamento parcial', + 'BC' => 'Análise gerencial-sacado inválido p/operação crédito', + 'BD' => 'Análise gerencial-sacado inadimplente', + 'BE' => 'Análise gerencial-sacado difere do exigido', + 'BF' => 'Análise gerencial-vencto excede vencto da operação de crédito', + 'BG' => 'Análise gerencial-sacado com baixa liquidez', + 'BH' => 'Análise gerencial-sacado excede concentração', + 'CC' => 'Valor de iof incompatível com a espécie documento', + 'CD' => 'Efetivação de protesto sem agenda válida', + 'CE' => 'Título não aceito - pessoa física', + 'CF' => 'Excede prazo máximo da entrada ao vencimento', + 'CG' => 'Título não aceito – por análise gerencial', + 'CH' => 'Título em espera – em análise pelo banco', + 'CJ' => 'Análise gerencial-vencto do titulo abaixo przcurto', + 'CK' => 'Análise gerencial-vencto do titulo abaixo przlongo', + 'CS' => 'Título rejeitado pela checagem de duplicatas', + 'DA' => 'Análise gerencial – Entrada de Título Descontado com limite cancelado', + 'DB' => 'Análise gerencial – Entrada de Título Descontado com limite vencido', + 'DC' => 'Análise gerencial - cedente com limite cancelado', + 'DD' => 'Análise gerencial – cedente é sacado e teve seu limite cancelado', + 'DE' => 'Análise gerencial - apontamento no Serasa', + 'DG' => 'Endereço sacador/avalista não informado', + 'DH' => 'Cep do sacador/avalista não informado', + 'DI' => 'Cidade do sacador/avalista não informado', + 'DJ' => 'Estado do sacador/avalista inválido ou n informado', + 'DM' => 'Cliente sem Código de Flash cadastrado no cobrador', + 'DN' => 'Título Descontado com Prazo ZERO – Recusado', + 'DP' => 'Data de Referência menor que a Data de Emissão do Título', + 'DT' => 'Nosso Número do Correspondente não deve ser informado', + 'EB' => 'HSBC não aceita endereço de sacado com mais de 38 caracteres', + 'G1' => 'Endereço do sacador incompleto ( lei 12.039)', + 'G2' => 'Sacador impedido de movimentar', + 'G3' => 'Concentração de cep não permitida', + 'G4' => 'Valor do título não permitido', + 'HA' => 'Serviço e Modalidade Incompatíveis', + 'HB' => 'Inconsistências entre Registros Título e Sacador', + 'HC' => 'Ocorrência não disponível', + 'HD' => 'Título com Aceite', + 'HF' => 'Baixa Liquidez do Sacado', + 'HG' => 'Sacado Informou que não paga Boletos', + 'HH' => 'Sacado não confirmou a Nota Fiscal', + 'HI' => 'Checagem Prévia não Efetuada', + 'HJ' => 'Sacado desconhece compra e Nota Fiscal', + 'HK' => 'Compra e Nota Fiscal canceladas pelo sacado', + 'HL' => 'Concentração além do permitido pela área de Crédito', + 'HM' => 'Vencimento acima do permitido pelo área de Crédito', + 'HN' => 'Excede o prazo limite da operação', + 'IX' => 'Título de Cartão de Crédito não aceita instruções', + 'JB' => 'Título de Cartão de Crédito inválido para o Produto', + 'JC' => 'Produto somente para Cartão de Crédito', + 'JH' => 'CB Direta com operação de Desconto Automático', + 'JI' => 'Espécie de Documento incompatível para produto de Cartão de Crédito', + 'JK' => 'Produto não permite alterar Valor e Vencimento', + 'JQ' => 'Título em Correspondente – Alteração não permitida', + 'JS' => 'Título possui Desc/Abatim/Mora/Multa', + 'JT' => 'Título possui Agenda', + 'KC' => 'Título já Sustado', + 'KD' => 'Serviço de Cobrança não permitido para carteira', + 'KE' => 'Título possui caracteres não permitidos.', + 'KF' => 'Operação fechada para novas entradas', + 'KG' => 'Nosso número bancos duplicado.', + 'ZQ' => 'Sem informação da Nota Fiscal Eletrônica', + 'ZR' => 'Chave de Acesso NF Rejeitada', + 'ZS' => 'Chave de Acesso NF Duplicada', + 'ZT' => 'Quantidade NF excede a quantidade permitida (30)', + 'ZU' => 'Chave de Acesso NF inválida', + ], + '15' => [ + '05' => 'Solicitação de baixa para título já baixado ou liquidado', + '06' => 'Solicitação de baixa para título não registrado no sistema', + '08' => 'Solicitação de baixa para título em float', + ], + '16' => [ + '04' => 'Data de vencimento não numérica ou inválida', + '05' => 'Data de Vencimento inválida ou fora do prazo mínimo', + '14' => 'Registro em duplicidade', + '19' => 'Data de desconto inválida ou maior que a data de vencimento', + '20' => 'Campo livre não informado', + '21' => 'Título não registrado no sistema', + '22' => 'Título baixado ou liquidado', + '26' => 'Espécie de documento inválida', + '27' => 'Instrução não aceita, por não ter sido emitida ordem de protesto ao cartório', + '28' => 'Título tem instrução de cartório ativa', + '29' => 'Título não tem instrução de carteira ativa', + '30' => 'Existe instrução de não protestar, ativa para o título', + '36' => 'Valor de permanência (mora) não numérico', + '37' => 'Título Descontado – Instrução não permitida para a carteira', + '38' => 'Valor do abatimento não numérico ou maior que a soma do valor do título + permanência + multa', + '39' => 'Título em cartório', + '40' => 'Instrução recusada – Reprovado no Represamento para Análise', + '44' => 'Título zerado ou em branco; ou não numérico na remessa', + '51' => 'Tipo/Número de Inscrição Sacador/Avalista Inválido', + '53' => 'Prazo de vencimento do título excede ao da contratação', + '57' => 'Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.', + 'AA' => 'Serviço de cobrança inválido', + 'AE' => 'Título não possui abatimento', + 'AG' => 'Movimento não permitido – Título à vista ou contra apresentação', + 'AH' => 'Cancelamento de valores inválidos', + 'AI' => 'Nossa carteira inválida', + 'AK' => 'Título pertence a outro cliente', + 'AU' => 'Data da ocorrência inválida', + 'AY' => 'Título deve estar em aberto e vencido para acatar protesto', + 'BA' => 'Banco Correspondente Recebedor não é o Cobrador Atual', + 'BB' => 'Título deve estar em cartório para baixar', + 'CB' => 'Título possui protesto efetivado/a efetivar hoje', + 'CT' => 'Título já baixado', + 'CW' => 'Título já transferido', + 'DO' => 'Título em Prejuízo', + 'IX' => 'Título de Cartão de Crédito não aceita instruções', + 'JK' => 'Produto não permite alteração de valor de título', + 'JQ' => 'Título em Correspondente – Não alterar Valor', + 'JS' => 'Título possui Descontos/Abto/Mora/Multa', + 'JT' => 'Título possui Agenda de Protesto/Devolução', + '99' => 'Ocorrência desconhecida na remessa', + ], + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 26, $header)) + ->setCodigoCliente($this->rem(27, 46, $header)) + ->setData($this->rem(95, 100, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + $d->setCarteira($this->rem(108, 108, $detalhe)) + ->setNossoNumero($this->rem(63, 73, $detalhe)) + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); + + $msgAdicional = str_split(sprintf('%08s', $this->rem(378, 385, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '08', '10')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('01', '02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('43')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('05', '14', '22')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '15', '16')) { + $this->totais['erros']++; + $error = Util::appendStrings(Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '')); + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->count()) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->totais['liquidados']) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Santander.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Santander.php index 4644d178..eba7c2ed 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Santander.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Santander.php @@ -1,11 +1,13 @@ totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -251,7 +253,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -271,20 +273,22 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { if ($this->count() == 1) { if (trim($this->rem(384, 385, $detalhe), '') != '') { $this->getHeader() - ->setConta( - $this->getHeader()->getConta() - . $this->rem(384, 385, $detalhe) - ); + ->setConta($this->getHeader()->getConta() + . $this->rem(384, 385, $detalhe)); } } + if ($this->rem(1, 1, $detalhe) == 2) { + return $this->processarPix($detalhe); + } + $d = $this->detalheAtual(); $d->setCarteira($this->rem(108, 108, $detalhe)) ->setNossoNumero($this->rem(63, 70, $detalhe)) @@ -295,15 +299,15 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(296, 301, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $this->totais['valor_recebido'] += $d->getValorRecebido(); @@ -356,4 +360,18 @@ protected function processarTrailer(array $trailer) return true; } + + /** + * @param array $detalhe + * @return bool + * @throws ValidationException + */ + private function processarPix(array $detalhe) + { + $d = $this->getDetalhe($this->increment - 1); + $d->setPixLocation($this->rem(3, 79, $detalhe)); + $d->setId($this->rem(80, 114, $detalhe)); + + return false; + } } diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Sicredi.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Sicredi.php index 4dd2af49..9db8e2a0 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Sicredi.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Sicredi.php @@ -1,11 +1,13 @@ totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -223,7 +225,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -243,7 +245,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -256,18 +258,18 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe), 2, false) / 100) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe), 2, false) / 100) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe), 2, false) / 100) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe), 2, false) / 100) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe), 2, false) / 100) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe), 2, false) / 100) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe), 2, false) / 100) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)) ->setDataCredito($this->rem(329, 336, $detalhe), 'Ymd'); if ($d->hasOcorrencia('06', '15', '16')) { - $this->totais['valor_recebido'] += $d->getValorRecebido(); + $this->totais['valor_recebido'] += $d->getValorRecebido(); $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { @@ -282,10 +284,10 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('33')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03','24', '27', '30', '32')) { + } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { $this->totais['erros']++; - if($d->hasOcorrencia('03')) { - if(isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); } } @@ -298,7 +300,6 @@ protected function processarDetalhe(array $detalhe) $msgAdicRetorno = str_split($msgAdicional, 2) + array_fill(0, 5, '') + array_fill(0, 5, ''); if (trim($msgAdicional, '0') != '') { - //Caso seja detalhe de Tarifa ('28' => 'Tarifa') Buscar as mensagens especificas e não classificar como erro if ($d->hasOcorrencia('28')) { $motivo = []; @@ -310,39 +311,13 @@ protected function processarDetalhe(array $detalhe) $motivo = array_filter($motivo); - if (count($motivo) > 0){ + if (count($motivo) > 0) { $d->setRejeicao(implode(PHP_EOL, $motivo)); } - - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - - //Caso haja outra mensagem adicional para tratar e não seja ocorrência de erro então - //concatenar a mensagem com o texto da descricao atual - } else - if ( $d->getOcorrenciaTipo() != $d::OCORRENCIA_ERRO ){ - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->rejeicoes, $msgAdicRetorno[0], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[1], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[2], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[3], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); - } - else { - + } elseif ($d->getOcorrenciaTipo() != $d::OCORRENCIA_ERRO) { + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->rejeicoes, $msgAdicRetorno[0], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[1], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[2], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[3], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); + } else { $error = []; $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[0], ''); $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[1], ''); @@ -350,16 +325,9 @@ protected function processarDetalhe(array $detalhe) $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[3], ''); $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[4], ''); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - $error = array_filter($error); - if (count($error) > 0){ + if (count($error) > 0) { $d->setError(implode(PHP_EOL, $error)); } } diff --git a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Unicred.php b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Unicred.php index 4da0bdec..86a7d6e1 100644 --- a/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Unicred.php +++ b/src/Cnab/Retorno/Cnab400/Cobranca/Banco/Unicred.php @@ -1,11 +1,13 @@ "Pago (Título protestado pago em cartório)", - "02" => "Instrução Confirmada", - "03" => "Instrução Rejeitada", - "04" => "Sustado Judicial (Título protestado sustado judicialmente)", - "06" => "Liquidação Normal", - "07" => "Liquidação em Condicional (Título liquidado em cartório com cheque do próprio devedor)", - "08" => "Sustado Definitivo (Título protestado sustado judicialmente)", - "09" => "Liquidação de Título Descontado", - "10" => "Protesto solicitado", - "11" => "Protesto Em cartório", - "12" => "Sustação solicitada", - "13" => "Títulos Descontado (título utilizado como garantia em operação de desconto)", - "14" => "Títulos Descontável (título com desistência de garantia em operação de desconto)", + '01' => 'Pago (Título protestado pago em cartório)', + '02' => 'Instrução Confirmada', + '03' => 'Instrução Rejeitada', + '04' => 'Sustado Judicial (Título protestado sustado judicialmente)', + '06' => 'Liquidação Normal', + '07' => 'Liquidação em Condicional (Título liquidado em cartório com cheque do próprio devedor)', + '08' => 'Sustado Definitivo (Título protestado sustado judicialmente)', + '09' => 'Liquidação de Título Descontado', + '10' => 'Protesto solicitado', + '11' => 'Protesto Em cartório', + '12' => 'Sustação solicitada', + '13' => 'Títulos Descontado (título utilizado como garantia em operação de desconto)', + '14' => 'Títulos Descontável (título com desistência de garantia em operação de desconto)', ]; /** @@ -43,74 +45,74 @@ class Unicred extends AbstractRetorno implements RetornoCnab400 * @var array */ private $rejeicoes = [ - '00' => 'Sem Complemento a informar', - '01' => 'Código do Banco Inválido', - '04' => 'Código de Movimento não permitido para a carteira', - '05' => 'Código de Movimento Inválido', - '06' => 'Número de Inscrição do Beneficiário Inválido', - '07' => 'Agência - Conta Inválida', - '08' => 'Nosso Número Inválido', - '09' => 'Nosso Número Duplicado', - '10' => 'Carteira inválida', - '12' => 'Tipo de Documento Inválido', - '15' => 'Data de Vencimento inferior a 5 dias uteis para remessa gráfica', - '16' => 'Data de Vencimento Inválida', - '17' => 'Data de Vencimento Anterior à Data de Emissão', - '18' => 'Vencimento fora do Prazo de Operação', - '20' => 'Valor do Título Inválido', - '24' => 'Data de Emissão Inválida', - '25' => 'Data de Emissão Posterior à data de Entrega', - '26' => 'Código de juros inválido', - '27' => 'Valor de juros inválido', - '28' => 'Código de Desconto inválido', - '29' => 'Valor de Desconto inválido', - '30' => 'Alteração de Dados Rejeitada', - '33' => 'Valor de Abatimento Inválido', - '34' => 'Valor do Abatimento Maior ou Igual ao Valor do título', - '37' => 'Código para Protesto Inválido; (Protesto via SGR, não é CRA)', - '38' => 'Prazo para Protesto Inválido; (Protesto via SGR, não é CRA)', - '39' => 'Pedido de Protesto Não Permitido para o Título', - '40' => 'Título com Ordem de Protesto Emitida', - '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto ou Instrução de Protesto não confirmada pelo cartório', - '45' => 'Nome do Pagador não informado', - '46' => 'Número de Inscrição do Pagador Inválido', - '47' => 'Endereço do Pagador Não Informado', - '48' => 'CEP Inválido', - '52' => 'Unidade Federativa Inválida', - '57' => 'Código de Multa inválido', - '58' => 'Data de Multa inválido', - '59' => 'Valor / percentual de Multa inválido', - '60' => 'Movimento para Título não Cadastrado', - '63' => 'Entrada para Título já cadastrado', - '79' => 'Data de Juros inválida', - '80' => 'Data de Desconto inválida', - '86' => 'Seu Número Inválido', - 'A5' => 'Título Liquidado', - 'A8' => 'Valor do Abatimento Inválido para Cancelamento', - 'C0' => 'Sistema Intermitente – Entre em contato com sua Cooperativa', - 'C1' => 'Situação do título Aberto', - 'C3' => 'Status do Borderô Inválido', - 'C4' => 'Nome do Beneficiário Inválido', - 'C5' => 'Documento Inválido', - 'C6' => 'Instrução não Atualiza Cadastro do Título', - 'C7' => 'Título não registrado na CIP', - 'C8' => 'Situação do Borderô inválida', - 'C9' => 'Título inválido conforme situação CIP', + '00' => 'Sem Complemento a informar', + '01' => 'Código do Banco Inválido', + '04' => 'Código de Movimento não permitido para a carteira', + '05' => 'Código de Movimento Inválido', + '06' => 'Número de Inscrição do Beneficiário Inválido', + '07' => 'Agência - Conta Inválida', + '08' => 'Nosso Número Inválido', + '09' => 'Nosso Número Duplicado', + '10' => 'Carteira inválida', + '12' => 'Tipo de Documento Inválido', + '15' => 'Data de Vencimento inferior a 5 dias uteis para remessa gráfica', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior à Data de Emissão', + '18' => 'Vencimento fora do Prazo de Operação', + '20' => 'Valor do Título Inválido', + '24' => 'Data de Emissão Inválida', + '25' => 'Data de Emissão Posterior à data de Entrega', + '26' => 'Código de juros inválido', + '27' => 'Valor de juros inválido', + '28' => 'Código de Desconto inválido', + '29' => 'Valor de Desconto inválido', + '30' => 'Alteração de Dados Rejeitada', + '33' => 'Valor de Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do título', + '37' => 'Código para Protesto Inválido; (Protesto via SGR, não é CRA)', + '38' => 'Prazo para Protesto Inválido; (Protesto via SGR, não é CRA)', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto ou Instrução de Protesto não confirmada pelo cartório', + '45' => 'Nome do Pagador não informado', + '46' => 'Número de Inscrição do Pagador Inválido', + '47' => 'Endereço do Pagador Não Informado', + '48' => 'CEP Inválido', + '52' => 'Unidade Federativa Inválida', + '57' => 'Código de Multa inválido', + '58' => 'Data de Multa inválido', + '59' => 'Valor / percentual de Multa inválido', + '60' => 'Movimento para Título não Cadastrado', + '63' => 'Entrada para Título já cadastrado', + '79' => 'Data de Juros inválida', + '80' => 'Data de Desconto inválida', + '86' => 'Seu Número Inválido', + 'A5' => 'Título Liquidado', + 'A8' => 'Valor do Abatimento Inválido para Cancelamento', + 'C0' => 'Sistema Intermitente – Entre em contato com sua Cooperativa', + 'C1' => 'Situação do título Aberto', + 'C3' => 'Status do Borderô Inválido', + 'C4' => 'Nome do Beneficiário Inválido', + 'C5' => 'Documento Inválido', + 'C6' => 'Instrução não Atualiza Cadastro do Título', + 'C7' => 'Título não registrado na CIP', + 'C8' => 'Situação do Borderô inválida', + 'C9' => 'Título inválido conforme situação CIP', 'C10' => 'Protesto: Título precisa estar em Aberto', - 'D0' => 'Beneficiário não autorizado a operar com produto Desconto', - 'D1' => 'Alteração de status de desconto não permitido para título', - 'D2' => 'Operação de desconto não permitida para título vencido', - 'D3' => 'Alteração de status de desconto não permitido para situação do título', - 'E0' => 'CEP indicado para o endereço do Pagador não compatível com os Correios', - 'E1' => 'Logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E2' => 'Tipo de logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E3' => 'Bairro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E4' => 'Cidade para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E5' => 'UF para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E6' => 'Dados do segmento/registro opcional de endereço do pagador, incompletos no arquivo remessa', - 'E7' => 'Beneficiário não autorizado a enviar boleto por e-mail', - 'E8' => 'Indicativo para pagador receber boleto por e-mail sinalizado, porém sem o endereço do e-mail', - 'E9' => 'Beneficiário não autorizado a enviar títulos para protesto', + 'D0' => 'Beneficiário não autorizado a operar com produto Desconto', + 'D1' => 'Alteração de status de desconto não permitido para título', + 'D2' => 'Operação de desconto não permitida para título vencido', + 'D3' => 'Alteração de status de desconto não permitido para situação do título', + 'E0' => 'CEP indicado para o endereço do Pagador não compatível com os Correios', + 'E1' => 'Logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E2' => 'Tipo de logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E3' => 'Bairro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E4' => 'Cidade para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E5' => 'UF para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E6' => 'Dados do segmento/registro opcional de endereço do pagador, incompletos no arquivo remessa', + 'E7' => 'Beneficiário não autorizado a enviar boleto por e-mail', + 'E8' => 'Indicativo para pagador receber boleto por e-mail sinalizado, porém sem o endereço do e-mail', + 'E9' => 'Beneficiário não autorizado a enviar títulos para protesto', 'E10' => 'Instrução ‘09 – Protestar’, usada erroneamente para título a vencer ou ainda dentro do período de Carência de ‘1 dia’ do vencimento, referente a liquidação por Compensação', 'E11' => 'Instrução ‘26 – Protesto Automático’, usada erroneamente para título vencido', 'E12' => 'Cancelamento de protesto automático não permitido, título não possui configuração de protesto automático', @@ -203,7 +205,6 @@ class Unicred extends AbstractRetorno implements RetornoCnab400 '170' => 'Dados do Cedente em branco ou inválido', ]; - /** * Array com os Códigos de Tipo de Instrução Origem (Posições 327 a 328 do retorno) * @@ -233,12 +234,12 @@ protected function init() { $this->totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -246,7 +247,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -267,7 +268,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -282,7 +283,7 @@ protected function processarDetalhe(array $detalhe) * Portanto, quando não refere-se a quitação de valores esse campo vem preenchido com '000000', e nesse caso * será utilizada então a data de geração do arquivo como data de ocorrência */ - $this->dataOcorrencia = ((!empty($this->rem(111, 116, $detalhe)) && ($this->rem(111, 116, $detalhe)!= '000000'))?$this->rem(111, 116, $detalhe):$this->dataGeracaoArquivo); + $this->dataOcorrencia = ((! empty($this->rem(111, 116, $detalhe)) && ($this->rem(111, 116, $detalhe) != '000000')) ? $this->rem(111, 116, $detalhe) : $this->dataGeracaoArquivo); $d = $this->detalheAtual(); @@ -296,20 +297,19 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->dataOcorrencia)//Data de geração do arquivo de remessa ou data de quitação do registro ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(176, 181, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe) / 100, 2, false)) // ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); - // ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); - + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); + // ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); //Adicionar array_fill para garantir que array tenha 5 casas - $msgAdicional = str_split( $this->rem(319, 326, $detalhe), 2) + array_fill(0, 5, ''); + $msgAdicional = str_split($this->rem(319, 326, $detalhe), 2) + array_fill(0, 5, ''); - if ($d->hasOcorrencia('01','06', '09')) { //'07' + if ($d->hasOcorrencia('01', '06', '09')) { //'07' $this->totais['valor_recebido'] += $d->getValorRecebido(); $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); @@ -319,28 +319,13 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('09', '10')) { $this->totais['baixados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); - } elseif ($d->hasOcorrencia('10','11')) { + } elseif ($d->hasOcorrencia('10', '11')) { $this->totais['protestados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); - //} elseif ($d->hasOcorrencia('14')) { - // $this->totais['alterados']++; - // $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03')) { - $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -353,13 +338,12 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos((int) $this->count()) - ->setValorTitulos( (float) Util::nFloat($this->totais['valor_recebido'], 2, false) ) + ->setValorTitulos((float) Util::nFloat($this->totais['valor_recebido'], 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Detalhe.php b/src/Cnab/Retorno/Cnab400/Detalhe.php index ca2284c2..82cd932d 100644 --- a/src/Cnab/Retorno/Cnab400/Detalhe.php +++ b/src/Cnab/Retorno/Cnab400/Detalhe.php @@ -3,12 +3,14 @@ namespace VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab400; use Carbon\Carbon; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Pessoa; use VinicciusGuedes\LaravelCnab\MagicTrait; +use VinicciusGuedes\LaravelCnab\Exception\ValidationException; use VinicciusGuedes\LaravelCnab\Contracts\Cnab\Retorno\Cnab400\Detalhe as DetalheContract; class Detalhe implements DetalheContract { - use MagicTrait; /** @@ -20,30 +22,37 @@ class Detalhe implements DetalheContract * @var string */ protected $nossoNumero; + /** * @var string */ protected $numeroDocumento; + /** * @var string */ protected $numeroControle; + /** * @var string */ protected $codigoLiquidacao; + /** * @var string */ protected $ocorrencia; + /** * @var string */ protected $ocorrenciaTipo; + /** * @var string */ protected $ocorrenciaDescricao; + /** * @var array */ @@ -57,50 +66,77 @@ class Detalhe implements DetalheContract * @var Carbon */ protected $dataOcorrencia; + /** * @var Carbon */ protected $dataVencimento; + /** * @var Carbon */ protected $dataCredito; + /** * @var string */ protected $valor; + /** * @var string */ protected $valorTarifa; + /** * @var string */ protected $valorOutrasDespesas; + /** * @var string */ protected $valorIOF; + /** * @var string */ protected $valorAbatimento; + /** * @var string */ protected $valorDesconto; + /** * @var string */ protected $valorRecebido; + /** * @var string */ protected $valorMora; + /** * @var string */ protected $valorMulta; + + /** + * @var + */ + protected $id; + + /** + * @var + */ + protected $pixQrCode; + + /** + * @var + */ + protected $pixLocation; + /** * @var string */ @@ -211,7 +247,7 @@ public function setCodigoLiquidacao($codigoLiquidacao) } /** - * @return boolean + * @return bool */ public function hasOcorrencia() { @@ -615,4 +651,92 @@ public function setError($error) return $this; } + + /** + * @param string $error + * + * @return Detalhe + */ + public function appendError($error) + { + $this->error .= $error; + + return $this; + } + + /** + * @return mixed + */ + public function getId() + { + return $this->id; + } + + /** + * @param mixed $id + * @return Detalhe + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * @return mixed + */ + public function getPixQrCode() + { + return $this->pixQrCode; + } + + /** + * @param mixed $pixQrCode + * @return Detalhe + */ + public function setPixQrCode($pixQrCode) + { + $this->pixQrCode = $pixQrCode; + + return $this; + } + + /** + * @return mixed + */ + public function getPixLocation() + { + return $this->pixLocation; + } + + /** + * @param mixed $pixLocation + * @return Detalhe + */ + public function setPixLocation($pixLocation) + { + $this->pixLocation = $pixLocation; + + return $this; + } + + /** + * @param $nome + * @param $cidade + * @param bool $force + * @return string|null + * @throws ValidationException + */ + public function gerarPixCopiaECola($nome, $cidade, $force = false) + { + if ($this->getPixQrCode() && ! $force) { + return $this->getPixQrCode(); + } + if ($this->getPixLocation() && $this->getValor() && $this->getID()) { + $this->setPixQrCode(Util::gerarPixCopiaECola($this->getPixLocation(), $this->getValor(), $this->getID(), new Pessoa(['nome' => Util::normalizeChars($nome), 'cidade' => Util::normalizeChars($cidade)]))); + } + + return $this->getPixQrCode(); + } } diff --git a/src/Cnab/Retorno/Cnab400/Header.php b/src/Cnab/Retorno/Cnab400/Header.php index bfe52c32..9befd949 100644 --- a/src/Cnab/Retorno/Cnab400/Header.php +++ b/src/Cnab/Retorno/Cnab400/Header.php @@ -1,49 +1,60 @@ 'Confirmação Entrada Título', '05' => 'Liquidação Sem Registro: Identifica a liquidação de título da modalidade ""SEM REGISTRO""', @@ -33,8 +34,9 @@ class Bancoob extends AbstractRetorno implements RetornoCnab400 '15' => 'Liquidação em Cartório: Identifica as liquidações dos títulos ocorridas em cartórios de protesto', '23' => 'Encaminhado a Protesto: Identifica o recebimento da instrução de protesto', '27' => 'Confirmação Alteração Dados.', - '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança"' + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança"', ]; + /** * Array com as possiveis rejeicoes do banco. * @@ -67,7 +69,7 @@ class Bancoob extends AbstractRetorno implements RetornoCnab400 '73' => 'Débito não agendado – Data de vencimento inválida', '74' => 'Débito não agendado – Conforme seu pedido, Título não registrado', '75' => 'Débito não agendado – Tipo de número de inscrição do debitado inválido', -]; + ]; /** * Roda antes dos metodos de processar @@ -75,11 +77,11 @@ class Bancoob extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -87,7 +89,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -110,7 +112,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -125,14 +127,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(176, 181, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('05', '06')) { @@ -150,21 +152,9 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('14')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { + } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -177,7 +167,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Banrisul.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Banrisul.php index 0891d97a..9ce7d957 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Banrisul.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Banrisul.php @@ -1,15 +1,16 @@ 'Cancelamento dos dados do rateio', ]; - /** * Array com as possiveis descricoes de baixa e liquidacao. * @@ -146,12 +146,12 @@ class Banrisul extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'erros' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'erros' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -159,7 +159,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -179,7 +179,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -194,13 +194,13 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(296, 301, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); /** * ocorrencias @@ -208,42 +208,16 @@ protected function processarDetalhe(array $detalhe) $msgAdicional = str_split(sprintf('%010s', $this->rem(383, 392, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '25', '08')) { $this->totais['liquidados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02', '47')) { $this->totais['entradas']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); } elseif ($d->hasOcorrencia('04', '08', '10')) { $this->totais['baixados']++; - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), - Arr::get($this->baixa_liquidacao, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->baixa_liquidacao, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->baixa_liquidacao, $msgAdicional[0], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[1], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[2], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[3], ''), Arr::get($this->baixa_liquidacao, $msgAdicional[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('40')) { $this->totais['protestados']++; @@ -265,16 +239,16 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeTitulos((int) $this->rem(18, 25, $trailer)) ->setQuantidadeErros((int) $this->totais['erros']) - ->setQuantidadeEntradas((int) $this->rem(49, 55, $trailer)) - ->setQuantidadeLiquidados((int) $this->rem(71, 77, $trailer)) + ->setQuantidadeEntradas((int) $this->rem(49, 55, $trailer)) + ->setQuantidadeLiquidados((int) $this->rem(71, 77, $trailer)) ->setQuantidadeBaixados((int) $this->totais['baixados']) ->setQuantidadeAlterados((int) $this->totais['alterados']); diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bb.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bb.php index 6f1454d1..435f3fef 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bb.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bb.php @@ -1,11 +1,13 @@ totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -174,7 +176,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -197,7 +199,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -216,15 +218,15 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(176, 181, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); if ($d->hasOcorrencia('05', '06', '07', '08', '15')) { $this->totais['liquidados']++; @@ -255,12 +257,12 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeTitulos((int) $this->rem(18, 25, $trailer)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bnb.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bnb.php index ebe61f5f..18a38c2d 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bnb.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bnb.php @@ -1,11 +1,13 @@ 'Erro ocorrencia 19', '70' => 'Erro ocorrencia 20', '71' => 'Erro ocorrencia 21', - '72' => 'Erro ocorrencia 22' + '72' => 'Erro ocorrencia 22', ]; /** @@ -65,12 +67,12 @@ class Bnb extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -78,7 +80,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -99,14 +101,14 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { $d = $this->detalheAtual(); // Verifica data de crédotp (não vem no retorno mas uso pra saber se foi liquidado) if ($this->rem(254, 266, $detalhe) == '0000000000000') { - $dataCredito = ""; + $dataCredito = ''; } else { $dataCredito = $this->rem(111, 116, $detalhe); } @@ -119,13 +121,13 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($dataCredito) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) ->setValorIOF(Util::nFloat(0.00, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) ->setValorMulta(Util::nFloat(0.00, 2, false)); if ($d->hasOcorrencia('06', '07', '08')) { @@ -157,13 +159,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos((int) $this->rem(18, 25, $trailer)) - ->setValorTitulos((float) Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos((float) Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bradesco.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bradesco.php index bfe5c026..7b7bcde3 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bradesco.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Bradesco.php @@ -1,11 +1,13 @@ "Entrada Confirmada", - "03" => "Entrada Rejeitada", - "06" => "Liquidação normal (sem motivo)", - "09" => "Baixado Automat. via Arquivo", - "10" => "Baixado conforme instruções da Agência", - "11" => "Em Ser - Arquivo de Títulos pendentes (sem motivo)", - "12" => "Abatimento Concedido (sem motivo)", - "13" => "Abatimento Cancelado (sem motivo)", - "14" => "Vencimento Alterado (sem motivo)", - "15" => "Liquidação em Cartório (sem motivo)", - "16" => "Título Pago em Cheque - Vinculado", - "17" => "Liquidação após baixa ou Título não registrado (sem motivo)", - "18" => "Acerto de Depositária (sem motivo)", - "19" => "Confirmação Receb. Inst. de Protesto", - "20" => "Confirmação Recebimento Instrução Sustação de Protesto (sem motivo)", - "21" => "Acerto do Controle do Participante (sem motivo)", - "22" => "Título Com Pagamento Cancelado", - "23" => "Entrada do Título em Cartório (sem motivo)", - "24" => "Entrada rejeitada por CEP Irregular", - "27" => "Baixa Rejeitada", - "28" => "Débito de tarifas/custas", - "30" => "Alteração de Outros Dados Rejeitados", - "32" => "Instrução Rejeitada", - "33" => "Confirmação Pedido Alteração Outros Dados (sem motivo)", - "34" => "Retirado de Cartório e Manutenção Carteira (sem motivo)", - "35" => "Desagendamento do débito automático", - "40" => "Estorno de pagamento (Novo)", - "55" => "Sustado judicial (Novo)", - "68" => "Acerto dos dados do rateio de Crédito", - "69" => "Cancelamento dos dados do rateio", + '02' => 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '06' => 'Liquidação normal (sem motivo)', + '09' => 'Baixado Automat. via Arquivo', + '10' => 'Baixado conforme instruções da Agência', + '11' => 'Em Ser - Arquivo de Títulos pendentes (sem motivo)', + '12' => 'Abatimento Concedido (sem motivo)', + '13' => 'Abatimento Cancelado (sem motivo)', + '14' => 'Vencimento Alterado (sem motivo)', + '15' => 'Liquidação em Cartório (sem motivo)', + '16' => 'Título Pago em Cheque - Vinculado', + '17' => 'Liquidação após baixa ou Título não registrado (sem motivo)', + '18' => 'Acerto de Depositária (sem motivo)', + '19' => 'Confirmação Receb. Inst. de Protesto', + '20' => 'Confirmação Recebimento Instrução Sustação de Protesto (sem motivo)', + '21' => 'Acerto do Controle do Participante (sem motivo)', + '22' => 'Título Com Pagamento Cancelado', + '23' => 'Entrada do Título em Cartório (sem motivo)', + '24' => 'Entrada rejeitada por CEP Irregular', + '27' => 'Baixa Rejeitada', + '28' => 'Débito de tarifas/custas', + '30' => 'Alteração de Outros Dados Rejeitados', + '32' => 'Instrução Rejeitada', + '33' => 'Confirmação Pedido Alteração Outros Dados (sem motivo)', + '34' => 'Retirado de Cartório e Manutenção Carteira (sem motivo)', + '35' => 'Desagendamento do débito automático', + '40' => 'Estorno de pagamento (Novo)', + '55' => 'Sustado judicial (Novo)', + '68' => 'Acerto dos dados do rateio de Crédito', + '69' => 'Cancelamento dos dados do rateio', ]; /** @@ -102,12 +104,12 @@ class Bradesco extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -115,7 +117,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -134,7 +136,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -145,6 +147,10 @@ protected function processarDetalhe(array $detalhe) ->setContaDv($this->rem(37, 37, $detalhe)); } + if ($this->rem(1, 1, $detalhe) == 4) { + return $this->processarPix($detalhe); + } + $d = $this->detalheAtual(); $d->setCarteira($this->rem(108, 108, $detalhe)) ->setNossoNumero($this->rem(71, 82, $detalhe)) @@ -155,14 +161,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(296, 301, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '15', '17')) { @@ -182,24 +188,12 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - if($d->hasOcorrencia('03')) { - if(isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ - $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); - } + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } } - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -212,13 +206,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) @@ -227,4 +221,18 @@ protected function processarTrailer(array $trailer) return true; } + + /** + * @param array $detalhe + * @return bool + * @throws ValidationException + */ + private function processarPix(array $detalhe) + { + $d = $this->getDetalhe($this->increment - 1); + $d->setPixLocation($this->rem(29, 105, $detalhe)); + $d->setId($this->rem(106, 140, $detalhe)); + + return false; + } } diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/C6.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/C6.php new file mode 100644 index 00000000..082be7cc --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/C6.php @@ -0,0 +1,385 @@ + 'Entrada confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Alteração de Dados (Entrada)', + '05' => 'Alteração de Dados (Baixa)', + '06' => 'Liquidação Normal', + '07' => 'Liquidação após Baixa', + '08' => 'Liquidação em Cartório', + '09' => 'Baixa Simples', + '10' => 'Baixa comandada do cliente arquivo', + '12' => 'Abatimento concedido', + '13' => 'Abatimento cancelado', + '14' => 'Vencimento alterado', + '15' => 'Baixa rejeitada', + '16' => 'Instrução rejeitada', + '17' => 'Alterações de dados rejeitados', + '19' => 'Confirma instrução de protesto', + '20' => 'Confirma instrução de sustação de protesto', + '21' => 'Confirma instrução de não protestar', + '23' => 'Protesto enviado a cartório', + '29' => 'Sacado nao retirou boleto eletronicamente,enviado para correio', + '32' => 'Baixa por ter sido protestado', + '35' => 'Alegações do sacado', + '36' => 'Custas de Edital', + '37' => 'Custas de sustação judicial', + '38' => 'Título sustado judicialmente', + '65' => 'Pagamento com Cheque - Aguardando compensação', + '69' => 'Cancelamento de Liquidação por Cheque Devolvido', + '71' => 'Protesto cancelado pelo Cartório', + '72' => 'Baixa Operacional', + '74' => 'Cancelamento da Baixa Operacional', + '75' => 'Pagamento Parcial', + '90' => 'Instrução de Protesto Rejeitada', + '95' => 'Troca Uso Empresa', + '96' => 'Emissão Extrato Mov. Carteira', + '97' => 'Tarifa de sustação de protesto', + '98' => 'Tarifa de protesto', + '99' => 'Custas de protesto', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '1818' => 'boleto não retirado pelo sacado. reenviado pelo correio para carteiras com emissão pelo banco', + '9000' => 'data vencimento menor que o prazo de aceitação do título', + '9001' => 'sacado bloqueado por atraso', + '9002' => 'registro opcional inválido', + '9003' => 'cep sem praça de cobrança', + '9004' => 'prazo insuficiente para cobrança do título', + '9005' => 'Campo numérico inválido', + '9006' => 'Campo texto inválido', + '9007' => 'Campo tipo data inválido', + '9008' => 'Caractere inválido', + '9009' => 'cpf/cnpj do sacado e emitente devem ser diferentes', + '9010' => 'data vencimento menor que a data de emissão', + '9011' => 'data emissão maior que a data atual', + '9012' => 'uf sacado inválido', + '9013' => 'uf emitente inválido', + '9014' => 'Campo obrigatório não preenchido', + '9015' => 'cpf do sacado inválido', + '9016' => 'cnpj do sacado inválido', + '9017' => 'o nome do sacado enviado não confere com o nome do sacado cadastrado no sistema para este cnpj/cpf', + '9018' => 'tipo do sacado inválido', + '9019' => 'o sacado está bloqueado', + '9020' => 'o endereço do sacado esta com o tamanho esta maior que o permitido', + '9021' => 'digito do nosso numero inválido', + '9022' => 'não existe faixa cadastrada para o banco e a conta', + '9023' => 'o nosso numero esta fora da faixa cadastrada para o cedente', + '9024' => 'identificação do título inválida', + '9025' => 'ocorrência não permitida pois o título esta baixado', + '9026' => 'ocorrência não permitida pois o título esta liquidado', + '9027' => 'ocorrência não permitida pois o título esta em protesto', + '9028' => 'não é permitida alteração de vencimento para carteira de desconto', + '9029' => 'situação do título inválida', + '9030' => 'não foi possível conceder o abatimento', + '9031' => 'não existe abatimento a ser cancelado', + '9032' => 'não foi possível prorrogar a data de vencimento do título', + '9033' => 'evento não permitido para situação do título', + '9034' => 'evento não permitido para cheques', + '9035' => 'o código do registro esta diferente de 1', + '9036' => 'Agência inválida', + '9037' => 'Número da Conta Corrente para depósito Inválido', + '9038' => 'o cnpj do cedente passado para o arquivo não confere com o cnpj do cedente cadastrado para o arquivo', + '9040' => 'cnpj do cedente não encontrado no cadastro', + '9041' => 'tipo do emitente inválido', + '9042' => 'cnpj do emitente inválido', + '9045' => 'campo nosso numero deve ter um valor de, no máximo , 10 digitos quando a carteira de cobrança não é direta', + '9046' => 'no campo nosso número a identificação do título esta inválida', + '9047' => 'banco e conta de cobrança direta não informados', + '9049' => 'campo aceite enviado com valor nulo ou inválido', + '9050' => 'data de emisão inválida', + '9051' => 'data de vencimento inválida', + '9052' => 'Data de desconto 2 inválida', + '9053' => 'especie de titulo invalida', + '9054' => 'especie de titulo não encontrada', + '9055' => 'valor de título inválido', + '9056' => 'prazo de cartorio invalido', + '9057' => 'valor de abatimento inválido', + '9058' => 'valor de desconto inválido', + '9059' => 'código de ocorrência inválida ou inexistente', + '9060' => 'tipo de mora inválido', + '9062' => 'valor de juros ao dia inválido', + '9063' => 'a data de juros mora é anterior à data de vencimento. favor verificar estes campos.', + '9064' => 'a data de juros mora inválida', + '9065' => 'número da sequência diferente do esperado', + '9066' => 'numero de sequencia inválido', + '9067' => 'registro inválido', + '9068' => 'cpf do emitente inválido', + '9070' => 'nome do emitente inválido', + '9071' => 'endereço do emitente inválido', + '9072' => 'cidade do emitente inválida', + '9073' => 'cep do emitente inválido', + '9074' => 'este contrato não está cadastrado para o cedente', + '9075' => 'não é permitida a entrada de títulos vencidos', + '9078' => 'não existe endereço, uf e cidade para o título', + '9079' => 'nosso número inválido', + '9081' => 'prazo insuficiente para cobrança do título neste cep', + '9083' => 'o cedente não pode enviar esse tipo de título com esta carteira', + '9084' => 'seu número do registro opcional diferente da linha do registro do título', + '9085' => 'data de vencimento do registro opcional diferente da linha do registro do título.', + '9086' => 'valor do título no vencimento do registro opcional diferente da linha do registro do título.', + '9087' => 'os títulos de carteira de cobrança direta só podem ser enviados para contas de cobrnaça direta. acao: confira a carteira e a conta cobrança que está sendo enviada/atribuida ao título.', + '9089' => 'código cmc7 invalido', + '9090' => 'entrada - nosso número já está sendo utilizado para mesmo banco / conta', + '9091' => 'cep do sacado não pertence ao estado da federação (uf) informado', + '9092' => 'tipo de multa inválido', + '9093' => 'registro opcional de emitente inválido', + '9097' => 'O campo Nosso Número não foi informado ou não foi possivel identificar o titulo.', + '9098' => 'foi encontrado mais de um título para esse nosso número.', + '9099' => 'preencha o campo de "conta de cobrança" no cadastro de carteira por cedente.', + '9100' => 'título possui registro opcional de emitente e a sua configuração não permite envio de títulos de terceiros.', + '9101' => 'título possui emitente, porém seus dados não foram informados.', + '9103' => 'ja existe titulo em aberto cadastrado para este cedente/seu numero/data vencimento/valor e emitente', + '9104' => 'impedido pela legislação vigente', + '9105' => 'crédito retido', + '9106' => 'nosso numero nao informado', + '9107' => 'tamanho máximo do nosso número para cobrança direta é 10 posições + digito(layout padrao matera/bradesco).', + '9108' => 'título pertence a uma espécie que não pode ser protestada.', + '9109' => 'protesto não permitido para título com moeda diferente de real.', + '9110' => 'cep do sacado não atendido pelos cartórios cadastrados.', + '9113' => 'Não permitimos troca de carteira no evento de Alteração de Outros Dados.', + '9114' => 'Não permitimos troca de tipo titulo no evento de Alteração de Outros Dados.', + '9201' => 'liquidação em cartório', + '9202' => 'baixa decurso prazo - banco', + '9203' => 'baixa protestado', + '9204' => 'Tarifa de Sustacao de protesto', + '9205' => 'tarifa de protesto', + '9206' => 'custas de protesto', + '9207' => 'custas de edital', + '9208' => 'custas de sustação de protesto título sustado judicialmente', + '9210' => 'liquidação em cheque', + '9213' => 'tarifa de manutenção de título vencido', + '9216' => 'liquidação no guichê de caixa em dinheiro', + '9217' => 'liquidação em banco correspondente', + '9218' => 'liquidação por compensação eletrônica', + '9219' => 'liquidação por conta', + '9222' => 'emissão extrato mov. carteira', + '9223' => 'Liquidação por STR', + '9224' => 'Carteira do Tipo G não pode inserir titulos.', + '9230' => 'Valor desconto 2 inválido', + '9232' => 'Sacado pertence a empresa do grupo (coligada)', + '9233' => 'Por solicitação da diretoria de crédito/comercial', + '9234' => 'Inexistência de relação com o cedente', + '9235' => 'Outros', + '9236' => 'Recusado - Outros Motivos', + '9237' => 'Baixa por Outros Motivos', + '9238' => 'Pagador Rejeita Boleto', + '9239' => 'Pagador Aceita Boleto', + '9240' => 'Data multa menor que data de vencimento do título', + '9242' => 'Baixa Integral Interbancária', + '9243' => 'Baixa Integral Intrabancária', + '9244' => 'Baixa Parcial Intrabancária', + '9245' => 'Baixa Parcial Interbancária', + '9250' => 'Tipo de autorização para recebimento de valor divergente inválido', + '9251' => 'Indicativo Tipo de valor ou percentual inválido', + '9252' => 'Quantidade de pagamento parcial inválido', + '9253' => 'Quantidade de pagamento parcial inválido, somente é permitido um valor maior ou igual a quantidade de pagamentos já recebido', + '9254' => 'Mínimo não aceito para o título', + '9255' => 'Máximo não aceito para o título', + '9258' => 'Data de desconto 3 inválida', + '9259' => 'Valor desconto 3 inválido', + '9260' => 'Mínimo é obrigatório quando informado o tipo valor ou percentual', + '9261' => 'Tipo de autorização de recebimento de valor divergente não permitio para tipo de título 31', + '9262' => 'Para especie de título diferente de fatura de cartão de crédito não é possível informar o tipo aceita qualquer valor com range mínimo e máximo preenchido', + '9263' => 'Mínimo e Máximo tem que ser informado para o tipo de autorização de valor divergente igual a 2', + '9264' => 'Mínimo e Máximo não devem ser informados para o tipo de autorização de valor divergente igual a 3', + '9265' => 'Mínimo deve ser informado e Máximo não pode ser informado para o tipo de autorização de valor divergente igual a 4', + '9266' => 'Valor não permitido para tipo de título fatura de cartão de crédito', + '9267' => 'Não é permitido ter juros, multa, abatimento, desconto ou protesto tipo de título fatura de cartão de crédito', + '9999' => 'cep do sacado inválido', + ]; + + /** + * Campos com possíveis erros + * @var string[] + */ + private $campoInvalido = [ + '004' => 'CNPJ da Empresa', + '018' => 'Código da Empresa', + '063' => 'Nosso Número', + '074' => 'Digito Verificador nosso número', + '107' => 'Código da Carteira', + '109' => 'Código Ocorrência Remessa', + '111' => 'Seu Número', + '121' => 'Data Vencimento', + '127' => 'Valor Título', + '148' => 'Espécie do Título', + '150' => 'Aceite', + '151' => 'Data Emissão Título', + '157' => 'Instrução 1', + '159' => 'Instrução 2', + '161' => 'Juros ao Dia', + '174' => 'Data Desconto ', + '180' => 'Valor Desconto ', + '193' => 'Data Multa', + '206' => 'Valor Abatimento', + '219' => 'Tipo Sacado', + '221' => 'CNPJ / CPF Sacado', + '235' => 'Nome do Sacado', + '275' => 'Endereço Sacado', + '315' => 'Bairro Sacado', + '327' => 'CEP Sacado', + '335' => 'Cidade Sacado', + '350' => 'UF Sacado', + '352' => 'Sacador', + '382' => 'Tipo de Multa', + '383' => 'Percentual de Multa', + '386' => 'Data Juros Mora', + '392' => 'Prazo dias para Cartório', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 19, $header)) + ->setConta($this->rem(27, 38, $header)) + ->setCodigoCliente($this->rem(39, 50, $header)) + ->setData($this->rem(125, 130, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + $d->setCarteira($this->rem(107, 108, $detalhe)) + ->setNossoNumero($this->rem(63, 73, $detalhe)) + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setDataCredito($this->rem(296, 301, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); + + $codErro = str_split(sprintf('%016s', $this->rem(378, 393, $detalhe)), 4) + array_fill(0, 4, ''); + + if ($d->hasOcorrencia('06', '08')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('07', '09', '10', '32', '72')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('23')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('04', '05', '14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '15', '16', '17', '90')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $codErro[0], ''), + Arr::get($this->rejeicoes, $codErro[1], ''), + Arr::get($this->rejeicoes, $codErro[2], ''), + Arr::get($this->rejeicoes, $codErro[3], '') + ); + if (in_array($codErro[0], ['9005', '9006', '9007', '9008']) + || in_array($codErro[1], ['9005', '9006', '9007', '9008']) + || in_array($codErro[2], ['9005', '9006', '9007', '9008']) + || in_array($codErro[3], ['9005', '9006', '9007', '9008'])) { + $posicaoInvalida = str_split(sprintf('%012s', $this->rem(366, 377, $detalhe)), 3) + array_fill(0, 4, ''); + $error .= Util::appendStrings( + Arr::get($this->campoInvalido, $posicaoInvalida[0], ''), + Arr::get($this->campoInvalido, $posicaoInvalida[1], ''), + Arr::get($this->campoInvalido, $posicaoInvalida[2], ''), + Arr::get($this->campoInvalido, $posicaoInvalida[3], '') + ); + } + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->rem(17, 22, $trailer)) + ->setValorTitulos(Util::nFloat($this->rem(3, 16, $trailer) / 100, 2, false)) + ->setQuantidadeErros((int) $this->totais['erros']) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->rem(37, 42, $trailer)) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Caixa.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Caixa.php index 34cc7f9c..180cc663 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Caixa.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Caixa.php @@ -1,11 +1,13 @@ 'Estorno de Baixa/Liquidação', '34' => 'Transferência de Carteira/Entrada', '35' => 'Transferência de Carteira/Baixa', - '99' => 'Rejeição do Título – Cód. Rejeição informado nas POS 80 a 82' + '99' => 'Rejeição do Título – Cód. Rejeição informado nas POS 80 a 82', ]; /** @@ -93,12 +95,12 @@ protected function init() { $this->totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -106,7 +108,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -130,7 +132,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -144,14 +146,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(294, 299, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $this->totais['valor_recebido'] += $d->getValorRecebido(); diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Cresol.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Cresol.php new file mode 100644 index 00000000..09095536 --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Cresol.php @@ -0,0 +1,323 @@ + 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '04' => 'Transferência de carteira/entrada', + '05' => 'Transferência de carteira/baixa', + '06' => 'Liquidação', + '07' => 'Confirmação do Recebimento da Instrução de Desconto', + '08' => 'Confirmação do Recebimento do Cancelamento do Desconto', + '09' => 'Baixa', + '11' => 'Em Ser - Títulos em carteira', + '12' => 'Confirmação recebimento instrução de abatimento', + '13' => 'Confirmação recebimento instrução de cancelamento de abatimento', + '14' => 'Confirmação recebimento instrução alteração de vencimento', + '15' => 'Franco de pagamento', + '17' => 'Liquidação após baixa ou liquidação de título não registrado', + '19' => 'Confirmação Receb. Inst. de Protesto', + '20' => 'Confirmação recebimento instrução de sustação/cancelamento de protesto', + '23' => 'Remessa a cartório (aponte em cartório)', + '24' => 'Retirada de cartório e manutenção em carteira', + '25' => 'Protestado e baixado (baixa por ter sido protestado)', + '26' => 'Instrução rejeitada', + '27' => 'Confirmação do pedido de alteração de outros dados', + '28' => 'Débito de tarifas/custas', + '29' => 'Ocorrências do pagador', + '30' => 'Alteração de Outros Dados Rejeitados', + '33' => 'Confirmação da Alteração dos Dados do Rateio de Crédito', + '34' => 'Confirmação do Cancelamento dos Dados do Rateio de Crédito', + '35' => 'Confirmação do Desagendamento do Débito Automático', + '36' => 'Confirmação de envio de e-mail/SMS', + '37' => 'Envio de e-mail/SMS rejeitado', + '38' => 'Confirmação de alteração do Prazo Limite de Recebimento', + '39' => 'Confirmação de Dispensa de Prazo Limite de Recebimento', + '40' => 'Confirmação da alteração do número do título dado pelo cedente', + '41' => 'Confirmação da alteração do número controle do Participante', + '42' => 'Confirmação da alteração dos dados do Sacado', + '43' => 'Confirmação da alteração dos dados do Sacador/Avalista', + '44' => 'Título pago com cheque devolvido', + '45' => 'Título pago com cheque compensado', + '46' => 'Instrução para cancelar protesto confirmada', + '47' => 'Instrução para protesto para fins falimentares confirmada', + '48' => 'Confirmação de instrução de transferência de carteira/modalidade de cobrança', + '49' => 'Alteração de contrato de cobrança', + '50' => 'Título pago com cheque pendente de liquidação', + '51' => 'Título DDA reconhecido pelo sacado', + '52' => 'Título DDA não reconhecido pelo sacado', + '53' => 'Título DDA recusado pela CIP', + '54' => 'Confirmação da Instrução de Baixa de Título Negativado sem Protesto', + '55' => 'Confirmação de Pedido de Dispensa de Multa', + '56' => 'Confirmação do Pedido de Cobrança de Multa', + '57' => 'Confirmação do Pedido de Alteração de Cobrança de Juros', + '58' => 'Confirmação do Pedido de Alteração do Valor/Data de Desconto', + '59' => 'Confirmação do Pedido de Alteração do Cedente do Título', + '60' => 'Confirmação do Pedido de Dispensa de Juros de Mora', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '1' => 'Código do Banco Inválido', + '2' => 'Código do Registro Detalhe Inválido', + '3' => 'Código do Segmento Inválido', + '4' => 'Código de Movimento Não Permitido para Carteira', + '5' => 'Código de Movimento Inválido', + '6' => 'Tipo/Número de Inscrição do Cedente Inválidos', + '7' => 'Agência/Conta/DV Inválido', + '8' => 'Nosso Número Inválido', + '9' => 'Nosso Número Duplicado', + '10' => 'Carteira Inválida', + '11' => 'Forma de Cadastramento do Título Inválido', + '12' => 'Tipo de Documento Inválido', + '13' => 'Identificação de Emissão do Bloqueto Inválida', + '14' => 'Identificação da Distribuição do Bloqueto Inválida', + '15' => 'Características da Cobrança Incompatíveis', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior a Data de Emissão', + '18' => 'Vencimento Fora do Prazo de Operação', + '19' => 'Título a Cargo de Bancos Correspondentes com Vencimento Inferior a XX Dias', + '20' => 'Valor do Título Inválido', + '21' => 'Espécie do Título Inválida', + '22' => 'Espécie do Título Não Permitida para a Carteira', + '23' => 'Aceite Inválido', + '24' => 'Data de Emissão Inválida', + '25' => 'Data da Emissão Posterior a Data de Entrada', + '26' => 'Código de Juros de Mora Inválido', + '27' => 'Valor/Taxa de Juros de Mora Inválido', + '28' => 'Código do Desconto Inválido', + '29' => 'Valor do Desconto Maior ou Igual ao Valor do Título', + '30' => 'Desconto a Conceder Não Confere', + '31' => 'Concessão de Desconto - Já Existe Desconto Anterior', + '32' => 'Valor do IOF Inválido', + '33' => 'Valor do Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do Título', + '35' => 'Valor a Conceder Não Confere', + '36' => 'Concessão de Abatimento - Já Existe Abatimento Anterior', + '37' => 'Código para Protesto Inválido', + '38' => 'Prazo para Protesto Inválido', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto', + '42' => 'Código para Baixa/Devolução Inválido', + '43' => 'Prazo para Baixa/Devolução Inválida', + '44' => 'Código da Moeda Inválido', + '45' => 'Nome do Sacado Não Informado', + '46' => 'Tipo/Número de Inscrição do Sacado Inválido', + '47' => 'Endereço do Sacado Não Informado', + '48' => 'CEP Inválido', + '49' => 'CEP Sem Praça de Cobrança (Não Localizado)', + '50' => 'CEP Referente a um Banco Correspondente', + '51' => 'CEP imcompatível com a Unidade da Federação', + '52' => 'Registro de Título já liquidado Cart. 17', + '53' => 'Tipo/Número de Inscrição do Sacador/Avalista Inválidos', + '54' => 'Sacador/Avalista Não Informado', + '55' => 'Nosso Número no Banco Correspondente Não Informado', + '56' => 'Código do Banco Correspondente Não Informado', + '57' => 'Código da Multa Inválido', + '58' => 'Data da Multa Inválida', + '59' => 'Valor/Percentual da Multa Inválido', + '60' => 'Movimento para Título Não Cadastrado', + '61' => 'Alteração da Agência Cobradora/DV Inválida', + '62' => 'Tipo de Impressão Inválido', + '63' => 'Entrada para Título já Cadastrado', + '64' => 'Número da Linha Inválido', + '65' => 'Código do Banco para Débito Inválido', + '66' => 'Agência/Conta/DV para Débito Inválido', + '67' => 'Dados para Débito incompatível com a Identificação da Emissão do Bloqueto', + '68' => 'Débito Automático Agendado', + '69' => 'Débito Não Agendado - Erro nos Dados da Remessa', + '70' => 'Débito Não Agendado - Sacado Não Consta do Cadastro de Autorizante', + '71' => 'Débito Não Agendado - Cedente Não Autorizado pelo Sacado', + '72' => 'Débito Não Agendado - Cedente Não Participa da Modalidade Débito Automático', + '73' => 'Débito Não Agendado - Código de Moeda Diferente de Reao (R$)', + '74' => 'Débito Não Agendado - Data Vencimento Inválida', + '75' => 'Débito Não Agendado, Conforme seu Pedido, Título Não Registrado', + '76' => 'Débito Não Agendado, Tipo/Num. Inscrição do Debitado, Inválido', + '77' => 'Transferência para Desconto Não Permitida para a Cateira do Título', + '78' => 'Data Inferior ou Igual ao Vencimento para Débito Automático', + '79' => 'Data Juros de Mora Inválido', + '80' => 'Data do Desconto Inválida', + '81' => 'Tentativas de Débito Esgotadas - Baixado', + '82' => 'Tentativas de Débito Esgotadas - Pendente', + '83' => 'Limite Excedido', + '84' => 'Número Autorização Inexistente', + '85' => 'Título com Pagamento Vinculado', + '86' => 'Seu Número Inválido', + '87' => 'e-mail/SMS enviado', + '88' => 'e-mail Lido', + '89' => 'e-mail/SMS devolvido - endereço de e-mail ou número do celular incorreto', + '90' => 'e-mail devolvido - caixa postal cheia', + '91' => 'e-mail/número do celular do sacado não informado', + '92' => 'Sacado optante por Bloqueto Eletrônico - e-mail não enviado', + '93' => 'Código para emissão de bloqueto não permite envio de e-mail', + '94' => 'Código da Carteira inválido para envio e-mail', + '95' => 'Contrato não permite o envio de e-mail', + '96' => 'Número de contrato inválido', + '97' => 'Rejeição da alteração do prazo limite de recebimento', + '98' => 'Rejeição de dispensa de prazo limite de recebimento', + '99' => 'Rejeição da alteração do número do título dado pelo cedente', + 'A1' => 'Rejeição da alteração do número controle do participante', + 'A2' => 'Rejeição da alteração dos dados do sacado', + 'A3' => 'Rejeição da alteração dos dados do sacador/avalista', + 'A4' => 'Sacado DDA', + 'A5' => 'Registro Rejeitado - Título já Liquidado', + 'A6' => 'Código do Convenente Inválido ou Encerrado', + 'A7' => 'Título se já encontra na situação Pretendida', + 'A8' => 'Valor do Abatimento inválido para cancelamento', + 'A9' => 'Não autoriza pagamento parcial', + 'B1' => 'Autoriza recebimento parcial', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws \Exception + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 26, $header)) + ->setCodigoCliente($this->rem(27, 46, $header)) + ->setData($this->rem(95, 100, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws \Exception + */ + protected function processarDetalhe(array $detalhe) + { + if ($this->count() == 1) { + $this->getHeader() + ->setAgencia($this->rem(25, 29, $detalhe)) + ->setConta($this->rem(30, 36, $detalhe)) + ->setContaDv($this->rem(37, 37, $detalhe)); + } + + $d = $this->detalheAtual(); + $d->setCarteira($this->rem(108, 108, $detalhe)) + ->setNossoNumero($this->rem(71, 82, $detalhe)) + //71 - 81 Identificação do Título no Banco / 82 Digito N/N + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setDataCredito($this->rem(296, 301, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); //outros creditos + + $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '15', '17')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09', '10')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('23')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { + $this->totais['erros']++; + $error = Util::appendStrings( + Arr::get($this->rejeicoes, $msgAdicional[0], ''), + Arr::get($this->rejeicoes, $msgAdicional[1], ''), + Arr::get($this->rejeicoes, $msgAdicional[2], ''), + Arr::get($this->rejeicoes, $msgAdicional[3], ''), + Arr::get($this->rejeicoes, $msgAdicional[4], '') + ); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } + } + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws \Exception + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) + ->setQuantidadeErros((int) $this->totais['erros']) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->totais['liquidados']) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Delbank.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Delbank.php index 550a182d..a6a765e3 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Delbank.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Delbank.php @@ -1,11 +1,13 @@ "Confirma Entrada Título na CIP", - "02" => "Entrada Confirmada", - "03" => "Entrada Rejeitada", - "05" => "Campo Livre Alterado", - "06" => "Liquidação Normal", - "08" => "Liquidação em Cartório", - "09" => "Baixa Automática", - "10" => "Baixa por ter sido liquidado", - "12" => "Confirma Abatimento", - "13" => "Abatimento Cancelado", - "14" => "Vencimento Alterado", - "15" => "Baixa Rejeitada", - "16" => "Instrução Rejeitada", - "19" => "Confirma Recebimento de Ordem de Protesto", - "20" => "Confirma Recebimento de Ordem de Sustação", - "22" => "Seu número alterado", - "23" => "Título enviado para cartório", - "24" => "Confirma recebimento de ordem de não protestar", - "28" => "Débito de Tarifas/Custas – Correspondentes", - "40" => "Tarifa de Entrada (debitada na Liquidação)", - "43" => "Baixado por ter sido protestado", - "96" => "Tarifa Sobre Instruções – Mês anterior", - "97" => "Tarifa Sobre Baixas – Mês Anterior", - "98" => "Tarifa Sobre Entradas – Mês Anterior", - "99" => "Tarifa Sobre Instruções de Protesto/Sustação – Mês Anterio" + '01' => 'Confirma Entrada Título na CIP', + '02' => 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '05' => 'Campo Livre Alterado', + '06' => 'Liquidação Normal', + '08' => 'Liquidação em Cartório', + '09' => 'Baixa Automática', + '10' => 'Baixa por ter sido liquidado', + '12' => 'Confirma Abatimento', + '13' => 'Abatimento Cancelado', + '14' => 'Vencimento Alterado', + '15' => 'Baixa Rejeitada', + '16' => 'Instrução Rejeitada', + '19' => 'Confirma Recebimento de Ordem de Protesto', + '20' => 'Confirma Recebimento de Ordem de Sustação', + '22' => 'Seu número alterado', + '23' => 'Título enviado para cartório', + '24' => 'Confirma recebimento de ordem de não protestar', + '28' => 'Débito de Tarifas/Custas – Correspondentes', + '40' => 'Tarifa de Entrada (debitada na Liquidação)', + '43' => 'Baixado por ter sido protestado', + '96' => 'Tarifa Sobre Instruções – Mês anterior', + '97' => 'Tarifa Sobre Baixas – Mês Anterior', + '98' => 'Tarifa Sobre Entradas – Mês Anterior', + '99' => 'Tarifa Sobre Instruções de Protesto/Sustação – Mês Anterio', ]; /** @@ -55,47 +57,47 @@ class Delbank extends AbstractRetorno implements RetornoCnab400 * @var array */ private $rejeicoes = [ - "04" => "Data de vencimento não numérica ou inválida", - "05" => "Data de Vencimento inválida ou fora do prazo mínimo", - "14" => "Registro em duplicidade", - "19" => "Data de desconto inválida ou maior que a data de vencimento", - "20" => "Campo livre não informado", - "21" => "Título não registrado no sistema", - "22" => "Título baixado ou liquidado", - "26" => "Espécie de documento inválida", - "27" => "Instrução não aceita, por não ter sido emitida ordem de protesto ao cartório", - "28" => "Título tem instrução de cartório ativa", - "29" => "Título não tem instrução de carteira ativa", - "30" => "Existe instrução de não protestar, ativa para o título", - "36" => "Valor de permanência (mora) não numérico ", - "37" => "Título Descontado – Instrução não permitida para a carteira", - "38" => "Valor do abatimento não numérico ou maior que a soma do valor do título + permanência + multa", - "39" => "Título em cartório", - "40" => "Instrução recusada – Reprovado no Represamento para Análise", - "44" => "Título zerado ou em branco; ou não numérico na remessa", - "51" => "Tipo/Número de Inscrição Sacador/Avalista Inválido", - "53" => "Prazo de vencimento do título excede ao da contratação", - "57" => "Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.", - "AA" => "Serviço de cobrança inválido", - "AE" => "Título não possui abatimento", - "AG" => "Movimento não permitido – Título à vista ou contra apresentação", - "AH" => "Cancelamento de valores inválidos", - "AI" => "Nossa carteira inválida", - "AK" => "Título pertence a outro cliente", - "AU" => "Data da ocorrência inválida", - "AY" => "Título deve estar em aberto e vencido para acatar protesto", - "BA" => "Banco Correspondente Recebedor não é o Cobrador Atual", - "BB" => "Título deve estar em cartório para baixar", - "CB" => "Título possui protesto efetivado/a efetivar hoje", - "CT" => "Título já baixado", - "CW" => "Título já transferido", - "DO" => "Título em Prejuízo", - "IX" => "Título de Cartão de Crédito não aceita instruções", - "JK" => "Produto não permite alteração de valor de título", - "JQ" => "Título em Correspondente – Não alterar Valor", - "JS" => "Título possui Descontos/Abto/Mora/Multa", - "JT" => "Título possui Agenda de Protesto/Devolução", - "99" => "Ocorrência desconhecida na remessa" + '04' => 'Data de vencimento não numérica ou inválida', + '05' => 'Data de Vencimento inválida ou fora do prazo mínimo', + '14' => 'Registro em duplicidade', + '19' => 'Data de desconto inválida ou maior que a data de vencimento', + '20' => 'Campo livre não informado', + '21' => 'Título não registrado no sistema', + '22' => 'Título baixado ou liquidado', + '26' => 'Espécie de documento inválida', + '27' => 'Instrução não aceita, por não ter sido emitida ordem de protesto ao cartório', + '28' => 'Título tem instrução de cartório ativa', + '29' => 'Título não tem instrução de carteira ativa', + '30' => 'Existe instrução de não protestar, ativa para o título', + '36' => 'Valor de permanência (mora) não numérico ', + '37' => 'Título Descontado – Instrução não permitida para a carteira', + '38' => 'Valor do abatimento não numérico ou maior que a soma do valor do título + permanência + multa', + '39' => 'Título em cartório', + '40' => 'Instrução recusada – Reprovado no Represamento para Análise', + '44' => 'Título zerado ou em branco; ou não numérico na remessa', + '51' => 'Tipo/Número de Inscrição Sacador/Avalista Inválido', + '53' => 'Prazo de vencimento do título excede ao da contratação', + '57' => 'Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.', + 'AA' => 'Serviço de cobrança inválido', + 'AE' => 'Título não possui abatimento', + 'AG' => 'Movimento não permitido – Título à vista ou contra apresentação', + 'AH' => 'Cancelamento de valores inválidos', + 'AI' => 'Nossa carteira inválida', + 'AK' => 'Título pertence a outro cliente', + 'AU' => 'Data da ocorrência inválida', + 'AY' => 'Título deve estar em aberto e vencido para acatar protesto', + 'BA' => 'Banco Correspondente Recebedor não é o Cobrador Atual', + 'BB' => 'Título deve estar em cartório para baixar', + 'CB' => 'Título possui protesto efetivado/a efetivar hoje', + 'CT' => 'Título já baixado', + 'CW' => 'Título já transferido', + 'DO' => 'Título em Prejuízo', + 'IX' => 'Título de Cartão de Crédito não aceita instruções', + 'JK' => 'Produto não permite alteração de valor de título', + 'JQ' => 'Título em Correspondente – Não alterar Valor', + 'JS' => 'Título possui Descontos/Abto/Mora/Multa', + 'JT' => 'Título possui Agenda de Protesto/Devolução', + '99' => 'Ocorrência desconhecida na remessa', ]; /** @@ -104,12 +106,12 @@ class Delbank extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -117,7 +119,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -136,7 +138,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -157,14 +159,14 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(386, 391, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '08')) { @@ -184,24 +186,12 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '15', '16')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - if($d->hasOcorrencia('03')) { - if(isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ - $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); - } + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } } - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -214,13 +204,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) - ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer)/100, 2, false)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Fibra.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Fibra.php index a0e67e8f..c7abd9cb 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Fibra.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Fibra.php @@ -1,11 +1,13 @@ 'Confirma Entrada Título na CIP', '02' => 'Entrada Confirmada', @@ -211,7 +212,7 @@ class Fibra extends AbstractRetorno implements RetornoCnab400 'JS' => 'Título possui Descontos/Abto/Mora/Multa', 'JT' => 'Título possui Agenda de Protesto/Devolução', '99' => 'Ocorrência desconhecida na remessa', - ] + ], ]; /** @@ -220,11 +221,11 @@ class Fibra extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -232,7 +233,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -252,7 +253,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -266,13 +267,13 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(378, 385, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '08', '10')) { @@ -290,21 +291,9 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('05', '14', '22')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03', '15', '16')) { + } elseif ($d->hasOcorrencia('03', '15', '16')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -317,7 +306,6 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Hsbc.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Hsbc.php index 2eae79b4..cfc622ff 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Hsbc.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Hsbc.php @@ -1,11 +1,13 @@ totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -171,7 +173,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -192,7 +194,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -205,12 +207,12 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); $this->totais['valor_recebido'] += $d->getValorRecebido(); diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Inter.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Inter.php index 89d9cee3..3d1d38a6 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Inter.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Inter.php @@ -1,11 +1,13 @@ totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -56,7 +58,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -74,7 +76,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -95,8 +97,8 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(92, 97, $detalhe)) ->setDataVencimento($this->rem(119, 124, $detalhe)) ->setDataCredito($this->rem(173, 178, $detalhe)) - ->setValor(Util::nFloat(((float) $this->rem(125, 137, $detalhe))/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(160, 172, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat(((float) $this->rem(125, 137, $detalhe)) / 100, 2, false)) + ->setValorRecebido(Util::nFloat(((float) $this->rem(160, 172, $detalhe)) / 100, 2, false)); if ($d->hasOcorrencia('06')) { $this->totais['liquidados']++; @@ -109,10 +111,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); } elseif ($d->hasOcorrencia('03')) { $this->totais['erros']++; - $error = Util::appendStrings( - 'Entrada rejeitada', - $this->rem(241, 380, $detalhe) - ); + $error = Util::appendStrings('Entrada rejeitada', $this->rem(241, 380, $detalhe)); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -125,13 +124,13 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) - ->setValorTitulos(Util::nFloat($this->rem(121, 132, $trailer)/100, 2, false)) //Total dos valores dos títulos Pagos + ->setValorTitulos(Util::nFloat($this->rem(121, 132, $trailer) / 100, 2, false)) //Total dos valores dos títulos Pagos ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Itau.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Itau.php index 57178015..9b6d9a49 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Itau.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Itau.php @@ -1,11 +1,13 @@ detalheAtual(); + if ($this->rem(1, 1, $detalhe) == 3) { + return $this->processarPix($detalhe); + } + $d = $this->detalheAtual(); $d->setCarteira($this->rem(83, 85, $detalhe)) ->setNossoNumero($this->rem(86, 94, $detalhe)) ->setNumeroDocumento($this->rem(117, 126, $detalhe)) @@ -251,18 +256,7 @@ protected function processarDetalhe(array $detalhe) $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03', '15', '16', '17', '18', '60')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -275,7 +269,7 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarTrailer(array $trailer) { @@ -290,4 +284,39 @@ protected function processarTrailer(array $trailer) return true; } + + /** + * @param array $detalhe + * @return bool + * @throws ValidationException + */ + private function processarPix(array $detalhe) + { + $d = $this->getDetalhe($this->increment - 1); + + $aErrorPix = [ + '000' => null, + '001' => 'VALOR MAIOR QUE O MÁXIMO PERMITIDO', + '002' => 'NÃO É COMPATÍVEL COM O CNPJ INFORMADO', + '003' => 'CHAVE INVÁLIDA', + '004' => 'CHAVE SEM CADASTRO NA DICT', + '005' => 'CHAVE NÃO CADASTRADA NO MESMO CNPJ DA AG/CONTA DA REMESSA.', + '006' => 'EMISSÃO DE QR CODE NÃO PERMITIDA', + '007' => 'DATA DE DESCONTO MAIOR QUE A DATA DE VENCIMENTO', + '008' => 'IDLOCATION JÁ ESTÁ SENDO UTILIZADO POR OUTRA COBRANÇA PIX.', + '009' => 'LOCATION CRIADA PARA TIPO “COBRANÇA COM VENCIMENTO”', + '010' => 'BOLETO COM PIX NÃO É PERMITIDO PARA BOLETO COM PAGAMENTO PARCIAL', + '011' => 'BOLETO COM PIX NÃO É PERMITIDO PARA A CARTEIRA DO BOLETO', + '999' => 'PIX NÃO EMITIDO POR PROLEMAS NA PLATAFORMA. ENTRE EM CONTATO COM AS ÁREAS DE SUPORTE DO ITAÚ UNIBANCO', + ]; + + $d->setPixQrCode(trim($this->rem(2, 391, $detalhe))); + if ($decoded = Util::decodePixCopiaECola($d->getPixQrCode())) { + $d->setPixLocation(Arr::get($decoded, '26.25')); + $d->setId(Arr::get($decoded, '62.05')); + } + $d->appendError($aErrorPix[sprintf('%03s', $this->rem(392, 394, $detalhe))]); + + return false; + } } diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Ourinvest.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Ourinvest.php new file mode 100644 index 00000000..6213e6d9 --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Ourinvest.php @@ -0,0 +1,178 @@ + 'Nenhuma ocorrência informada', + '06' => 'Liquidação normal (sem motivo)', + '09' => 'Baixado Automat. via Arquivo', + '10' => 'Baixado conforme instruções da Agência', + '12' => 'Abatimento Concedido (sem motivo)', + '13' => 'Abatimento Cancelado (sem motivo)', + '14' => 'Vencimento Alterado (sem motivo)', + '15' => 'Liquidação em Cartório (sem motivo)', + '16' => 'Título Pago em Cheque - Vinculado', + '17' => 'Liquidação após baixa ou Título não registrado (sem motivo)', + '20' => 'Confirmação Recebimento Instrução Sustação de Protesto (sem motivo)', + '23' => 'Entrada do Título em Cartório (sem motivo)', + '28' => 'Débito de tarifas/custas', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '00' => 'Confirmação da ocorrência', + '02' => 'Tarifa de permanência título cadastrado', + '03' => 'Tarifa de sustação/Excl Negativação', + '04' => 'Tarifa de protesto/Incl Negativação', + '05' => 'Tarifa de outras instruções', + '06' => 'Tarifa de outras ocorrências', + '08' => 'Custas de protesto', + '10' => 'Baixa Comandada pelo cliente', + '15' => 'Título pago com cheque', + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 26, $header)) + ->setCodigoCliente($this->rem(27, 46, $header)) + ->setData($this->rem(95, 100, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + if ($this->count() == 1) { + $this->getHeader() + ->setAgencia($this->rem(25, 29, $detalhe)) + ->setConta($this->rem(30, 36, $detalhe)) + ->setContaDv($this->rem(37, 37, $detalhe)); + } + + $d = $this->detalheAtual(); + $d->setCarteira($this->rem(22, 24, $detalhe)) + ->setNossoNumero($this->rem(71, 82, $detalhe)) + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setDataCredito($this->rem(296, 301, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); + + $msgAdicional = str_split(sprintf('%08s', $this->rem(319, 328, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '15', '17', '20')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09', '10')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('23')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('14')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03')) { + $this->totais['erros']++; + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { + $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); + } + } + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + * @throws ValidationException + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->rem(18, 25, $trailer)) + ->setValorTitulos(Util::nFloat($this->rem(26, 39, $trailer) / 100, 2, false)) + ->setQuantidadeErros((int) $this->totais['erros']) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->totais['liquidados']) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Pine.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Pine.php index c9903ade..2e202379 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Pine.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Pine.php @@ -1,11 +1,13 @@ 'Confirma Entrada Título na CIP', '02' => 'Entrada Confirmada', @@ -211,7 +212,7 @@ class Pine extends AbstractRetorno implements RetornoCnab400 'JS' => 'Título possui Descontos/Abto/Mora/Multa', 'JT' => 'Título possui Agenda de Protesto/Devolução', '99' => 'Ocorrência desconhecida na remessa', - ] + ], ]; /** @@ -220,11 +221,11 @@ class Pine extends AbstractRetorno implements RetornoCnab400 protected function init() { $this->totais = [ - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, 'protestados' => 0, - 'alterados' => 0, + 'alterados' => 0, ]; } @@ -232,7 +233,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -252,7 +253,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -266,13 +267,13 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); $msgAdicional = str_split(sprintf('%08s', $this->rem(378, 385, $detalhe)), 2) + array_fill(0, 5, ''); if ($d->hasOcorrencia('06', '08', '10')) { @@ -290,21 +291,9 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('05', '14', '22')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03', '15', '16')) { + } elseif ($d->hasOcorrencia('03', '15', '16')) { $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), - Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '')); $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -317,7 +306,6 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception */ protected function processarTrailer(array $trailer) { diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Rendimento.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Rendimento.php new file mode 100644 index 00000000..ee6a3823 --- /dev/null +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Rendimento.php @@ -0,0 +1,323 @@ + 'Confirma Entrada Título na CIP', + '02' => 'Entrada Confirmada', + '03' => 'Entrada Rejeitada', + '05' => 'Campo Livre Alterado', + '06' => 'Liquidação Normal', + '08' => 'Liquidação em Cartório', + '09' => 'Baixa Automática', + '10' => 'Baixa por ter sido liquidado', + '12' => 'Confirma Abatimento', + '13' => 'Abatimento Cancelado', + '14' => 'Vencimento Alterado', + '15' => 'Baixa Rejeitada', + '16' => 'Instrução Rejeitada', + '19' => 'Confirma Recebimento de Ordem de Protesto', + '20' => 'Confirma Recebimento de Ordem de Sustação', + '22' => 'Seu número alterado', + '23' => 'Título enviado para cartório', + '24' => 'Confirma recebimento de ordem de não protestar', + '28' => 'Débito de Tarifas/Custas – Correspondentes', + '40' => 'Tarifa de Entrada (debitada na Liquidação)', + '43' => 'Baixado por ter sido protestado', + '96' => 'Tarifa Sobre Instruções – Mês anterior', + '97' => 'Tarifa Sobre Baixas – Mês Anterior', + '98' => 'Tarifa Sobre Entradas – Mês Anterior', + '99' => 'Tarifa Sobre Instruções de Protesto/Sustação – Mês Anterior', + ]; + + /** + * Array com as possiveis rejeicoes do banco. + * + * @var array + */ + private $rejeicoes = [ + '03' => [ + '03' => 'CEP inválido – Não temos cobrador – Cobrador não Localizado', + '04' => 'Sigla do Estado inválida', + '05' => 'Data de Vencimento inválida ou fora do prazo mínimo', + '06' => 'Código do Banco inválido', + '08' => 'Nome do sacado não informado', + '10' => 'Logradouro não informado', + '14' => 'Registro em duplicidade', + '19' => 'Data de desconto inválida ou maior que a data de vencimento', + '20' => 'Valor de IOF não numérico', + '21' => 'Movimento para título não cadastrado no sistema', + '22' => 'Valor de desconto + abatimento maior que o valor do título', + '25' => 'CNPJ ou CPF do sacado inválido (aceito com restrições)', + '26' => 'Espécie de documento inválida', + '27' => 'Data de emissão do título inválida', + '28' => 'Seu número não informado', + '29' => 'CEP é igual a espaço ou zeros; ou não numérico', + '30' => 'Valor do título não numérico ou inválido', + '36' => 'Valor de permanência (mora) não numérico', + '37' => 'Valor de permanência inconsistente, pois, dentro de um mês, será maior que o valor do título', + '38' => 'Valor de desconto/abatimento não numérico ou inválido', + '39' => 'Valor de abatimento não numérico', + '42' => 'Título já existente em nossos registros. Nosso número não aceito', + '43' => 'Título enviado em duplicidade nesse movimento', + '44' => 'Título zerado ou em branco; ou não numérico na remessa', + '46' => 'Título enviado fora da faixa de Nosso Número, estipulada para o cliente.', + '51' => 'Tipo/Número de Inscrição Sacador/Avalista Inválido', + '52' => 'Sacador/Avalista não informado', + '53' => 'Prazo de vencimento do título excede ao da contratação', + '54' => 'Banco informado não é nosso correspondente 140-142', + '55' => 'Banco correspondente informado não cobra este CEP ou não possui faixas de CEP cadastradas', + '56' => 'Nosso número no correspondente não foi informado', + '57' => 'Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.', + '58' => 'Entradas Rejeitadas – Reprovado no Represamento para Análise', + '60' => 'CNPJ/CPF do sacado inválido – título recusado', + '87' => 'Excede Prazo máximo entre emissão e vencimento', + 'AA' => 'Serviço de cobrança inválido', + 'AB' => 'Serviço de "0" ou "5" e banco cobrador <> zeros', + 'AE' => 'Título não possui abatimento', + 'AI' => 'Nossa carteira inválida', + 'AJ' => 'Modalidade com bancos correspondentes inválida', + 'AL' => 'Sacado impedido de entrar nesta cobrança', + 'AU' => 'Data da ocorrência inválida', + 'AV' => 'Valor da tarifa de cobrança inválida', + 'AX' => 'Título em pagamento parcial', + 'BC' => 'Análise gerencial-sacado inválido p/operação crédito', + 'BD' => 'Análise gerencial-sacado inadimplente', + 'BE' => 'Análise gerencial-sacado difere do exigido', + 'BF' => 'Análise gerencial-vencto excede vencto da operação de crédito', + 'BG' => 'Análise gerencial-sacado com baixa liquidez', + 'BH' => 'Análise gerencial-sacado excede concentração', + 'CC' => 'Valor de iof incompatível com a espécie documento', + 'CD' => 'Efetivação de protesto sem agenda válida', + 'CE' => 'Título não aceito - pessoa física', + 'CF' => 'Excede prazo máximo da entrada ao vencimento', + 'CG' => 'Título não aceito – por análise gerencial', + 'CH' => 'Título em espera – em análise pelo banco', + 'CJ' => 'Análise gerencial-vencto do titulo abaixo przcurto', + 'CK' => 'Análise gerencial-vencto do titulo abaixo przlongo', + 'CS' => 'Título rejeitado pela checagem de duplicatas', + 'DA' => 'Análise gerencial – Entrada de Título Descontado com limite cancelado', + 'DB' => 'Análise gerencial – Entrada de Título Descontado com limite vencido', + 'DC' => 'Análise gerencial - cedente com limite cancelado', + 'DD' => 'Análise gerencial – cedente é sacado e teve seu limite cancelado', + 'DE' => 'Análise gerencial - apontamento no Serasa', + 'DG' => 'Endereço sacador/avalista não informado', + 'DH' => 'Cep do sacador/avalista não informado', + 'DI' => 'Cidade do sacador/avalista não informado', + 'DJ' => 'Estado do sacador/avalista inválido ou n informado', + 'DM' => 'Cliente sem Código de Flash cadastrado no cobrador', + 'DN' => 'Título Descontado com Prazo ZERO – Recusado', + 'DP' => 'Data de Referência menor que a Data de Emissão do Título', + 'DT' => 'Nosso Número do Correspondente não deve ser informado', + 'EB' => 'HSBC não aceita endereço de sacado com mais de 38 caracteres', + 'G1' => 'Endereço do sacador incompleto ( lei 12.039)', + 'G2' => 'Sacador impedido de movimentar', + 'G3' => 'Concentração de cep não permitida', + 'G4' => 'Valor do título não permitido', + 'HA' => 'Serviço e Modalidade Incompatíveis', + 'HB' => 'Inconsistências entre Registros Título e Sacador', + 'HC' => 'Ocorrência não disponível', + 'HD' => 'Título com Aceite', + 'HF' => 'Baixa Liquidez do Sacado', + 'HG' => 'Sacado Informou que não paga Boletos', + 'HH' => 'Sacado não confirmou a Nota Fiscal', + 'HI' => 'Checagem Prévia não Efetuada', + 'HJ' => 'Sacado desconhece compra e Nota Fiscal', + 'HK' => 'Compra e Nota Fiscal canceladas pelo sacado', + 'HL' => 'Concentração além do permitido pela área de Crédito', + 'HM' => 'Vencimento acima do permitido pelo área de Crédito', + 'HN' => 'Excede o prazo limite da operação', + 'IX' => 'Título de Cartão de Crédito não aceita instruções', + 'JB' => 'Título de Cartão de Crédito inválido para o Produto', + 'JC' => 'Produto somente para Cartão de Crédito', + 'JH' => 'CB Direta com operação de Desconto Automático', + 'JI' => 'Espécie de Documento incompatível para produto de Cartão de Crédito', + 'JK' => 'Produto não permite alterar Valor e Vencimento', + 'JQ' => 'Título em Correspondente – Alteração não permitida', + 'JS' => 'Título possui Desc/Abatim/Mora/Multa', + 'JT' => 'Título possui Agenda', + 'KC' => 'Título já Sustado', + 'KD' => 'Serviço de Cobrança não permitido para carteira', + 'KE' => 'Título possui caracteres não permitidos.', + 'KF' => 'Operação fechada para novas entradas', + 'KG' => 'Nosso número bancos duplicado.', + 'ZQ' => 'Sem informação da Nota Fiscal Eletrônica', + 'ZR' => 'Chave de Acesso NF Rejeitada', + 'ZS' => 'Chave de Acesso NF Duplicada', + 'ZT' => 'Quantidade NF excede a quantidade permitida (30)', + 'ZU' => 'Chave de Acesso NF inválida', + ], + '15' => [ + '05' => 'Solicitação de baixa para título já baixado ou liquidado', + '06' => 'Solicitação de baixa para título não registrado no sistema', + '08' => 'Solicitação de baixa para título em float', + ], + '16' => [ + '04' => 'Data de vencimento não numérica ou inválida', + '05' => 'Data de Vencimento inválida ou fora do prazo mínimo', + '14' => 'Registro em duplicidade', + '19' => 'Data de desconto inválida ou maior que a data de vencimento', + '20' => 'Campo livre não informado', + '21' => 'Título não registrado no sistema', + '22' => 'Título baixado ou liquidado', + '26' => 'Espécie de documento inválida', + '27' => 'Instrução não aceita, por não ter sido emitida ordem de protesto ao cartório', + '28' => 'Título tem instrução de cartório ativa', + '29' => 'Título não tem instrução de carteira ativa', + '30' => 'Existe instrução de não protestar, ativa para o título', + '36' => 'Valor de permanência (mora) não numérico', + '37' => 'Título Descontado – Instrução não permitida para a carteira', + '38' => 'Valor do abatimento não numérico ou maior que a soma do valor do título + permanência + multa', + '39' => 'Título em cartório', + '40' => 'Instrução recusada – Reprovado no Represamento para Análise', + '44' => 'Título zerado ou em branco; ou não numérico na remessa', + '51' => 'Tipo/Número de Inscrição Sacador/Avalista Inválido', + '53' => 'Prazo de vencimento do título excede ao da contratação', + '57' => 'Remessa contendo duas instruções incompatíveis – não protestar e dias de protesto ou prazo para protesto inválido.', + 'AA' => 'Serviço de cobrança inválido', + 'AE' => 'Título não possui abatimento', + 'AG' => 'Movimento não permitido – Título à vista ou contra apresentação', + 'AH' => 'Cancelamento de valores inválidos', + 'AI' => 'Nossa carteira inválida', + 'AK' => 'Título pertence a outro cliente', + 'AU' => 'Data da ocorrência inválida', + 'AY' => 'Título deve estar em aberto e vencido para acatar protesto', + 'BA' => 'Banco Correspondente Recebedor não é o Cobrador Atual', + 'BB' => 'Título deve estar em cartório para baixar', + 'CB' => 'Título possui protesto efetivado/a efetivar hoje', + 'CT' => 'Título já baixado', + 'CW' => 'Título já transferido', + 'DO' => 'Título em Prejuízo', + 'IX' => 'Título de Cartão de Crédito não aceita instruções', + 'JK' => 'Produto não permite alteração de valor de título', + 'JQ' => 'Título em Correspondente – Não alterar Valor', + 'JS' => 'Título possui Descontos/Abto/Mora/Multa', + 'JT' => 'Título possui Agenda de Protesto/Devolução', + '99' => 'Ocorrência desconhecida na remessa', + ], + ]; + + /** + * Roda antes dos metodos de processar + */ + protected function init() + { + $this->totais = [ + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'alterados' => 0, + ]; + } + + /** + * @param array $header + * + * @return bool + * @throws ValidationException + */ + protected function processarHeader(array $header) + { + $this->getHeader() + ->setOperacaoCodigo($this->rem(2, 2, $header)) + ->setOperacao($this->rem(3, 9, $header)) + ->setServicoCodigo($this->rem(10, 11, $header)) + ->setServico($this->rem(12, 26, $header)) + ->setCodigoCliente($this->rem(27, 46, $header)) + ->setData($this->rem(95, 100, $header)); + + return true; + } + + /** + * @param array $detalhe + * + * @return bool + * @throws ValidationException + */ + protected function processarDetalhe(array $detalhe) + { + $d = $this->detalheAtual(); + + $d->setCarteira($this->rem(108, 108, $detalhe)) + ->setNossoNumero($this->rem(63, 73, $detalhe)) + ->setNumeroDocumento($this->rem(117, 126, $detalhe)) + ->setNumeroControle($this->rem(38, 62, $detalhe)) + ->setOcorrencia($this->rem(109, 110, $detalhe)) + ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) + ->setDataOcorrencia($this->rem(111, 116, $detalhe)) + ->setDataVencimento($this->rem(147, 152, $detalhe)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); + + $msgAdicional = str_split(sprintf('%08s', $this->rem(378, 385, $detalhe)), 2) + array_fill(0, 5, ''); + if ($d->hasOcorrencia('06', '08', '10')) { + $this->totais['liquidados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); + } elseif ($d->hasOcorrencia('01', '02')) { + $this->totais['entradas']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ENTRADA); + } elseif ($d->hasOcorrencia('09')) { + $this->totais['baixados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); + } elseif ($d->hasOcorrencia('43')) { + $this->totais['protestados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); + } elseif ($d->hasOcorrencia('05', '14', '22')) { + $this->totais['alterados']++; + $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); + } elseif ($d->hasOcorrencia('03', '15', '16')) { + $this->totais['erros']++; + $error = Util::appendStrings(Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[0], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[1], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[2], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[3], ''), Arr::get($this->rejeicoes[sprintf('%02s', $d->getOcorrencia())], $msgAdicional[4], '')); + $d->setError($error); + } else { + $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); + } + + return true; + } + + /** + * @param array $trailer + * + * @return bool + */ + protected function processarTrailer(array $trailer) + { + $this->getTrailer() + ->setQuantidadeTitulos($this->count()) + ->setQuantidadeEntradas((int) $this->totais['entradas']) + ->setQuantidadeLiquidados((int) $this->totais['liquidados']) + ->setQuantidadeBaixados((int) $this->totais['baixados']) + ->setQuantidadeAlterados((int) $this->totais['alterados']); + + return true; + } +} diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Santander.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Santander.php index c79cefc5..dd25aab7 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Santander.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Santander.php @@ -1,11 +1,13 @@ totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -251,7 +253,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -271,20 +273,22 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { if ($this->count() == 1) { if (trim($this->rem(384, 385, $detalhe), '') != '') { $this->getHeader() - ->setConta( - $this->getHeader()->getConta() - . $this->rem(384, 385, $detalhe) - ); + ->setConta($this->getHeader()->getConta() + . $this->rem(384, 385, $detalhe)); } } + if ($this->rem(1, 1, $detalhe) == 2) { + return $this->processarPix($detalhe); + } + $d = $this->detalheAtual(); $d->setCarteira($this->rem(108, 108, $detalhe)) ->setNossoNumero($this->rem(63, 70, $detalhe)) @@ -295,15 +299,15 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(296, 301, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe)/100, 2, false)) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)); $this->totais['valor_recebido'] += $d->getValorRecebido(); @@ -356,4 +360,18 @@ protected function processarTrailer(array $trailer) return true; } + + /** + * @param array $detalhe + * @return bool + * @throws ValidationException + */ + private function processarPix(array $detalhe) + { + $d = $this->getDetalhe($this->increment - 1); + $d->setPixLocation($this->rem(3, 79, $detalhe)); + $d->setId($this->rem(80, 114, $detalhe)); + + return false; + } } diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Sicredi.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Sicredi.php index 84ba3f70..be7dfe98 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Sicredi.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Sicredi.php @@ -1,11 +1,13 @@ totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -223,7 +225,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -243,7 +245,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -256,18 +258,18 @@ protected function processarDetalhe(array $detalhe) ->setOcorrenciaDescricao(Arr::get($this->ocorrencias, $d->getOcorrencia(), 'Desconhecida')) ->setDataOcorrencia($this->rem(111, 116, $detalhe)) ->setDataVencimento($this->rem(147, 152, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe), 2, false) / 100) - ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe), 2, false) / 100) - ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe), 2, false) / 100 ) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe), 2, false) / 100) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe), 2, false) / 100) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe), 2, false) / 100) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe), 2, false) / 100) - ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe), 2, false) / 100) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(176, 188, $detalhe) / 100, 2, false)) + ->setValorOutrasDespesas(Util::nFloat($this->rem(189, 201, $detalhe) / 100, 2, false)) + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)) + ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe) / 100, 2, false)) ->setDataCredito($this->rem(329, 336, $detalhe), 'Ymd'); if ($d->hasOcorrencia('06', '15', '16')) { - $this->totais['valor_recebido'] += $d->getValorRecebido(); + $this->totais['valor_recebido'] += $d->getValorRecebido(); $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); } elseif ($d->hasOcorrencia('02')) { @@ -282,10 +284,10 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('33')) { $this->totais['alterados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); - } elseif ($d->hasOcorrencia('03','24', '27', '30', '32')) { + } elseif ($d->hasOcorrencia('03', '24', '27', '30', '32')) { $this->totais['erros']++; - if($d->hasOcorrencia('03')) { - if(isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])){ + if ($d->hasOcorrencia('03')) { + if (isset($this->rejeicoes[$this->rem(319, 320, $detalhe)])) { $d->setRejeicao($this->rejeicoes[$this->rem(319, 320, $detalhe)]); } } @@ -298,7 +300,6 @@ protected function processarDetalhe(array $detalhe) $msgAdicRetorno = str_split($msgAdicional, 2) + array_fill(0, 5, '') + array_fill(0, 5, ''); if (trim($msgAdicional, '0') != '') { - //Caso seja detalhe de Tarifa ('28' => 'Tarifa') Buscar as mensagens especificas e não classificar como erro if ($d->hasOcorrencia('28')) { $motivo = []; @@ -310,39 +311,13 @@ protected function processarDetalhe(array $detalhe) $motivo = array_filter($motivo); - if (count($motivo) > 0){ + if (count($motivo) > 0) { $d->setRejeicao(implode(PHP_EOL, $motivo)); } - - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->ocorrenciasTarifas, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - - //Caso haja outra mensagem adicional para tratar e não seja ocorrência de erro então - //concatenar a mensagem com o texto da descricao atual - } else - if ( $d->getOcorrenciaTipo() != $d::OCORRENCIA_ERRO ){ - $ocorrencia = Util::appendStrings( - $d->getOcorrenciaDescricao(), - Arr::get($this->rejeicoes, $msgAdicRetorno[0], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[1], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[2], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[3], ''), - Arr::get($this->rejeicoes, $msgAdicRetorno[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - //$d->setOcorrenciaDescricao($ocorrencia); - } - else { - + } elseif ($d->getOcorrenciaTipo() != $d::OCORRENCIA_ERRO) { + $ocorrencia = Util::appendStrings($d->getOcorrenciaDescricao(), Arr::get($this->rejeicoes, $msgAdicRetorno[0], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[1], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[2], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[3], ''), Arr::get($this->rejeicoes, $msgAdicRetorno[4], '')); + $d->setOcorrenciaDescricao($ocorrencia); + } else { $error = []; $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[0], ''); $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[1], ''); @@ -350,16 +325,9 @@ protected function processarDetalhe(array $detalhe) $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[3], ''); $error[] = Arr::get($this->rejeicoes, $msgAdicRetorno[4], ''); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); - $error = array_filter($error); - if (count($error) > 0){ + if (count($error) > 0) { $d->setError(implode(PHP_EOL, $error)); } } diff --git a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Unicred.php b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Unicred.php index 4c1f27e1..67ccf194 100644 --- a/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Unicred.php +++ b/src/Cnab/Retorno/Cnab400/Pagamento/Banco/Unicred.php @@ -1,11 +1,13 @@ "Pago (Título protestado pago em cartório)", - "02" => "Instrução Confirmada", - "03" => "Instrução Rejeitada", - "04" => "Sustado Judicial (Título protestado sustado judicialmente)", - "06" => "Liquidação Normal", - "07" => "Liquidação em Condicional (Título liquidado em cartório com cheque do próprio devedor)", - "08" => "Sustado Definitivo (Título protestado sustado judicialmente)", - "09" => "Liquidação de Título Descontado", - "10" => "Protesto solicitado", - "11" => "Protesto Em cartório", - "12" => "Sustação solicitada", - "13" => "Títulos Descontado (título utilizado como garantia em operação de desconto)", - "14" => "Títulos Descontável (título com desistência de garantia em operação de desconto)", + '01' => 'Pago (Título protestado pago em cartório)', + '02' => 'Instrução Confirmada', + '03' => 'Instrução Rejeitada', + '04' => 'Sustado Judicial (Título protestado sustado judicialmente)', + '06' => 'Liquidação Normal', + '07' => 'Liquidação em Condicional (Título liquidado em cartório com cheque do próprio devedor)', + '08' => 'Sustado Definitivo (Título protestado sustado judicialmente)', + '09' => 'Liquidação de Título Descontado', + '10' => 'Protesto solicitado', + '11' => 'Protesto Em cartório', + '12' => 'Sustação solicitada', + '13' => 'Títulos Descontado (título utilizado como garantia em operação de desconto)', + '14' => 'Títulos Descontável (título com desistência de garantia em operação de desconto)', ]; /** @@ -43,74 +45,74 @@ class Unicred extends AbstractRetorno implements RetornoCnab400 * @var array */ private $rejeicoes = [ - '00' => 'Sem Complemento a informar', - '01' => 'Código do Banco Inválido', - '04' => 'Código de Movimento não permitido para a carteira', - '05' => 'Código de Movimento Inválido', - '06' => 'Número de Inscrição do Beneficiário Inválido', - '07' => 'Agência - Conta Inválida', - '08' => 'Nosso Número Inválido', - '09' => 'Nosso Número Duplicado', - '10' => 'Carteira inválida', - '12' => 'Tipo de Documento Inválido', - '15' => 'Data de Vencimento inferior a 5 dias uteis para remessa gráfica', - '16' => 'Data de Vencimento Inválida', - '17' => 'Data de Vencimento Anterior à Data de Emissão', - '18' => 'Vencimento fora do Prazo de Operação', - '20' => 'Valor do Título Inválido', - '24' => 'Data de Emissão Inválida', - '25' => 'Data de Emissão Posterior à data de Entrega', - '26' => 'Código de juros inválido', - '27' => 'Valor de juros inválido', - '28' => 'Código de Desconto inválido', - '29' => 'Valor de Desconto inválido', - '30' => 'Alteração de Dados Rejeitada', - '33' => 'Valor de Abatimento Inválido', - '34' => 'Valor do Abatimento Maior ou Igual ao Valor do título', - '37' => 'Código para Protesto Inválido; (Protesto via SGR, não é CRA)', - '38' => 'Prazo para Protesto Inválido; (Protesto via SGR, não é CRA)', - '39' => 'Pedido de Protesto Não Permitido para o Título', - '40' => 'Título com Ordem de Protesto Emitida', - '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto ou Instrução de Protesto não confirmada pelo cartório', - '45' => 'Nome do Pagador não informado', - '46' => 'Número de Inscrição do Pagador Inválido', - '47' => 'Endereço do Pagador Não Informado', - '48' => 'CEP Inválido', - '52' => 'Unidade Federativa Inválida', - '57' => 'Código de Multa inválido', - '58' => 'Data de Multa inválido', - '59' => 'Valor / percentual de Multa inválido', - '60' => 'Movimento para Título não Cadastrado', - '63' => 'Entrada para Título já cadastrado', - '79' => 'Data de Juros inválida', - '80' => 'Data de Desconto inválida', - '86' => 'Seu Número Inválido', - 'A5' => 'Título Liquidado', - 'A8' => 'Valor do Abatimento Inválido para Cancelamento', - 'C0' => 'Sistema Intermitente – Entre em contato com sua Cooperativa', - 'C1' => 'Situação do título Aberto', - 'C3' => 'Status do Borderô Inválido', - 'C4' => 'Nome do Beneficiário Inválido', - 'C5' => 'Documento Inválido', - 'C6' => 'Instrução não Atualiza Cadastro do Título', - 'C7' => 'Título não registrado na CIP', - 'C8' => 'Situação do Borderô inválida', - 'C9' => 'Título inválido conforme situação CIP', + '00' => 'Sem Complemento a informar', + '01' => 'Código do Banco Inválido', + '04' => 'Código de Movimento não permitido para a carteira', + '05' => 'Código de Movimento Inválido', + '06' => 'Número de Inscrição do Beneficiário Inválido', + '07' => 'Agência - Conta Inválida', + '08' => 'Nosso Número Inválido', + '09' => 'Nosso Número Duplicado', + '10' => 'Carteira inválida', + '12' => 'Tipo de Documento Inválido', + '15' => 'Data de Vencimento inferior a 5 dias uteis para remessa gráfica', + '16' => 'Data de Vencimento Inválida', + '17' => 'Data de Vencimento Anterior à Data de Emissão', + '18' => 'Vencimento fora do Prazo de Operação', + '20' => 'Valor do Título Inválido', + '24' => 'Data de Emissão Inválida', + '25' => 'Data de Emissão Posterior à data de Entrega', + '26' => 'Código de juros inválido', + '27' => 'Valor de juros inválido', + '28' => 'Código de Desconto inválido', + '29' => 'Valor de Desconto inválido', + '30' => 'Alteração de Dados Rejeitada', + '33' => 'Valor de Abatimento Inválido', + '34' => 'Valor do Abatimento Maior ou Igual ao Valor do título', + '37' => 'Código para Protesto Inválido; (Protesto via SGR, não é CRA)', + '38' => 'Prazo para Protesto Inválido; (Protesto via SGR, não é CRA)', + '39' => 'Pedido de Protesto Não Permitido para o Título', + '40' => 'Título com Ordem de Protesto Emitida', + '41' => 'Pedido de Cancelamento/Sustação para Títulos sem Instrução de Protesto ou Instrução de Protesto não confirmada pelo cartório', + '45' => 'Nome do Pagador não informado', + '46' => 'Número de Inscrição do Pagador Inválido', + '47' => 'Endereço do Pagador Não Informado', + '48' => 'CEP Inválido', + '52' => 'Unidade Federativa Inválida', + '57' => 'Código de Multa inválido', + '58' => 'Data de Multa inválido', + '59' => 'Valor / percentual de Multa inválido', + '60' => 'Movimento para Título não Cadastrado', + '63' => 'Entrada para Título já cadastrado', + '79' => 'Data de Juros inválida', + '80' => 'Data de Desconto inválida', + '86' => 'Seu Número Inválido', + 'A5' => 'Título Liquidado', + 'A8' => 'Valor do Abatimento Inválido para Cancelamento', + 'C0' => 'Sistema Intermitente – Entre em contato com sua Cooperativa', + 'C1' => 'Situação do título Aberto', + 'C3' => 'Status do Borderô Inválido', + 'C4' => 'Nome do Beneficiário Inválido', + 'C5' => 'Documento Inválido', + 'C6' => 'Instrução não Atualiza Cadastro do Título', + 'C7' => 'Título não registrado na CIP', + 'C8' => 'Situação do Borderô inválida', + 'C9' => 'Título inválido conforme situação CIP', 'C10' => 'Protesto: Título precisa estar em Aberto', - 'D0' => 'Beneficiário não autorizado a operar com produto Desconto', - 'D1' => 'Alteração de status de desconto não permitido para título', - 'D2' => 'Operação de desconto não permitida para título vencido', - 'D3' => 'Alteração de status de desconto não permitido para situação do título', - 'E0' => 'CEP indicado para o endereço do Pagador não compatível com os Correios', - 'E1' => 'Logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E2' => 'Tipo de logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E3' => 'Bairro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E4' => 'Cidade para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E5' => 'UF para o endereço do Pagador não compatível com os Correios, para o CEP indicado', - 'E6' => 'Dados do segmento/registro opcional de endereço do pagador, incompletos no arquivo remessa', - 'E7' => 'Beneficiário não autorizado a enviar boleto por e-mail', - 'E8' => 'Indicativo para pagador receber boleto por e-mail sinalizado, porém sem o endereço do e-mail', - 'E9' => 'Beneficiário não autorizado a enviar títulos para protesto', + 'D0' => 'Beneficiário não autorizado a operar com produto Desconto', + 'D1' => 'Alteração de status de desconto não permitido para título', + 'D2' => 'Operação de desconto não permitida para título vencido', + 'D3' => 'Alteração de status de desconto não permitido para situação do título', + 'E0' => 'CEP indicado para o endereço do Pagador não compatível com os Correios', + 'E1' => 'Logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E2' => 'Tipo de logradouro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E3' => 'Bairro para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E4' => 'Cidade para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E5' => 'UF para o endereço do Pagador não compatível com os Correios, para o CEP indicado', + 'E6' => 'Dados do segmento/registro opcional de endereço do pagador, incompletos no arquivo remessa', + 'E7' => 'Beneficiário não autorizado a enviar boleto por e-mail', + 'E8' => 'Indicativo para pagador receber boleto por e-mail sinalizado, porém sem o endereço do e-mail', + 'E9' => 'Beneficiário não autorizado a enviar títulos para protesto', 'E10' => 'Instrução ‘09 – Protestar’, usada erroneamente para título a vencer ou ainda dentro do período de Carência de ‘1 dia’ do vencimento, referente a liquidação por Compensação', 'E11' => 'Instrução ‘26 – Protesto Automático’, usada erroneamente para título vencido', 'E12' => 'Cancelamento de protesto automático não permitido, título não possui configuração de protesto automático', @@ -203,7 +205,6 @@ class Unicred extends AbstractRetorno implements RetornoCnab400 '170' => 'Dados do Cedente em branco ou inválido', ]; - /** * Array com os Códigos de Tipo de Instrução Origem (Posições 327 a 328 do retorno) * @@ -233,12 +234,12 @@ protected function init() { $this->totais = [ 'valor_recebido' => 0, - 'liquidados' => 0, - 'entradas' => 0, - 'baixados' => 0, - 'protestados' => 0, - 'erros' => 0, - 'alterados' => 0, + 'liquidados' => 0, + 'entradas' => 0, + 'baixados' => 0, + 'protestados' => 0, + 'erros' => 0, + 'alterados' => 0, ]; } @@ -246,7 +247,7 @@ protected function init() * @param array $header * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarHeader(array $header) { @@ -267,7 +268,7 @@ protected function processarHeader(array $header) * @param array $detalhe * * @return bool - * @throws \Exception + * @throws ValidationException */ protected function processarDetalhe(array $detalhe) { @@ -282,7 +283,7 @@ protected function processarDetalhe(array $detalhe) * Portanto, quando não refere-se a quitação de valores esse campo vem preenchido com '000000', e nesse caso * será utilizada então a data de geração do arquivo como data de ocorrência */ - $this->dataOcorrencia = ((!empty($this->rem(111, 116, $detalhe)) && ($this->rem(111, 116, $detalhe)!= '000000'))?$this->rem(111, 116, $detalhe):$this->dataGeracaoArquivo); + $this->dataOcorrencia = ((! empty($this->rem(111, 116, $detalhe)) && ($this->rem(111, 116, $detalhe) != '000000')) ? $this->rem(111, 116, $detalhe) : $this->dataGeracaoArquivo); $d = $this->detalheAtual(); @@ -296,20 +297,19 @@ protected function processarDetalhe(array $detalhe) ->setDataOcorrencia($this->dataOcorrencia)//Data de geração do arquivo de remessa ou data de quitação do registro ->setDataVencimento($this->rem(147, 152, $detalhe)) ->setDataCredito($this->rem(176, 181, $detalhe)) - ->setValor(Util::nFloat($this->rem(153, 165, $detalhe)/100, 2, false)) - ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe)/100, 2, false)) + ->setValor(Util::nFloat($this->rem(153, 165, $detalhe) / 100, 2, false)) + ->setValorTarifa(Util::nFloat($this->rem(182, 188, $detalhe) / 100, 2, false)) // ->setValorIOF(Util::nFloat($this->rem(215, 227, $detalhe)/100, 2, false)) - ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe)/100, 2, false)) - ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe)/100, 2, false)) - ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe)/100, 2, false)) - ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe)/100, 2, false)); - // ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); - + ->setValorAbatimento(Util::nFloat($this->rem(228, 240, $detalhe) / 100, 2, false)) + ->setValorDesconto(Util::nFloat($this->rem(241, 253, $detalhe) / 100, 2, false)) + ->setValorRecebido(Util::nFloat($this->rem(254, 266, $detalhe) / 100, 2, false)) + ->setValorMora(Util::nFloat($this->rem(267, 279, $detalhe) / 100, 2, false)); + // ->setValorMulta(Util::nFloat($this->rem(280, 292, $detalhe)/100, 2, false)); //Adicionar array_fill para garantir que array tenha 5 casas - $msgAdicional = str_split( $this->rem(319, 326, $detalhe), 2) + array_fill(0, 5, ''); + $msgAdicional = str_split($this->rem(319, 326, $detalhe), 2) + array_fill(0, 5, ''); - if ($d->hasOcorrencia('01','06', '09')) { //'07' + if ($d->hasOcorrencia('01', '06', '09')) { //'07' $this->totais['valor_recebido'] += $d->getValorRecebido(); $this->totais['liquidados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_LIQUIDADA); @@ -319,28 +319,13 @@ protected function processarDetalhe(array $detalhe) } elseif ($d->hasOcorrencia('09', '10')) { $this->totais['baixados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_BAIXADA); - } elseif ($d->hasOcorrencia('10','11')) { + } elseif ($d->hasOcorrencia('10', '11')) { $this->totais['protestados']++; $d->setOcorrenciaTipo($d::OCORRENCIA_PROTESTADA); - //} elseif ($d->hasOcorrencia('14')) { - // $this->totais['alterados']++; - // $d->setOcorrenciaTipo($d::OCORRENCIA_ALTERACAO); } elseif ($d->hasOcorrencia('03')) { - $this->totais['erros']++; - $error = Util::appendStrings( - Arr::get($this->rejeicoes, $msgAdicional[0], ''), - Arr::get($this->rejeicoes, $msgAdicional[1], ''), - Arr::get($this->rejeicoes, $msgAdicional[2], ''), - Arr::get($this->rejeicoes, $msgAdicional[3], ''), - Arr::get($this->rejeicoes, $msgAdicional[4], '') - ); - $ocorrenciaArray[$msgAdicional[0]] = Arr::get($this->rejeicoes, $msgAdicional[0], ''); - $ocorrenciaArray[$msgAdicional[1]] = Arr::get($this->rejeicoes, $msgAdicional[1], ''); - $ocorrenciaArray[$msgAdicional[2]] = Arr::get($this->rejeicoes, $msgAdicional[2], ''); - $ocorrenciaArray[$msgAdicional[3]] = Arr::get($this->rejeicoes, $msgAdicional[3], ''); - $ocorrenciaArray[$msgAdicional[4]] = Arr::get($this->rejeicoes, $msgAdicional[4], ''); - $d->setOcorrenciaArray($ocorrenciaArray); + $error = Util::appendStrings(Arr::get($this->rejeicoes, $msgAdicional[0], ''), Arr::get($this->rejeicoes, $msgAdicional[1], ''), Arr::get($this->rejeicoes, $msgAdicional[2], ''), Arr::get($this->rejeicoes, $msgAdicional[3], ''), Arr::get($this->rejeicoes, $msgAdicional[4], '')); + $d->setError($error); } else { $d->setOcorrenciaTipo($d::OCORRENCIA_OUTROS); @@ -353,13 +338,12 @@ protected function processarDetalhe(array $detalhe) * @param array $trailer * * @return bool - * @throws \Exception */ protected function processarTrailer(array $trailer) { $this->getTrailer() ->setQuantidadeTitulos((int) $this->count()) - ->setValorTitulos( (float) Util::nFloat($this->totais['valor_recebido'], 2, false) ) + ->setValorTitulos((float) Util::nFloat($this->totais['valor_recebido'], 2, false)) ->setQuantidadeErros((int) $this->totais['erros']) ->setQuantidadeEntradas((int) $this->totais['entradas']) ->setQuantidadeLiquidados((int) $this->totais['liquidados']) diff --git a/src/Cnab/Retorno/Cnab400/Trailer.php b/src/Cnab/Retorno/Cnab400/Trailer.php index 082d2527..d4ed3644 100644 --- a/src/Cnab/Retorno/Cnab400/Trailer.php +++ b/src/Cnab/Retorno/Cnab400/Trailer.php @@ -1,40 +1,49 @@ processar(); } @@ -31,7 +32,7 @@ public static function make($file, $type = 'C') * @param $file_content * * @return mixed - * @throws \Exception + * @throws ValidationException */ private static function getBancoClass($file_content, $type = 'C') { @@ -58,7 +59,7 @@ private static function getBancoClass($file_content, $type = 'C') $bancoClass = $namespace . Util::getBancoClass($banco); if (!class_exists($bancoClass)) { - throw new \Exception("Banco não possui essa versão de CNAB"); + throw new ValidationException('Banco não possui essa versão de CNAB'); } return new $bancoClass($file_content); diff --git a/src/Contracts/Api/Api.php b/src/Contracts/Api/Api.php new file mode 100644 index 00000000..68021d48 --- /dev/null +++ b/src/Contracts/Api/Api.php @@ -0,0 +1,64 @@ +{$name}($arguments); + } + + $property = lcfirst(str_replace(['get', 'set'], ['', ''], $name)); + + return $this->{$property}; + } + /** * Fast set method. * @@ -33,6 +45,7 @@ public function __get($name) { if (property_exists($this, $name)) { $method = 'get' . Str::camel($name); + return $this->{$method}(); } elseif (isset($this->trash[$name])) { return $this->trash[$name]; @@ -69,6 +82,7 @@ public function toArray() $aRet[$var] = $aRet[$var]->toArray(); } } + return $aRet; } } diff --git a/src/Pessoa.php b/src/Pessoa.php index 9d3e15c4..0fbe9ea1 100644 --- a/src/Pessoa.php +++ b/src/Pessoa.php @@ -1,6 +1,8 @@ $nome, @@ -72,6 +84,7 @@ public static function create($nome, $documento, $endereco = null, $numero = nul 'uf' => $uf, 'cidade' => $cidade, 'documento' => $documento, + 'email' => $email, ]); } @@ -98,6 +111,7 @@ public function setCep($cep) return $this; } + /** * Retorna o CEP * @@ -119,9 +133,9 @@ public function setCidade($cidade) { $this->cidade = $cidade; - return $this; } + /** * Retorna a cidade * @@ -138,18 +152,19 @@ public function getCidade() * @param string $documento * * @return Pessoa - * @throws \Exception + * @throws ValidationException */ public function setDocumento($documento) { $documento = substr(Util::onlyNumbers($documento), -14); if (!in_array(strlen($documento), [10, 11, 14, 0])) { - throw new \Exception('Documento inválido'); + throw new ValidationException('Documento inválido'); } $this->documento = $documento; return $this; } + /** * Retorna o documento (CPF ou CNPJ) * @@ -162,6 +177,7 @@ public function getDocumento() } elseif ($this->getTipoDocumento() == 'CEI') { return Util::maskString(Util::onlyNumbers($this->documento), '##.#####.#-##'); } + return Util::maskString(Util::onlyNumbers($this->documento), '##.###.###/####-##'); } @@ -178,6 +194,7 @@ public function setEndereco($endereco) return $this; } + /** * Retorna o endereço * @@ -247,6 +264,7 @@ public function setBairro($bairro) return $this; } + /** * Retorna o bairro * @@ -270,6 +288,7 @@ public function setNome($nome) return $this; } + /** * Retorna o nome * @@ -293,6 +312,7 @@ public function setUf($uf) return $this; } + /** * Retorna a UF * @@ -302,6 +322,7 @@ public function getUf() { return $this->uf; } + /** * Retorna o nome e o documento formatados * @@ -315,6 +336,7 @@ public function getNomeDocumento() return $this->getNome() . ' / ' . $this->getTipoDocumento() . ': ' . $this->getDocumento(); } } + /** * Retorna se o tipo do documento é CPF ou CNPJ ou Documento * @@ -341,7 +363,8 @@ public function getTipoDocumento() */ public function getCepCidadeUf() { - $dados = array_filter(array($this->getCep(), $this->getCidade(), $this->getUf())); + $dados = array_filter([$this->getCep(), $this->getCidade(), $this->getUf()]); + return implode(' - ', $dados); } @@ -354,14 +377,16 @@ public function getCepCidadeUf() */ public function getEnderecoCompleto() { - $dados = array_filter(array($this->getEndereco(), $this->getBairro(), $this->getCidade(), $this->getUf(), $this->getCep())); + $dados = array_filter([$this->getEndereco(), $this->getBairro(), $this->getCidade(), $this->getUf(), $this->getCep()]); + return implode(' - ', $dados); } /** * @return bool */ - public function isDda() { + public function isDda() + { return $this->dda; } @@ -370,11 +395,33 @@ public function isDda() { * * @return Pessoa */ - public function setDda($dda) { + public function setDda($dda) + { $this->dda = $dda; return $this; } + + /** + * @param string $email + * + * @return Pessoa + */ + public function setEmail($email) + { + $this->email = $email; + + return $this; + } + + /** + * @return string + */ + public function getEmail() + { + return $this->email; + } + /** * @return array */ @@ -393,6 +440,7 @@ public function toArray() 'nome_documento' => $this->getNomeDocumento(), 'endereco2' => $this->getCepCidadeUf(), 'endereco_completo' => $this->getEnderecoCompleto(), + 'email' => $this->getEmail(), 'dda' => $this->isDda(), ]; } diff --git a/src/Util.php b/src/Util.php index 10755454..3ac97485 100644 --- a/src/Util.php +++ b/src/Util.php @@ -1,10 +1,16 @@ 'Banco ABC Brasil S.A.', '025' => 'Banco Alfa S.A.', @@ -128,6 +135,7 @@ final class Util '070' => 'BRB - Banco de Brasília S.A.', '104' => 'Caixa Econômica Federal', '477' => 'Citibank S.A.', + '133' => 'Cresol', '081' => 'Concórdia Banco S.A.', '487' => 'Deutsche Bank S.A. - Banco Alemão', '064' => 'Goldman Sachs do Brasil Banco Múltiplo S.A.', @@ -141,39 +149,41 @@ final class Util '751' => 'Scotiabank Brasil S.A. Banco Múltiplo', '409' => 'UNIBANCO - União de Bancos Brasileiros S.A.', '230' => 'Unicard Banco Múltiplo S.A.', + '712' => 'Banco Ourinvest', + '085' => 'AILOS - Sistema de Cooperativa de Crédito', 'XXX' => 'Desconhecido', ]; /** * Retorna a String em MAIUSCULO * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function upper($string) { - return strtr(mb_strtoupper($string), "àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ", "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß"); + return strtr(mb_strtoupper($string), 'àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ', 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß'); } /** * Retorna a String em minusculo * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function lower($string) { - return strtr(mb_strtolower($string), "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß", "àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ"); + return strtr(mb_strtolower($string), 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÜÚÞß', 'àáâãäåæçèéêëìíîïðñòóôõö÷øùüúþÿ'); } /** * Retorna a String em minusculo * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function upFirst($string) { @@ -183,9 +193,9 @@ public static function upFirst($string) /** * Retorna somente as letras da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function lettersOnly($string) { @@ -195,9 +205,9 @@ public static function lettersOnly($string) /** * Retorna somente as letras da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function onlyLetters($string) { @@ -207,9 +217,9 @@ public static function onlyLetters($string) /** * Retorna somente as letras da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function lettersNot($string) { @@ -219,9 +229,9 @@ public static function lettersNot($string) /** * Retorna somente as letras da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function notLetters($string) { @@ -231,9 +241,9 @@ public static function notLetters($string) /** * Retorna somente os digitos da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function numbersOnly($string) { @@ -243,9 +253,9 @@ public static function numbersOnly($string) /** * Retorna somente os digitos da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function onlyNumbers($string) { @@ -255,9 +265,9 @@ public static function onlyNumbers($string) /** * Retorna somente os digitos da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function numbersNot($string) { @@ -267,9 +277,9 @@ public static function numbersNot($string) /** * Retorna somente os digitos da string * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function notNumbers($string) { @@ -279,9 +289,9 @@ public static function notNumbers($string) /** * Retorna somente alfanumericos * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function alphanumberOnly($string) { @@ -291,9 +301,9 @@ public static function alphanumberOnly($string) /** * Retorna somente alfanumericos * - * @param String $string + * @param string $string * - * @return String + * @return string */ public static function onlyAlphanumber($string) { @@ -309,7 +319,7 @@ public static function onlyAlphanumber($string) */ public static function normalizeChars($string) { - $normalizeChars = array( + $normalizeChars = [ 'Á' => 'A', 'À' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Å' => 'A', 'Ä' => 'A', 'Æ' => 'AE', 'Ç' => 'C', 'É' => 'E', 'È' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Í' => 'I', 'Ì' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ð' => 'Eth', 'Ñ' => 'N', 'Ó' => 'O', 'Ò' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', @@ -321,7 +331,7 @@ public static function normalizeChars($string) 'ú' => 'u', 'ù' => 'u', 'û' => 'u', 'ü' => 'u', 'ý' => 'y', 'ŕ' => 'r', 'ÿ' => 'y', 'ß' => 'sz', 'þ' => 'thorn', 'º' => '', 'ª' => '', '°' => '', - ); + ]; return preg_replace('/[^0-9a-zA-Z !+=*\-,.;:%@_]/', '', strtr($string, $normalizeChars)); } @@ -330,8 +340,8 @@ public static function normalizeChars($string) * Mostra o Valor no float Formatado * * @param string $number - * @param integer $decimals - * @param boolean $showThousands + * @param int $decimals + * @param bool $showThousands * @return string */ public static function nFloat($number, $decimals = 2, $showThousands = false) @@ -340,8 +350,8 @@ public static function nFloat($number, $decimals = 2, $showThousands = false) return 0; } $pontuacao = preg_replace('/[0-9]/', '', $number); - $locale = (mb_substr($pontuacao, -1, 1) == ',') ? "pt-BR" : "en-US"; - $formater = new \NumberFormatter($locale, \NumberFormatter::DECIMAL); + $locale = (mb_substr($pontuacao, -1, 1) == ',') ? 'pt-BR' : 'en-US'; + $formater = new NumberFormatter($locale, NumberFormatter::DECIMAL); if ($decimals === false) { $decimals = 2; @@ -351,16 +361,16 @@ public static function nFloat($number, $decimals = 2, $showThousands = false) } } - return number_format($formater->parse($number, \NumberFormatter::TYPE_DOUBLE), $decimals, '.', ($showThousands ? ',' : '')); + return number_format($formater->parse($number, NumberFormatter::TYPE_DOUBLE), $decimals, '.', ($showThousands ? ',' : '')); } /** * Mostra o Valor no real Formatado * * @param float $number - * @param boolean $fixed - * @param boolean $symbol - * @param integer $decimals + * @param bool $fixed + * @param bool $symbol + * @param int $decimals * @return string */ public static function nReal($number, $decimals = 2, $symbol = true, $fixed = true) @@ -368,8 +378,8 @@ public static function nReal($number, $decimals = 2, $symbol = true, $fixed = tr if (is_null($number) || empty(self::onlyNumbers($number))) { return ''; } - $formater = new \NumberFormatter("pt-BR", \NumberFormatter::CURRENCY); - $formater->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, ($fixed ? $decimals : 1)); + $formater = new NumberFormatter('pt-BR', NumberFormatter::CURRENCY); + $formater->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, ($fixed ? $decimals : 1)); if ($decimals === false) { $decimals = 2; preg_match_all('/[0-9][^0-9]([0-9]+)/', $number, $matches); @@ -377,13 +387,14 @@ public static function nReal($number, $decimals = 2, $symbol = true, $fixed = tr $decimals = mb_strlen(rtrim($matches[1][0], 0)); } } - $formater->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $decimals); + $formater->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimals); $pattern = substr($formater->getPattern(), strpos($formater->getPattern(), '#')); if ($symbol) { - $pattern = "¤ " . $pattern; + $pattern = '¤ ' . $pattern; } $formater->setPattern($pattern); - return trim($formater->formatCurrency($number, $formater->getTextAttribute(\NumberFormatter::CURRENCY_CODE))); + + return trim($formater->formatCurrency($number, $formater->getTextAttribute(NumberFormatter::CURRENCY_CODE))); } /** @@ -398,6 +409,7 @@ public static function nReal($number, $decimals = 2, $symbol = true, $fixed = tr public static function percentOf($big, $small, $defaultOnZero = 0) { $result = $big > 0.01 ? (($small*100)/$big) : $defaultOnZero; + return self::nFloat($result); } @@ -414,6 +426,7 @@ public static function percent($big, $percent) if ($percent < 0.01) { return 0; } + return self::nFloat($big*($percent/100)); } @@ -452,7 +465,7 @@ public static function maskString($val, $mask) /** * @param $n - * @param integer $loop + * @param int $loop * @param $insert * * @return string @@ -461,24 +474,25 @@ public static function numberFormatGeral($n, $loop, $insert = 0) { // Removo os caracteras a mais do que o pad solicitado caso a string seja maior $n = mb_substr(self::onlyNumbers($n), 0, $loop); + return str_pad($n, $loop, $insert, STR_PAD_LEFT); } /** * @param $tipo * @param $valor - * @param integer $tamanho + * @param int $tamanho * @param int $dec * @param string $sFill * * @return string - * @throws \Exception + * @throws ValidationException */ public static function formatCnab($tipo, $valor, $tamanho, $dec = 0, $sFill = '') { $tipo = self::upper($tipo); $valor = self::upper(self::normalizeChars($valor)); - if (in_array($tipo, array('9', 9, 'N', '9L', 'NL'))) { + if (in_array($tipo, ['9', 9, 'N', '9L', 'NL'])) { if ($tipo == '9L' || $tipo == 'NL') { $valor = self::onlyNumbers($valor); } @@ -486,22 +500,27 @@ public static function formatCnab($tipo, $valor, $tamanho, $dec = 0, $sFill = '' $sFill = 0; $type = 's'; $valor = ($dec > 0) ? sprintf("%.{$dec}f", $valor) : $valor; - $valor = str_replace(array(',', '.'), '', $valor); - } elseif (in_array($tipo, array('A', 'X'))) { + $valor = str_replace([',', '.'], '', $valor); + } elseif (in_array($tipo, ['A', 'X', 'Z'])) { // Adiciona 'x' como uma condição válida $left = '-'; $type = 's'; } else { - throw new \Exception('Tipo inválido'); + throw new ValidationException('Tipo inválido'); } + + // Verifica se o tipo é 'x' minúsculo e então retorna a string em minúsculas + if ($tipo === 'Z') { + return strtolower(sprintf("%{$left}{$sFill}{$tamanho}{$type}", mb_substr($valor, 0, $tamanho))); + } else { return sprintf("%{$left}{$sFill}{$tamanho}{$type}", mb_substr($valor, 0, $tamanho)); + } } /** * @param Carbon|string $date * @param string $format * - * @return integer - * @throws \Exception + * @return int */ public static function fatorVencimento($date, $format = 'Y-m-d') { @@ -511,6 +530,7 @@ public static function fatorVencimento($date, $format = 'Y-m-d') if ($limit >= 1000) { return $limit; } + return $limit + 9000; } @@ -524,6 +544,7 @@ public static function dataJuliano($date, $format = 'Y-m-d') { $date = ($date instanceof Carbon) ? $date : Carbon::createFromFormat($format, $date); $dateDiff = $date->copy()->day(31)->month(12)->subYear()->diffInDays($date); + return $dateDiff . mb_substr($date->year, -1); } @@ -535,7 +556,8 @@ public static function dataJuliano($date, $format = 'Y-m-d') */ public static function fatorVencimentoBack($factor, $format = 'Y-m-d') { - $date = Carbon::create(1997, 10, 7, 0, 0, 0)->addDays($factor); + $date = Carbon::create(1997, 10, 7, 0, 0, 0)->addDays((int) $factor); + return $format ? $date->format($format) : $date; } @@ -547,7 +569,6 @@ public static function fatorVencimentoBack($factor, $format = 'Y-m-d') * @param int $resto10 * * @return int - * */ public static function modulo11($n, $factor = 2, $base = 9, $x10 = 0, $resto10 = 0) { @@ -566,8 +587,10 @@ public static function modulo11($n, $factor = 2, $base = 9, $x10 = 0, $resto10 = if ($digito == 10) { $digito = $resto10; } + return $digito; } + return $sum%11; } @@ -581,12 +604,11 @@ public static function modulo10($n) $chars = array_reverse(str_split($n, 1)); $odd = array_intersect_key($chars, array_fill_keys(range(1, count($chars), 2), null)); $even = array_intersect_key($chars, array_fill_keys(range(0, count($chars), 2), null)); - $even = array_map( - function ($n) { + $even = array_map(function ($n) { return ($n >= 5) ? 2*$n - 9 : 2*$n; - }, $even - ); + }, $even); $total = array_sum($odd) + array_sum($even); + return ((floor($total/10) + 1)*10 - $total)%10; } @@ -594,12 +616,12 @@ function ($n) { * @param array $a * * @return string - * @throws \Exception + * @throws ValidationException */ public static function array2Controle(array $a) { if (preg_match('/[0-9]/', implode('', array_keys($a)))) { - throw new \Exception('Somente chave alfanumérica no array, para separar o controle pela chave'); + throw new ValidationException('Somente chave alfanumérica no array, para separar o controle pela chave'); } $controle = ''; @@ -608,7 +630,7 @@ public static function array2Controle(array $a) } if (mb_strlen($controle) > 25) { - throw new \Exception('Controle muito grande, máximo permitido de 25 caracteres'); + throw new ValidationException('Controle muito grande, máximo permitido de 25 caracteres'); } return $controle; @@ -628,8 +650,10 @@ public static function controle2array($controle) foreach ($matches as $match) { $matches_founded[$match[2]] = (int) $match[3]; } + return $matches_founded; } + return [$controle]; } @@ -640,7 +664,7 @@ public static function controle2array($controle) * @param string $ocorrencia * * @return string - * @throws \Exception + * @throws ValidationException * @codeCoverageIgnore */ public static function criarRetornoFake($file, $ocorrencia = '02') @@ -652,45 +676,47 @@ public static function criarRetornoFake($file, $ocorrencia = '02') // header self::adiciona($retorno[0], 1, 9, '02RETORNO'); switch ($banco) { - case Contracts\Boleto\Boleto::COD_BANCO_BB: + case BoletoContract::COD_BANCO_BB: self::adiciona($retorno[0], 27, 30, self::remove(27, 30, $remessa[0])); self::adiciona($retorno[0], 31, 31, self::remove(31, 31, $remessa[0])); self::adiciona($retorno[0], 32, 39, self::remove(32, 39, $remessa[0])); self::adiciona($retorno[0], 40, 40, self::remove(40, 40, $remessa[0])); self::adiciona($retorno[0], 150, 156, self::remove(130, 136, $remessa[0])); break; - case Contracts\Boleto\Boleto::COD_BANCO_SANTANDER: + case BoletoContract::COD_BANCO_SANTANDER: self::adiciona($retorno[0], 27, 30, self::remove(27, 30, $remessa[0])); self::adiciona($retorno[0], 39, 46, '0' . self::remove(40, 46, $remessa[0])); break; - case Contracts\Boleto\Boleto::COD_BANCO_CEF: + case BoletoContract::COD_BANCO_CEF: self::adiciona($retorno[0], 27, 30, self::remove(27, 30, $remessa[0])); self::adiciona($retorno[0], 31, 36, self::remove(31, 36, $remessa[0])); break; - case Contracts\Boleto\Boleto::COD_BANCO_BRADESCO: + case BoletoContract::COD_BANCO_BRADESCO: + case BoletoContract::COD_BANCO_OURINVEST: + case BoletoContract::COD_BANCO_CRESOL: self::adiciona($retorno[0], 27, 46, self::remove(27, 46, $remessa[0])); break; - case Contracts\Boleto\Boleto::COD_BANCO_ITAU: + case BoletoContract::COD_BANCO_ITAU: self::adiciona($retorno[0], 27, 30, self::remove(27, 30, $remessa[0])); self::adiciona($retorno[0], 33, 37, self::remove(33, 37, $remessa[0])); self::adiciona($retorno[0], 38, 38, self::remove(38, 38, $remessa[0])); break; - case Contracts\Boleto\Boleto::COD_BANCO_HSBC: + case BoletoContract::COD_BANCO_HSBC: self::adiciona($retorno[0], 28, 31, self::remove(28, 31, $remessa[0])); self::adiciona($retorno[0], 38, 43, self::remove(38, 43, $remessa[0])); self::adiciona($retorno[0], 44, 44, self::remove(44, 44, $remessa[0])); break; - case Contracts\Boleto\Boleto::COD_BANCO_SICREDI: + case BoletoContract::COD_BANCO_SICREDI: self::adiciona($retorno[0], 27, 31, self::remove(27, 31, $remessa[0])); self::adiciona($retorno[0], 32, 45, self::remove(32, 45, $remessa[0])); self::adiciona($retorno[0], 111, 117, self::remove(111, 117, $remessa[0])); break; - case Contracts\Boleto\Boleto::COD_BANCO_BANRISUL: + case BoletoContract::COD_BANCO_BANRISUL: self::adiciona($retorno[0], 27, 39, self::remove(18, 30, $remessa[0])); self::adiciona($retorno[0], 47, 76, self::remove(47, 76, $remessa[0])); break; default: - throw new \Exception("Banco: $banco, inválido"); + throw new ValidationException("Banco: $banco, inválido"); } self::adiciona($retorno[0], 77, 79, $banco); self::adiciona($retorno[0], 95, 100, date('dmy')); @@ -700,6 +726,9 @@ public static function criarRetornoFake($file, $ocorrencia = '02') array_pop($remessa); // remove o trailer foreach ($remessa as $detalhe) { + if (! in_array(self::remove(1, 1, $detalhe), [0, 1, 9])) { + continue; + } $i = count($retorno); $retorno[$i] = array_fill(0, 400, '0'); self::adiciona($retorno[$i], 1, 1, '1'); @@ -711,7 +740,8 @@ public static function criarRetornoFake($file, $ocorrencia = '02') self::adiciona($retorno[$i], 117, 126, self::remove(111, 120, $detalhe)); self::adiciona($retorno[$i], 395, 400, sprintf('%06s', count($retorno))); switch ($banco) { - case Contracts\Boleto\Boleto::COD_BANCO_BB: + + case BoletoContract::COD_BANCO_BB: if (self::remove(1, 1, $detalhe) != 7) { unset($retorno[$i]); continue 2; @@ -719,35 +749,37 @@ public static function criarRetornoFake($file, $ocorrencia = '02') self::adiciona($retorno[$i], 1, 1, '7'); self::adiciona($retorno[$i], 64, 80, self::remove(64, 80, $detalhe)); break; - case Contracts\Boleto\Boleto::COD_BANCO_SANTANDER: + case BoletoContract::COD_BANCO_SANTANDER: self::adiciona($retorno[$i], 63, 71, self::remove(63, 71, $detalhe)); self::adiciona($retorno[$i], 384, 385, self::remove(384, 385, $detalhe)); break; - case Contracts\Boleto\Boleto::COD_BANCO_CEF: + case BoletoContract::COD_BANCO_CEF: self::adiciona($retorno[$i], 57, 73, self::remove(57, 73, $detalhe)); break; - case Contracts\Boleto\Boleto::COD_BANCO_BRADESCO: + case BoletoContract::COD_BANCO_BRADESCO: + case BoletoContract::COD_BANCO_OURINVEST: + case BoletoContract::COD_BANCO_CRESOL: self::adiciona($retorno[$i], 25, 29, self::remove(25, 29, $detalhe)); self::adiciona($retorno[$i], 30, 36, self::remove(30, 36, $detalhe)); self::adiciona($retorno[$i], 37, 37, self::remove(37, 37, $detalhe)); self::adiciona($retorno[$i], 71, 82, self::remove(71, 82, $detalhe)); break; - case Contracts\Boleto\Boleto::COD_BANCO_ITAU: + case BoletoContract::COD_BANCO_ITAU: self::adiciona($retorno[$i], 86, 94, self::remove(63, 70, $detalhe)); break; - case Contracts\Boleto\Boleto::COD_BANCO_HSBC: + case BoletoContract::COD_BANCO_HSBC: self::adiciona($retorno[$i], 63, 73, self::remove(63, 73, $detalhe)); break; - case Contracts\Boleto\Boleto::COD_BANCO_SICREDI: + case BoletoContract::COD_BANCO_SICREDI: self::adiciona($retorno[$i], 48, 62, '00000' . self::remove(48, 56, $detalhe)); break; - case Contracts\Boleto\Boleto::COD_BANCO_BANRISUL: + case BoletoContract::COD_BANCO_BANRISUL: self::adiciona($retorno[$i], 38, 62, self::remove(38, 62, $detalhe)); self::adiciona($retorno[$i], 63, 72, self::remove(111, 120, $detalhe)); self::adiciona($retorno[$i], 18, 30, self::remove(18, 30, $detalhe)); break; default: - throw new \Exception("Banco: $banco, inválido"); + throw new ValidationException("Banco: $banco, inválido"); } } @@ -756,11 +788,9 @@ public static function criarRetornoFake($file, $ocorrencia = '02') self::adiciona($retorno[$i], 1, 1, '9'); self::adiciona($retorno[$i], 395, 400, sprintf('%06s', count($retorno))); - $retorno = array_map( - function ($a) { + $retorno = array_map(function ($a) { return implode('', $a); - }, $retorno - ); + }, $retorno); return implode("\r\n", $retorno); } @@ -773,7 +803,7 @@ function ($a) { * @param $array * * @return string - * @throws \Exception + * @throws ValidationException */ public static function remove($i, $f, &$array) { @@ -784,11 +814,11 @@ public static function remove($i, $f, &$array) $i--; if ($i > 398 || $f > 400) { - throw new \Exception('$ini ou $fim ultrapassam o limite máximo de 400'); + throw new ValidationException('$ini ou $fim ultrapassam o limite máximo de 400'); } if ($f < $i) { - throw new \Exception('$ini é maior que o $fim'); + throw new ValidationException('$ini é maior que o $fim'); } $t = $f - $i; @@ -806,29 +836,29 @@ public static function remove($i, $f, &$array) * Função para add valor a linha nas posições informadas. * * @param $line - * @param integer $i - * @param integer $f + * @param int $i + * @param int $f * @param $value * * @return array - * @throws \Exception + * @throws ValidationException */ public static function adiciona(&$line, $i, $f, $value) { $i--; if (($i > 398 || $f > 400) && ($i != 401 && $f != 444)) { - throw new \Exception('$ini ou $fim ultrapassam o limite máximo de 400'); + throw new ValidationException('$ini ou $fim ultrapassam o limite máximo de 400'); } if ($f < $i) { - throw new \Exception('$ini é maior que o $fim'); + throw new ValidationException('$ini é maior que o $fim'); } $t = $f - $i; if (mb_strlen($value) > $t) { - throw new \Exception(sprintf('String $valor maior que o tamanho definido em $ini e $fim: $valor=%s e tamanho é de: %s', mb_strlen($value), $t)); + throw new ValidationException(sprintf('String $valor maior que o tamanho definido em $ini e $fim: $valor=%s e tamanho é de: %s', mb_strlen($value), $t)); } $value = sprintf("%{$t}s", $value); @@ -846,7 +876,8 @@ public static function adiciona(&$line, $i, $f, $value) public static function isCnab240($content) { $content = is_array($content) ? $content[0] : $content; - return mb_strlen(rtrim($content, "\r\n")) == 240 ? true : false; + + return mb_strlen(rtrim($content, "\r\n")) == 240; } /** @@ -858,7 +889,8 @@ public static function isCnab240($content) public static function isCnab400($content) { $content = is_array($content) ? $content[0] : $content; - return mb_strlen(rtrim($content, "\r\n")) == 400 ? true : false; + + return mb_strlen(rtrim($content, "\r\n")) == 400; } /** @@ -905,6 +937,7 @@ public static function isHeaderRetorno($header) if (self::isCnab240($header) && mb_substr($header, 142, 1) != '2') { return false; } + return true; } @@ -950,7 +983,7 @@ public static function IPTE2CodigoBarras($ipte) * @param $ipte * * @return array - * @throws \Exception + * @throws ValidationException */ public static function IPTE2Variveis($ipte) { @@ -978,21 +1011,63 @@ public static function IPTE2Variveis($ipte) return $variaveis; } + /** + * @param $codigo + * @return string + */ + public static function codigoBarras2LinhaDigitavel($codigo) + { + $parte1 = substr($codigo, 0, 4) . substr($codigo, 19, 5); + $parte1 .= Util::modulo10($parte1); + + $parte2 = substr($codigo, 24, 10); + $parte2 .= Util::modulo10($parte2); + + $parte3 = substr($codigo, 34, 10); + $parte3 .= Util::modulo10($parte3); + + $parte4 = substr($codigo, 4, 1); + + $parte5 = substr($codigo, 5, 14); + + return $parte1 . $parte2 . $parte3 . $parte4 . $parte5; + } + + /** + * @param $linhaDigitavel + * @return string + * @throws ValidationException + */ + public static function formatLinhaDigitavel($linhaDigitavel) + { + // Remover espaços em branco + $linhaDigitavel = Util::onlyNumbers($linhaDigitavel); + + // Verificar se a linha digitável possui 47 caracteres + if (strlen($linhaDigitavel) != 47) { + throw new ValidationException('A linha digitável deve ter 47 caracteres.'); + } + + return self::maskString($linhaDigitavel, '#####.##### #####.###### #####.###### # ##############'); + } + /** * @param $banco * * @return string - * @throws \Exception + * @throws ValidationException */ - public static function getBancoClass($banco) { - + public static function getBancoClass($banco) + { $aBancos = [ + BoletoContract::COD_BANCO_BB => 'Banco\\Bb', BoletoContract::COD_BANCO_BNB => 'Banco\\Bnb', BoletoContract::COD_BANCO_SANTANDER => 'Banco\\Santander', BoletoContract::COD_BANCO_BANRISUL => 'Banco\\Banrisul', BoletoContract::COD_BANCO_INTER => 'Banco\\Inter', BoletoContract::COD_BANCO_CEF => 'Banco\\Caixa', + BoletoContract::COD_BANCO_BTG => 'Banco\\Btg', BoletoContract::COD_BANCO_UNICRED => 'Banco\\Unicred', BoletoContract::COD_BANCO_BRADESCO => 'Banco\\Bradesco', BoletoContract::COD_BANCO_FIBRA => 'Banco\\Fibra', @@ -1000,15 +1075,18 @@ public static function getBancoClass($banco) { BoletoContract::COD_BANCO_HSBC => 'Banco\\Hsbc', BoletoContract::COD_BANCO_DELCRED => 'Banco\\Delbank', BoletoContract::COD_BANCO_PINE => 'Banco\\Pine', + BoletoContract::COD_BANCO_OURINVEST => 'Banco\\Ourinvest', BoletoContract::COD_BANCO_SICREDI => 'Banco\\Sicredi', BoletoContract::COD_BANCO_BANCOOB => 'Banco\\Bancoob', + BoletoContract::COD_BANCO_CRESOL => 'Banco\\Cresol', + BoletoContract::COD_BANCO_AILOS => 'Banco\\Ailos', ]; if (array_key_exists($banco, $aBancos)) { return $aBancos[$banco]; } - throw new \Exception("Banco: $banco, inválido"); + throw new ValidationException("Banco: $banco, inválido"); } /** @@ -1016,19 +1094,21 @@ public static function getBancoClass($banco) { * @param $obj * * @return Pessoa - * @throws \Exception + * @throws ValidationException */ public static function addPessoa(&$property, $obj) { if (is_subclass_of($obj, 'VinicciusGuedes\\LaravelCnab\\Contracts\\Pessoa')) { $property = $obj; + return $obj; } elseif (is_array($obj)) { $obj = new Pessoa($obj); $property = $obj; + return $obj; } - throw new \Exception('Objeto inválido, somente Pessoa e Array'); + throw new ValidationException('Objeto inválido, somente Pessoa e Array'); } /** @@ -1041,6 +1121,7 @@ public static function appendStrings() foreach ($strings as $string) { $appended .= " $string"; } + return trim($appended); } @@ -1053,7 +1134,6 @@ public static function appendStrings() * @return int * @internal param $key * @internal param int $default - * */ public static function whichOne($a, ...$parms) { @@ -1074,4 +1154,368 @@ public static function whichOne($a, ...$parms) return null; } + + /** + * @param $cpf + * @return bool + */ + public static function validarCpf($cpf) + { + $c = self::onlyNumbers($cpf); + if (mb_strlen($c) != 11 || preg_match("/^{$c[0]}{11}$/", $c)) { + return false; + } + for ($s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--); + if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { + + return false; + } + for ($s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--); + if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { + + return false; + } + + return true; + } + + /** + * @param $cnpj + * @return bool + */ + public static function validarCnpj($cnpj) + { + $c = self::onlyNumbers($cnpj); + $b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]; + if (mb_strlen($c) != 14 || preg_match("/^{$c[0]}{14}$/", $c)) { + return false; + } + for ($i = 0, $n = 0; $i < 12; $n += $c[$i] * $b[++$i]); + if ($c[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { + + return false; + } + for ($i = 0, $n = 0; $i <= 12; $n += $c[$i] * $b[$i++]); + if ($c[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) { + + return false; + } + + return true; + } + + /** + * @param $documento + * @return bool + */ + public static function validarCnpjCpf($documento) + { + $documento = Util::onlyNumbers($documento); + if (strlen($documento) == 11) { + return self::validarCpf($documento); + } elseif (strlen($documento) == 14) { + return self::validarCnpj($documento); + } + + return false; + } + + /** + * @param $uuid + * @return string + */ + public static function formatarUUID($uuid) + { + $uuidNew = self::onlyNumbers($uuid); + if (preg_match('/[a-zA-Z0-9]{32}/', $uuidNew)) { + return Util::maskString($uuidNew, '########-####-####-####-############'); + } + + return $uuid; + } + + /** + * @param $pix + * @param $valor + * @param $id + * @param Pessoa $beneficiario + * @return string + * @throws ValidationException + */ + public static function gerarPixCopiaECola($pix, $valor, $id, Pessoa $beneficiario) + { + if ($id != Util::normalizeChars($id)) { + throw new ValidationException('ID inválido, não pode possuir caracteres especiais'); + } + + $dinamico = false; + if (filter_var($pix, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) || filter_var('https://' . $pix, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) { + $dinamico = true; + } + + $crc16 = function ($payload) { + $payload .= '6304'; + + $polinomio = 0x1021; + $resultado = 0xFFFF; + if (($length = strlen($payload)) > 0) { + for ($offset = 0; $offset < $length; $offset++) { + $resultado ^= (ord($payload[$offset]) << 8); + for ($bitwise = 0; $bitwise < 8; $bitwise++) { + if (($resultado <<= 1) & 0x10000) { + $resultado ^= $polinomio; + } + $resultado &= 0xFFFF; + } + } + } + + return '6304' . strtoupper(dechex($resultado)); + }; + + $line = function ($id, $value) { + $size = str_pad(mb_strlen($value), 2, '0', STR_PAD_LEFT); + + return $id . $size . $value; + }; + + $gui = $line('00', 'br.gov.bcb.pix'); + if ($dinamico) { + $key = $line('25', preg_replace('/^https?:\/\//', '', $pix)); + $txId = $line('05', '***'); + } else { + $key = $line('01', $pix); + $txId = $line('05', $id); + } + $payload = $line('00', '01'); + if (! $dinamico) { + $payload .= $line('01', '12'); + } + $payload .= $line('26', $gui . $key); + $payload .= $line('52', '0000'); + $payload .= $line('53', '986'); + if (! $dinamico) { + $payload .= $line('54', $valor); + } + $payload .= $line('58', 'BR'); + $payload .= $line('59', Util::normalizeChars($beneficiario->getNome())); + $payload .= $line('60', Util::normalizeChars($beneficiario->getCidade())); + $payload .= $line('62', $txId); + + return $payload . $crc16($payload); + } + + /** + * @param $location + * @return array + */ + public static function fetchPixLocation($location) + { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_URL, $location); + $data = curl_exec($curl); + curl_close($curl); + $datas = explode('.', $data); + if (count($datas) !== 3) { + return []; + } + + return [ + 'fetch' => $data, + 'header' => json_decode(base64_decode($datas[0]), true), + 'payload' => json_decode(base64_decode($datas[1]), true), + 'signature' => $datas[2], + ]; + } + + /** + * @param $pixCopiaECola + * @param null $parent + * @return array|null + */ + public static function decodePixCopiaECola($pixCopiaECola, $parent = null) + { + $structures = [ + '00' => [ + 'type' => 'single', + 'name' => 'Payload Format Indicator', + ], + '01' => [ + 'type' => 'single', + 'name' => 'Point of Initiation Method', + ], + '04' => [ + 'type' => 'single', + 'name' => 'Merchant Account Information – Cartões', + ], + '26' => [ + 'type' => 'multiple', + 'name' => 'Merchant Account Information', + 'multiples' => [ + '00' => [ + 'type' => 'single', + 'name' => 'Globally Unique Identifier', + ], + '01' => [ + 'type' => 'single', + 'name' => 'Pix Key', + ], + '02' => [ + 'type' => 'single', + 'name' => 'Payment Description', + ], + '25' => [ + 'type' => 'single', + 'name' => 'Payment URL', + ], + ], + ], + '52' => [ + 'type' => 'single', + 'name' => 'Merchant Category Code', + ], + '53' => [ + 'type' => 'single', + 'name' => 'Transaction Currency', + ], + '54' => [ + 'type' => 'single', + 'name' => 'Transaction Amount', + ], + '58' => [ + 'type' => 'single', + 'name' => 'Country Code', + ], + '59' => [ + 'type' => 'single', + 'name' => 'Merchant Name', + ], + '60' => [ + 'type' => 'single', + 'name' => 'Merchant City', + ], + '61' => [ + 'type' => 'single', + 'name' => 'Postal Code', + ], + '62' => [ + 'type' => 'multiple', + 'name' => 'Additional Data Field Template', + 'multiples' => [ + '05' => [ + 'type' => 'single', + 'name' => 'Reference Label', + ], + ], + ], + '80' => [ + 'type' => 'multiple', + 'name' => 'Unreserved Templates', + 'multiples' => [ + '00' => [ + 'type' => 'single', + 'name' => 'Globally Unique Identifier', + ], + '01' => [ + 'type' => 'single', + 'name' => 'informação arbitrária do arranjo', + ], + ], + ], + '63' => [ + 'type' => 'single', + 'name' => 'CRC', + ], + ]; + + if ($parent && ! ($structures = Arr::get($structures, "$parent.multiples"))) { + return null; + } + + $aPix = []; + $i = 0; + while ($i < strlen($pixCopiaECola)) { + $code = $codeSearch = substr($pixCopiaECola, $i, 2); + if ($code >= 26 && $code <= 51) { + $codeSearch = 26; + } + if ($code >= 80 && $code <= 99) { + $codeSearch = 80; + } + $i += 2; + $size = intval(substr($pixCopiaECola, $i, 2)); + $i += 2; + if ($structure = Arr::get($structures, $codeSearch)) { + if ($structure['type'] == 'multiple') { + $aPix["$code"] = self::decodePixCopiaECola(substr($pixCopiaECola, $i, $size), $codeSearch); + } else { + $aPix["$code"] = substr($pixCopiaECola, $i, $size); + } + } + $i += $size; + } + + return $aPix; + } + + /** + * @param $chave + * @return string|null + */ + public static function tipoChavePix($chave) + { + if (is_null($chave)) { + return null; + } + + $parametro = trim($chave); + if (filter_var($parametro, FILTER_VALIDATE_EMAIL)) { + + return AbstractBoleto::TIPO_CHAVEPIX_EMAIL; + } + + if (Util::validarCnpj($parametro)) { + + return AbstractBoleto::TIPO_CHAVEPIX_CNPJ; + } + + if (Util::validarCpf($parametro)) { + + return AbstractBoleto::TIPO_CHAVEPIX_CPF; + } + + // Verificar se é um telefone + if (preg_match('/^(\+\d{2}\s?)?[-.\s]?\(?\d{2}\)?[-.\s]?(\d\s?)?\d{4}[-.\s]?\d{4}$/', $parametro)) { + + return AbstractBoleto::TIPO_CHAVEPIX_CELULAR; + } + + $parametro = Util::onlyAlphanumber($parametro); + // Verificar se é um UUID + if (preg_match('/^[a-fA-F0-9]{32}$/', $parametro) && (ctype_xdigit($parametro))) { + return AbstractBoleto::TIPO_CHAVEPIX_ALEATORIA; + } + + return null; + } + + /** + * @param $str + * @return bool + */ + public static function isBase64($str) + { + try { + $decoded = base64_decode($str, true); + + if (base64_encode($decoded) === $str) { + return true; + } else { + return false; + } + } catch (Exception $e) { + return false; + } + } } diff --git a/src/Webhook/AbstractWebhook.php b/src/Webhook/AbstractWebhook.php new file mode 100644 index 00000000..73dd5743 --- /dev/null +++ b/src/Webhook/AbstractWebhook.php @@ -0,0 +1,176 @@ +setPost($post); + $this->setPost($headers); + } + + /** + * @return array + */ + public function getPost() + { + return $this->post; + } + + /** + * @param array $post + * @return $this + */ + public function setPost(array $post) + { + $this->post = $post; + + return $this; + } + + /** + * @return array + */ + public function getHeaders() + { + return $this->headers; + } + + /** + * @param array $headers + * @return AbstractWebhook + */ + public function setHeaders(array $headers) + { + $this->headers = $headers; + + return $this; + } + + /** + * @param string|null $agencia + * @return AbstractWebhook + */ + public function setAgencia($agencia) + { + $this->agencia = $agencia; + + return $this; + } + + /** + * @return string|null + */ + public function getAgencia() + { + return $this->agencia; + } + + /** + * @param string|null $agenciaDv + * @return AbstractWebhook + */ + public function setAgenciaDv($agenciaDv) + { + $this->agenciaDv = $agenciaDv; + + return $this; + } + + /** + * @return string|null + */ + public function getAgenciaDv() + { + return $this->agenciaDv; + } + + /** + * @param string|null $conta + * @return AbstractWebhook + */ + public function setConta($conta) + { + $this->conta = $conta; + + return $this; + } + + /** + * @return string|null + */ + public function getConta() + { + return $this->conta; + } + + /** + * @param string|null $contaDv + * @return AbstractWebhook + */ + public function setContaDv($contaDv) + { + $this->contaDv = $contaDv; + + return $this; + } + + /** + * @return string|null + */ + public function getContaDv() + { + return $this->contaDv; + } + + /** + * @return Boleto[] + */ + abstract public function processar(); +} diff --git a/src/Webhook/Banco/Inter.php b/src/Webhook/Banco/Inter.php new file mode 100644 index 00000000..c14f9c87 --- /dev/null +++ b/src/Webhook/Banco/Inter.php @@ -0,0 +1,51 @@ +setConta(Arr::get($this->getHeaders(), 'x-conta-corrente')); + + $aRet = []; + foreach ($this->getPost() as $item) { + $boleto = new Boleto(); + $boleto->setNossoNumero(Arr::get($item, 'nossoNumero')); + $boleto->setNumeroDocumento(Arr::get($item, 'seuNumero')); + $boleto->setNumero($boleto->getNumeroDocumento()); + $boleto->setDataOcorrencia(new Carbon(Arr::get($item, 'dataHoraSituacao', Arr::get($item, 'horario', 'now')))); + $boleto->setValor(Arr::get($item, 'valorNominal', Arr::get($item, 'componentesValor.original.valor'))); + $boleto->setValorRecebido(Arr::get($item, 'valorTotalRecebimento', Arr::get($item, 'valor'))); + $boleto->setCodigoBarras(Arr::get($item, 'codigoBarras')); + $boleto->setLinhaDigitavel(Arr::get($item, 'linhaDigitavel')); + $boleto->setMotivo(Arr::get($item, 'motivoCancelamento')); + $boleto->setOcorrenciaTipo( + match (Arr::get($item, 'situacao')) { + 'A_RECEBER' => Boleto::OCORRENCIA_ENTRADA, + 'PAGO', 'MARCADO_RECEBIDO', 'RECEBIDO' => Boleto::OCORRENCIA_LIQUIDADA, + 'CANCELADO', 'EXPIRADO' => Boleto::OCORRENCIA_BAIXADA, + default => Boleto::OCORRENCIA_OUTROS, + } + ); + $boleto->setOcorrenciaOrigem( + Arr::get($item, 'origemRecebimento', 'BOLETO') == 'PIX' || ! is_null(Arr::get($item, 'txid')) + ? Boleto::OCORRENCIA_ORIGEM_PIX + : Boleto::OCORRENCIA_ORIGEM_BOLETO + ); + $boleto->setTxid(Arr::get($item, 'txid')); + $boleto->setPix(Arr::get($item, 'pixCopiaECola')); + $aRet[] = $boleto; + } + + return $aRet; + } +} diff --git a/src/Webhook/Boleto.php b/src/Webhook/Boleto.php new file mode 100644 index 00000000..d3cf2fa5 --- /dev/null +++ b/src/Webhook/Boleto.php @@ -0,0 +1,400 @@ +numero; + } + + /** + * @param mixed $numero + * @return Boleto + */ + public function setNumero($numero) + { + $this->numero = $numero; + + return $this; + } + + /** + * @return mixed + */ + public function getNumeroDocumento() + { + return $this->numeroDocumento; + } + + /** + * @param mixed $numeroDocumento + * @return Boleto + */ + public function setNumeroDocumento($numeroDocumento) + { + $this->numeroDocumento = $numeroDocumento; + + return $this; + } + + /** + * @return mixed + */ + public function getNossoNumero() + { + return $this->nossoNumero; + } + + /** + * @param mixed $nossoNumero + * @return Boleto + */ + public function setNossoNumero($nossoNumero) + { + $this->nossoNumero = $nossoNumero; + + return $this; + } + + /** + * @return Carbon + */ + public function getDataOcorrencia() + { + return $this->dataOcorrencia; + } + + /** + * @return mixed + */ + public function getOcorrenciaOrigem() + { + return $this->ocorrenciaOrigem; + } + + /** + * @param mixed $ocorrenciaOrigem + * @return Boleto + */ + public function setOcorrenciaOrigem($ocorrenciaOrigem) + { + $this->ocorrenciaOrigem = $ocorrenciaOrigem; + + return $this; + } + + /** + * @param Carbon $dataOcorrencia + * @return Boleto + */ + public function setDataOcorrencia(Carbon $dataOcorrencia) + { + $this->dataOcorrencia = $dataOcorrencia; + + return $this; + } + + /** + * @return mixed + */ + public function getValor() + { + return $this->valor; + } + + /** + * @param mixed $valor + * @return Boleto + */ + public function setValor($valor) + { + $this->valor = $valor; + + return $this; + } + + /** + * @return mixed + */ + public function getValorRecebido() + { + return $this->valorRecebido; + } + + /** + * @param mixed $valorRecebido + * @return Boleto + */ + public function setValorRecebido($valorRecebido) + { + $this->valorRecebido = $valorRecebido; + + return $this; + } + + /** + * @return mixed + */ + public function getOcorrenciaTipo() + { + return $this->ocorrenciaTipo; + } + + /** + * @param mixed $ocorrenciaTipo + * @return Boleto + */ + public function setOcorrenciaTipo($ocorrenciaTipo) + { + $this->ocorrenciaTipo = $ocorrenciaTipo; + + return $this; + } + + /** + * @return mixed + */ + public function getTxid() + { + return $this->txid; + } + + /** + * @param mixed $txid + * @return Boleto + */ + public function setTxid($txid) + { + $this->txid = $txid; + + return $this; + } + + /** + * @return mixed + */ + public function getPix() + { + return $this->pix; + } + + /** + * @param mixed $pix + * @return Boleto + */ + public function setPix($pix) + { + $this->pix = $pix; + + return $this; + } + + /** + * @return mixed + */ + public function getCodigoBarras() + { + return $this->codigoBarras; + } + + /** + * @param mixed $codigoBarras + * @return Boleto + */ + public function setCodigoBarras($codigoBarras) + { + $this->codigoBarras = Util::onlyNumbers($codigoBarras); + + return $this; + } + + /** + * @return mixed + */ + public function getLinhaDigitavelFormatada() + { + return $this->linhaDigitavelFormatada; + } + + /** + * @return mixed + */ + public function getLinhaDigitavel() + { + return $this->linhaDigitavel; + } + + /** + * @param mixed $linhaDigitavel + * @return Boleto + */ + public function setLinhaDigitavel($linhaDigitavel) + { + $this->linhaDigitavel = Util::onlyNumbers($linhaDigitavel); + try { + $this->linhaDigitavelFormatada = Util::formatLinhaDigitavel($this->getLinhaDigitavel()); + } catch (Exception $e) { + } + + return $this; + } + + /** + * @return Carbon + */ + public function getDataVencimento() + { + return $this->dataVencimento; + } + + /** + * @param Carbon $dataVencimento + * @return Boleto + */ + public function setDataVencimento(Carbon $dataVencimento) + { + $this->dataVencimento = $dataVencimento; + + return $this; + } + + /** + * @return mixed + */ + public function getValorTarifa() + { + return $this->valorTarifa; + } + + /** + * @param mixed $valorTarifa + * @return Boleto + */ + public function setValorTarifa($valorTarifa) + { + $this->valorTarifa = $valorTarifa; + + return $this; + } + + /** + * @return mixed + */ + public function getMotivo() + { + return $this->motivo; + } + + /** + * @param mixed $motivo + * @return Boleto + */ + public function setMotivo($motivo) + { + $this->motivo = $motivo; + + return $this; + } +} diff --git a/tests/Boleto/BoletoTest.php b/tests/Boleto/BoletoTest.php index fb7fae31..48409e55 100644 --- a/tests/Boleto/BoletoTest.php +++ b/tests/Boleto/BoletoTest.php @@ -2,33 +2,31 @@ namespace VinicciusGuedes\LaravelCnab\Tests\Boleto; -use VinicciusGuedes\LaravelCnab\Boleto\Banco as Boleto; -use VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf; -use VinicciusGuedes\LaravelCnab\Pessoa; -use VinicciusGuedes\LaravelCnab\Tests\TestCase; use Exception; +use VinicciusGuedes\LaravelCnab\Pessoa; use PHPUnit\Framework\Constraint\IsType; +use VinicciusGuedes\LaravelCnab\Tests\TestCase; +use VinicciusGuedes\LaravelCnab\Boleto\Render\Pdf; +use VinicciusGuedes\LaravelCnab\Boleto\Banco as Boleto; class BoletoTest extends TestCase { protected static $pagador; + protected static $beneficiario; public static function setUpBeforeClass(): void { - self::$beneficiario = new Pessoa( - [ + self::$beneficiario = new Pessoa([ 'nome' => 'ACME', 'endereco' => 'Rua um, 123', 'cep' => '99999-999', 'uf' => 'UF', 'cidade' => 'CIDADE', 'documento' => '99.999.999/9999-99', - ] - ); + ]); - self::$pagador = new Pessoa( - [ + self::$pagador = new Pessoa([ 'nome' => 'Cliente', 'endereco' => 'Rua um, 123', 'bairro' => 'Bairro', @@ -36,8 +34,7 @@ public static function setUpBeforeClass(): void 'uf' => 'UF', 'cidade' => 'CIDADE', 'documento' => '999.999.999-99', - ] - ); + ]); } public static function tearDownAfterClass() : void @@ -48,20 +45,20 @@ public static function tearDownAfterClass() : void ]; $files = glob(implode(DIRECTORY_SEPARATOR, $aFiles) . '/*'); // get all file names foreach($files as $file){ - if(is_file($file)) + if (is_file($file)) { @unlink($file); + } } } public function testAddBoletos() { - $boleto = new Boleto\Banrisul( - [ + $boleto = new Boleto\Banrisul([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 20, 'numeroDocumento' => 1, @@ -72,10 +69,9 @@ public function testAddBoletos() 'conta' => 22222, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $pdf = new Pdf(); $pdf->addBoletos([$boleto, $boleto]); @@ -85,13 +81,12 @@ public function testAddBoletos() public function testSave() { - $boleto = new Boleto\Banrisul( - [ + $boleto = new Boleto\Banrisul([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 20, 'numeroDocumento' => 1, @@ -102,15 +97,14 @@ public function testSave() 'conta' => 22222, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', - 'boletos1.pdf' + 'boletos1.pdf', ]); $pdf = new Pdf(); @@ -123,13 +117,12 @@ public function testSave() public function testSaveJS() { - $boleto = new Boleto\Banrisul( - [ + $boleto = new Boleto\Banrisul([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 20, 'numeroDocumento' => 1, @@ -140,20 +133,19 @@ public function testSaveJS() 'conta' => 22222, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', - 'boletos2.pdf' + 'boletos2.pdf', ]); $pdf = new Pdf(); - $pdf->addBoletos([$boleto, $boleto]); - $file2 = $pdf->gerarBoleto($pdf::OUTPUT_SAVE, $file, true); + $pdf->addBoletos([$boleto, $boleto])->showPrint(); + $file2 = $pdf->gerarBoleto($pdf::OUTPUT_SAVE, $file); $this->assertEquals($file, $file2); $this->assertFileExists($file); @@ -161,12 +153,11 @@ public function testSaveJS() public function testWithoutLogo() { - $boleto = new Boleto\Banrisul( - [ - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + $boleto = new Boleto\Banrisul([ + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 20, 'numeroDocumento' => 1, @@ -177,15 +168,14 @@ public function testWithoutLogo() 'conta' => 22222, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', - 'boletos3.pdf' + 'boletos3.pdf', ]); $pdf = new Pdf(); @@ -205,13 +195,12 @@ public function testSemBoletoAdicionado() public function testBoletoBanrisul() { - $boleto = new Boleto\Banrisul( - [ + $boleto = new Boleto\Banrisul([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 20, 'numeroDocumento' => 1, @@ -222,10 +211,9 @@ public function testBoletoBanrisul() 'conta' => 22222, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -233,13 +221,12 @@ public function testBoletoBanrisul() public function testBoletoBB() { - $boleto = new Boleto\Bb( - [ + $boleto = new Boleto\Bb([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR. '001.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -248,10 +235,9 @@ public function testBoletoBB() 'convenio' => 1234567, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -259,13 +245,12 @@ public function testBoletoBB() public function testBoletoBradesco() { - $boleto = new Boleto\Bradesco( - [ + $boleto = new Boleto\Bradesco([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '237.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 2, 'numeroDocumento' => 1, @@ -276,10 +261,9 @@ public function testBoletoBradesco() 'conta' => 9999999, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -287,8 +271,7 @@ public function testBoletoBradesco() public function testBoletoCaixa() { - $boleto = new Boleto\Caixa( - [ + $boleto = new Boleto\Caixa([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '104.png', 'dataVencimento' => new \Carbon\Carbon(), 'valor' => 100.41, @@ -305,10 +288,9 @@ public function testBoletoCaixa() 'codigoCliente' => 999999, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -316,13 +298,12 @@ public function testBoletoCaixa() public function testBoletoHSBC() { - $boleto = new Boleto\Hsbc( - [ + $boleto = new Boleto\Hsbc([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '399.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -334,10 +315,9 @@ public function testBoletoHSBC() 'contaDv' => 9, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -345,13 +325,12 @@ public function testBoletoHSBC() public function testBoletoItau() { - $boleto = new Boleto\Itau( - [ + $boleto = new Boleto\Itau([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '341.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -362,10 +341,9 @@ public function testBoletoItau() 'conta' => 99999, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -373,13 +351,12 @@ public function testBoletoItau() public function testBoletoSantander() { - $boleto = new Boleto\Santander( - [ + $boleto = new Boleto\Santander([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '033.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -390,10 +367,9 @@ public function testBoletoSantander() 'codigoCliente' => 9999999, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], - 'aceite' => 'S', + 'aceite' => $this->aceite(), 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -401,8 +377,7 @@ public function testBoletoSantander() public function testBoletoSicredi() { - $boleto = new Boleto\Sicredi( - [ + $boleto = new Boleto\Sicredi([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '748.png', 'dataVencimento' => new \Carbon\Carbon(), 'valor' => 100, @@ -421,8 +396,7 @@ public function testBoletoSicredi() 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -430,8 +404,7 @@ public function testBoletoSicredi() public function testBoletoBancoob() { - $boleto = new Boleto\Bancoob( - [ + $boleto = new Boleto\Bancoob([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '756.png', 'dataVencimento' => new \Carbon\Carbon(), 'valor' => 100, @@ -450,8 +423,7 @@ public function testBoletoBancoob() 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -459,8 +431,7 @@ public function testBoletoBancoob() public function testBoletoBnb() { - $boleto = new Boleto\Bnb( - [ + $boleto = new Boleto\Bnb([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '004.png', 'dataVencimento' => new \Carbon\Carbon(), 'valor' => 100, @@ -478,8 +449,115 @@ public function testBoletoBnb() 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boleto->renderHTML()); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoPine() + { + $boleto = new Boleto\Pine([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '643.png', + 'dataVencimento' => new \Carbon\Carbon('2023-03-09'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => '112', + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234', + 'modalidadeCarteira' => 'D', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', + ]); + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boleto->renderHTML()); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoFibra() + { + $boleto = new Boleto\Fibra([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '224.png', + 'dataVencimento' => new \Carbon\Carbon('2023-01-04'), + 'valor' => 10, + 'multa' => false, + 'juros' => false, + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'modalidadeCarteira' => 'D', + 'carteira' => 112, + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234567', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', + ]); + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boleto->renderHTML()); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoOurinvest() + { + $boleto = new Boleto\Ourinvest([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '712.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 2, + 'numeroDocumento' => 2, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => '19', + 'agencia' => 0001, + 'conta' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + ]); + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boleto->renderHTML()); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoRendimento() + { + $boleto = new Boleto\Rendimento([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '633.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 2, + 'numeroDocumento' => 2, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => '121', + 'agencia' => '0001', + 'codigoCliente' => '5447390', + 'conta' => '1234', + 'modalidadeCarteira' => '6', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); @@ -487,9 +565,248 @@ public function testBoletoBnb() public function testBoletoBBWithQRCodePix() { - $boleto = new Boleto\Bb( - [ + $boleto = new Boleto\Bb([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '001.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => 11, + 'convenio' => 1234567, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'pix_qrcode' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAABgAAAAYADwa0LPAAAObElEQVR42u3dQU7jTBPG8SbhFKC5QGaHwMNxUA4WcZzEQrMicwAWcwoHf4tRRswb+OJyXK567P9P8g417XbnmUzSRV21bdsWABCwiJ4AAHRFYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkJEmsG5vb8vV1RWX4cpgv9+Xh4eHslwuR7335XJZfvz4Ufb7PftsBvvsKE1gQdPT01N5eXkp7+/vo/7e9/f3Utd1Wa/X0UuAERFYuMjPnz9Df//Ly0v0EmBEBBYuMvY7q2y/H+MisADIILAAyCCwAMggsADIILDQ2+FwiJ4CZobAQm8cKcDYrqMnAD2Hw6G8vLxwaBOjk3yH9fb2Vtq2neR1c3PjsmZDltBcX1+Xx8fH8uvXL9McVqtVqeu6NE3z6b03TVO2221ZrVbRW6yUwj7LSDKwYBdVQvPR8/Pz39D8zLE+cLPZhM0RuRFYMxFdQlNKKXd3d51+7v7+PnqqSIrAmokMJSxfvbPq+3OYHwILgAwCC4AMAguADAILgAwCayYWi/hH3bWUh5IffCV+F2MUGY4KdC3loeQHXyGwZmKz2ZSqqkLfaa3X67Lb7b58B3U4HMput6PkB1+afC1hhq4fbdtGT6F8//697Ha7Qcb6WEtoKc/59etXeXx8jF4KF+yzcfAOC2aU0CAKgYXeMnwuhnkhsNAbJTQYG4EFQAaBBUAGgQVABoEFQAaBhYtkKPnBfLDbcBGONmBMBBYukqHkB/PBLpuJIbvmHE+67/f7vyU/h8Ph4k4u2brmIB8CayaG7Jrz/v5e6roevEiZkh+cQ2DNhEfXHK8/A8PnYvgKgTUTHl1zvDrxUPKDrxBYAGQQWABkEFgAZBBYAGQQWDPBwU5MAbt4JjgqgCkgsGaCEhpMAbt3Js6V0FAWAwUEFkoplMVAA4GFf/BZFzIjsPAPymKQGYEFQAaBBUAGgQVABoEFQAaBhRNdD5d6HkLNMAfkw9PGia5HGzyPQGSYA/IhsHDiXBnPYrEoVVW5HjLNMAfkcx09AW9t20ZPIYX9fl+enp7Kz58/P/3TxovFotzf35fNZvO3jGeKc/DCPhsH77Bm4lzXHK9OONnmAG0E1kx07Zrj1QknyxygjcCaia4dbrw64WSZA7QRWABkEFgAZBBYAGQQWABkEFgYDeU2uBQ7A6Oh3AaXIrAwGsptcLE2iZubm7aUwmW4LLzGfX19be/v79vFYvHpWIvFoq2qqn19fU0xLvvMd595SzMbNpJmYN3f33cas6qqFOOyz7QD66ptc1Rt3t7elt+/f0dPQ4rl0V1dXbmMu1wuO51MXywW5XA4hI/LPrNLEhGlFD7DwoW8ym0o48FnCCwAMggsADIILAAyCCwAMgismfAqi1EbF9p42jPhVRajNi7ERR8EO+JAn++BvtfX17aqKpcT6Urjss84OIqJsXa3AcZCYOHEw8NDp0YQVVVJteKCPgILJ7zKYoBLEVg44VV3CFyKbwkByCCwAMggsADIILAAyCCwcIKyGGTFjsMJymKQFYGFE3S3QVrRtUFH57qkqF1e3WKyzXfIe8vWYYdx80kTWF27pKhdXt1isszX496ydNhh3HzSnHTvWg6ixqtbTJb5Wqh12GHcfNIElqUcRI1liTOsg9eW8Cr5YVzfcTPhQ3cAMggsADIILAAyCCwAMgisZKZa7mL9Vqrrz6t+28U69DPNV4ewqZa7dPmTy31+3jquGtbhP6IPgh2VBIc8vS6Lc91iss33nKZp2u12265WK9McVqtVu91u26ZpBh3Xa096jZthHTJJM3PrQ6zrevCHqBAAFmNsZrWSKq896TVuhnXIRPLgaF3X5eHh4ezP7Xa78vj4GH1r4Yf0rOtgmW/XDjtZWO4twwHPDOuQiWRgNU1Tlsvl2Z87HA7l+vo6+tbCN4d1HSzzjS4lsiKw7PPNRPJD9y5hZfm5qfNcB6Wwgj7JwAIwTwQWABkEFgAZBBYAGWkCy6tTS3SpS/Tvt85DbX1hp/zM0szcq1NLdKlL9O+3zkNtfWEn/cyiT64enStJueQP80eUumT7g/9TW9++l0WGcae8J/tIE1hRLql1+3/lQR8NWb6i3N3G61lkCBavcaP2ZNZwm31gHW23W9PmqOu689genXAUu9t4PYsMweI1bvSezNZhJ01pTjRr+UrX8qBSfMpXFLvbdOVZUmXZ7mqlOR57MluHHQLrA7UN6vXoMnRfybBmU94PGZ5xH2m+JQSAcwgsADIILAAyCCwAMgisD5TKV7KUV3h9S+jBc83Uutt47XX3eUdPIBOl8pUs5RUefx7Z608ue66ZWncbr73uLvogWCYK5StjnEC2zOdcVxcLr5PufddsyHXIdorfa697kwysDKUuqqUNXXi9oLwuS0nKlNdhDiQPjnp0aqmqqux2u8HnYB03gwxNEiy6dlGa+joIvpTNJAMrQ6mLamlDF2ovVEtJypTXQfClbCYZWJQ2+OKFyjpkxbeEAGQQWABkEFgAZBBYAGRIBlaGUhfV0oapzhnzILkzM5S6yJY2THTOmAfJwNpsNqWqqkHeCSwWi1JVVdlsNoPOoe+4GQy5vsCgoo/aZ5Kh3CZD2VGUvvV2XixzGLI8KNs6ZDKPu+woQycRtQ47Hqxdc7xY5mDpWKO2DplInnT3kqHcJkPZUTRr1xyvLWw56e5RHpRlHTIhsD7IUG6ToewoA7VnMeU5ZMKnqgBkEFgAZBBYAGQQWABkEFgfZCi3yVB2pCa6y47X+ip9szuWae9kowzlNhnKjtREd9nxWt8sHXZSiT4IlkmGTiJqHXa8WO5zyM49lmfhtb6cdP/aPO4Sg5b8jBGaGeag9izmgIOjM+HRacjC2j3I4wBtlg5GXs9iDi9lAmsmPEp+LKzlQR6BlaVEyetZzOGlTGDNRIYOMJatNuUSpSnfmze+JQQgg8ACIIPAAiCDwAIgg8DCaCzf0E25RGnK9+ZtHneJFCxnj6ZcojTle/NGYGE06/W67Ha7Tu+0MnRG8jLle3MXfdT+6ObmZtSSkSlcFpZxz3WA6Vvrdu7KVkKjJkPXJ28ElvBletCGcbt2gLF2del6qXX5ySJD1ydvaU66397elt+/f0dPQ4rl0Xl0gLF2dekqSwmNmgxdn7zxGRZOdG1XNXRbq6PImkdlXddNeX0JLAAyCCwAMggsADIILAAyCKyZ8OoAQ5lJHtFdfka5x+gJYBxeHWAoM8kjusvPKKIPgh1xcNT34KhXBxi6/OSRoeuTN8nAent7i55uinWAXVT3IK/rkn9oFMt4JE+6v729lW/fvkVPOXwdkjw6KdHdg7xYOwJ1XYcsnYaOCKxkCCxf0d2DvFjLbVTLePjQHbMyxbDqc1+qZTwEFgAZBBYAGQQWABkEFgAZBBZmRbksBQQWZka6LAUEFuZlyI41GN/kn9rV1VX4lcF+vy8PDw9luVx+Osflcll+/PhR9vv9oONaLq85fBz3+/fvf1uNtX9K00a5mqYp2+22rFar6K2gLbo26MirlrDrmJ6X1zpYeHVU6Tqu5fKaQ4ZuMV6dhqz7wWtcb5MvzcnwDseyxF6lOV6lGB6lLlMuM/HqNFSKbT9YXhdJIqKUMoP/EuIPr1IMj9KNKZeZeHUamgsCC4AMAguADAILgAwCC4AMAgsXie6aE/2tXyaWtVDtsJNrNpAT3TVnin/uuC/LWqh22CGwcJEhS10Wi0WpqqpsNpuzP3s4HMputyvr9Tp6CdJYr9d/T/Gfc+65WZ7FqKJPrh5x0t2+DhZe8/Xi1d1myDn07SwTtQ+zdsIxrV30BI4ILPs6WKgFlkfJj/XevEp+ovdjhhKlvijNGYFlib1Kc9RKMby621juzavkJ3pPZihR6j336AkAn8lQRqNU8uNxXxkRWABkEFgAZBBYAGQQWABkEFg4ofoN0tBUy1emNt9/5h49AeRDucsfquUrU5vvRwQWTlhKPKZMtnzlC2rz/VT0ydUjTrrb18Ei6t6zla9kYJnvarVq67pum6aJnnYKvMOCq/f391LXNUXKPT0/P/9tYQb+S4iR8LlYP3d3d9FTSIXAwiiUy0Ei8c7qXwQWABkEFgAZBBYAGQQWABkEFkaRoRwkwxws88gy30xYEYwiQzlIhjlY5pFlvpkQWHCVoRwkwxw+mlrJz6iij9ofeZXmqMlQmpOhHMRrvl6dcKLG9bqydtghsJLJEFh1XUcvg9t8vTrhRI/rdWXrsDP5rjlqMnTNaZom/IS113y9OuFEj+slW4cdPsPCieiw8pyvVyec6HG9RP/+/yKwAMggsADIILAAyCCwAMggsDArXmUx0eN6if79J/OJngAwJq+ymOhxvUT//v8isDArXmUxUeN6SVseFH1y9chywpvL96S7hVdJitd8MxhyzZqmabfbbbtardzKmTJJ87QJLM3A8ipJmXJgeazZdrs1rVmG8qs+JEtz8Ifl0VlKXSzjepWkeM03A481OxwO5fr6uvMcMpRf9cFnWLiIV0nKlHmsmTV8FMOqFAILgBACC4AMAguADAILgAwCayaiS0eyjJsBa9af7sxhEl06kmXcDFizC0QfBDvi4KjvwdHX19e2qiqXJglK42bAmvWX5uAoAJzDfwkByCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyPgfua4A7AeOtswAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjItMDktMDZUMDE6MzM6MDErMDA6MDCmKlR4AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDIyLTA5LTA2VDAxOjMzOjAxKzAwOjAw13fsxAAAAABJRU5ErkJggg==', + ]); + + $boletoHtml = $boleto->renderHTML(); + + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boletoHtml); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoBBWithQRCodePixCopiaECola() + { + $boleto = new Boleto\Bb([ 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR. '001.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => 11, + 'convenio' => 1234567, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'pix_qrcode' => '00020104141234567890123426660014BR.GOV.BCB.PIX014466756C616E6F32303139406578616D706C652E636F6D27300012BR.COM.OUTRO011001234567895204000053039865406123.455802BR5915NOMEDORECEBEDOR6008BRASILIA61087007490062530515RP12345678-201950300017BR.GOV.BCB.BRCODE01051.0.080450014BR.GOV.BCB.PIX0123PADRAO.URL.PIX/0123ABCD81390012BR.COM.OUTRO01190123.ABCD.3456.WXYZ6304EB76', + ]); + + $boletoHtml = $boleto->renderHTML(); + + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boletoHtml); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoSantanderPix() + { + $boleto = new Boleto\Santander([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'codigoCliente' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'id' => '123456789012345678901234567890', + 'pix_chave' => '39a1178e-db6b-4407-bc7b-b674390acf5f', + 'pix_chave_tipo' => Boleto\Santander::TIPO_CHAVEPIX_ALEATORIA, + ]); + + $boletoHtml = $boleto->renderHTML(); + + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boletoHtml); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoSantanderPixGeraCopiaECola() + { + $boleto = new Boleto\Santander([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => 100, + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'codigoCliente' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'id' => '123456789012345678901234567890', + 'pix_chave' => '39a1178e-db6b-4407-bc7b-b674390acf5f', + 'pix_chave_tipo' => Boleto\Santander::TIPO_CHAVEPIX_ALEATORIA, + ]); + $boleto->gerarPixCopiaECola(); + + $this->assertEquals('00020101021226580014br.gov.bcb.pix013639a1178e-db6b-4407-bc7b-b674390acf5f5204000053039865406100.005802BR5904ACME6006CIDADE623405301234567890123456789012345678906304F0C4', $boleto->toArray()['pix_qrcode']); + } + + public function testBoletoSantanderPixSemTipo() + { + $this->expectException(Exception::class); + $boleto = new Boleto\Santander([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'codigoCliente' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'id' => '123456789012345678901234567890', + 'pix_chave' => '39a1178e-db6b-4407-bc7b-b674390acf5f', + ]); + + $boletoHtml = $boleto->renderHTML(); + + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boletoHtml); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoSantanderPixTipoSemPix() + { + $this->expectException(Exception::class); + $boleto = new Boleto\Santander([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'codigoCliente' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'id' => '123456789012345678901234567890', + 'pix_chave_tipo' => Boleto\Santander::TIPO_CHAVEPIX_ALEATORIA, + ]); + + $boletoHtml = $boleto->renderHTML(); + + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boletoHtml); + $this->assertNotNull($boleto->renderPDF()); + } + + public function testBoletoSantanderInvalidoID() + { + $this->expectException(Exception::class); + $boleto = new Boleto\Santander([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'codigoCliente' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'id' => '12345678901234567890', + 'pix_chave_tipo' => Boleto\Santander::TIPO_CHAVEPIX_ALEATORIA, + ]); + } + + public function testBoletoSantanderPixTipoEPixSemID() + { + $this->expectException(Exception::class); + $boleto = new Boleto\Santander([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'codigoCliente' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => $this->aceite(), + 'especieDoc' => 'DM', + 'pix_chave' => '39a1178e-db6b-4407-bc7b-b674390acf5f', + 'pix_chave_tipo' => Boleto\Santander::TIPO_CHAVEPIX_ALEATORIA, + ]); + + $boletoHtml = $boleto->renderHTML(); + + $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); + $this->assertNotNull($boletoHtml); + $this->assertNotNull($boleto->renderPDF()); + } + + + public function testBoletoAilos() + { + $boleto = new Boleto\Ailos([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '085.png', 'dataVencimento' => new \Carbon\Carbon(), 'valor' => 100, 'multa' => false, @@ -498,20 +815,19 @@ public function testBoletoBBWithQRCodePix() 'numeroDocumento' => 1, 'pagador' => self::$pagador, 'beneficiario' => self::$beneficiario, - 'carteira' => 11, - 'convenio' => 1234567, + 'carteira' => '1', + 'convenio' => '000000', + 'agencia' => 1111, + 'agenciaDv' => 1, + 'conta' => 11111, + 'contaDv' => 1, 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - 'pix_qrcode' => "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAABgAAAAYADwa0LPAAAObElEQVR42u3dQU7jTBPG8SbhFKC5QGaHwMNxUA4WcZzEQrMicwAWcwoHf4tRRswb+OJyXK567P9P8g417XbnmUzSRV21bdsWABCwiJ4AAHRFYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkEFgAZBBYAGQQWABkJEmsG5vb8vV1RWX4cpgv9+Xh4eHslwuR7335XJZfvz4Ufb7PftsBvvsKE1gQdPT01N5eXkp7+/vo/7e9/f3Utd1Wa/X0UuAERFYuMjPnz9Df//Ly0v0EmBEBBYuMvY7q2y/H+MisADIILAAyCCwAMggsADIILDQ2+FwiJ4CZobAQm8cKcDYrqMnAD2Hw6G8vLxwaBOjk3yH9fb2Vtq2neR1c3PjsmZDltBcX1+Xx8fH8uvXL9McVqtVqeu6NE3z6b03TVO2221ZrVbRW6yUwj7LSDKwYBdVQvPR8/Pz39D8zLE+cLPZhM0RuRFYMxFdQlNKKXd3d51+7v7+PnqqSIrAmokMJSxfvbPq+3OYHwILgAwCC4AMAguADAILgAwCayYWi/hH3bWUh5IffCV+F2MUGY4KdC3loeQHXyGwZmKz2ZSqqkLfaa3X67Lb7b58B3U4HMput6PkB1+afC1hhq4fbdtGT6F8//697Ha7Qcb6WEtoKc/59etXeXx8jF4KF+yzcfAOC2aU0CAKgYXeMnwuhnkhsNAbJTQYG4EFQAaBBUAGgQVABoEFQAaBhYtkKPnBfLDbcBGONmBMBBYukqHkB/PBLpuJIbvmHE+67/f7vyU/h8Ph4k4u2brmIB8CayaG7Jrz/v5e6roevEiZkh+cQ2DNhEfXHK8/A8PnYvgKgTUTHl1zvDrxUPKDrxBYAGQQWABkEFgAZBBYAGQQWDPBwU5MAbt4JjgqgCkgsGaCEhpMAbt3Js6V0FAWAwUEFkoplMVAA4GFf/BZFzIjsPAPymKQGYEFQAaBBUAGgQVABoEFQAaBhRNdD5d6HkLNMAfkw9PGia5HGzyPQGSYA/IhsHDiXBnPYrEoVVW5HjLNMAfkcx09AW9t20ZPIYX9fl+enp7Kz58/P/3TxovFotzf35fNZvO3jGeKc/DCPhsH77Bm4lzXHK9OONnmAG0E1kx07Zrj1QknyxygjcCaia4dbrw64WSZA7QRWABkEFgAZBBYAGQQWABkEFgYDeU2uBQ7A6Oh3AaXIrAwGsptcLE2iZubm7aUwmW4LLzGfX19be/v79vFYvHpWIvFoq2qqn19fU0xLvvMd595SzMbNpJmYN3f33cas6qqFOOyz7QD66ptc1Rt3t7elt+/f0dPQ4rl0V1dXbmMu1wuO51MXywW5XA4hI/LPrNLEhGlFD7DwoW8ym0o48FnCCwAMggsADIILAAyCCwAMgismfAqi1EbF9p42jPhVRajNi7ERR8EO+JAn++BvtfX17aqKpcT6Urjss84OIqJsXa3AcZCYOHEw8NDp0YQVVVJteKCPgILJ7zKYoBLEVg44VV3CFyKbwkByCCwAMggsADIILAAyCCwcIKyGGTFjsMJymKQFYGFE3S3QVrRtUFH57qkqF1e3WKyzXfIe8vWYYdx80kTWF27pKhdXt1isszX496ydNhh3HzSnHTvWg6ixqtbTJb5Wqh12GHcfNIElqUcRI1liTOsg9eW8Cr5YVzfcTPhQ3cAMggsADIILAAyCCwAMgisZKZa7mL9Vqrrz6t+28U69DPNV4ewqZa7dPmTy31+3jquGtbhP6IPgh2VBIc8vS6Lc91iss33nKZp2u12265WK9McVqtVu91u26ZpBh3Xa096jZthHTJJM3PrQ6zrevCHqBAAFmNsZrWSKq896TVuhnXIRPLgaF3X5eHh4ezP7Xa78vj4GH1r4Yf0rOtgmW/XDjtZWO4twwHPDOuQiWRgNU1Tlsvl2Z87HA7l+vo6+tbCN4d1HSzzjS4lsiKw7PPNRPJD9y5hZfm5qfNcB6Wwgj7JwAIwTwQWABkEFgAZBBYAGWkCy6tTS3SpS/Tvt85DbX1hp/zM0szcq1NLdKlL9O+3zkNtfWEn/cyiT64enStJueQP80eUumT7g/9TW9++l0WGcae8J/tIE1hRLql1+3/lQR8NWb6i3N3G61lkCBavcaP2ZNZwm31gHW23W9PmqOu689genXAUu9t4PYsMweI1bvSezNZhJ01pTjRr+UrX8qBSfMpXFLvbdOVZUmXZ7mqlOR57MluHHQLrA7UN6vXoMnRfybBmU94PGZ5xH2m+JQSAcwgsADIILAAyCCwAMgisD5TKV7KUV3h9S+jBc83Uutt47XX3eUdPIBOl8pUs5RUefx7Z608ue66ZWncbr73uLvogWCYK5StjnEC2zOdcVxcLr5PufddsyHXIdorfa697kwysDKUuqqUNXXi9oLwuS0nKlNdhDiQPjnp0aqmqqux2u8HnYB03gwxNEiy6dlGa+joIvpTNJAMrQ6mLamlDF2ovVEtJypTXQfClbCYZWJQ2+OKFyjpkxbeEAGQQWABkEFgAZBBYAGRIBlaGUhfV0oapzhnzILkzM5S6yJY2THTOmAfJwNpsNqWqqkHeCSwWi1JVVdlsNoPOoe+4GQy5vsCgoo/aZ5Kh3CZD2VGUvvV2XixzGLI8KNs6ZDKPu+woQycRtQ47Hqxdc7xY5mDpWKO2DplInnT3kqHcJkPZUTRr1xyvLWw56e5RHpRlHTIhsD7IUG6ToewoA7VnMeU5ZMKnqgBkEFgAZBBYAGQQWABkEFgfZCi3yVB2pCa6y47X+ip9szuWae9kowzlNhnKjtREd9nxWt8sHXZSiT4IlkmGTiJqHXa8WO5zyM49lmfhtb6cdP/aPO4Sg5b8jBGaGeag9izmgIOjM+HRacjC2j3I4wBtlg5GXs9iDi9lAmsmPEp+LKzlQR6BlaVEyetZzOGlTGDNRIYOMJatNuUSpSnfmze+JQQgg8ACIIPAAiCDwAIgg8DCaCzf0E25RGnK9+ZtHneJFCxnj6ZcojTle/NGYGE06/W67Ha7Tu+0MnRG8jLle3MXfdT+6ObmZtSSkSlcFpZxz3WA6Vvrdu7KVkKjJkPXJ28ElvBletCGcbt2gLF2del6qXX5ySJD1ydvaU66397elt+/f0dPQ4rl0Xl0gLF2dekqSwmNmgxdn7zxGRZOdG1XNXRbq6PImkdlXddNeX0JLAAyCCwAMggsADIILAAyCKyZ8OoAQ5lJHtFdfka5x+gJYBxeHWAoM8kjusvPKKIPgh1xcNT34KhXBxi6/OSRoeuTN8nAent7i55uinWAXVT3IK/rkn9oFMt4JE+6v729lW/fvkVPOXwdkjw6KdHdg7xYOwJ1XYcsnYaOCKxkCCxf0d2DvFjLbVTLePjQHbMyxbDqc1+qZTwEFgAZBBYAGQQWABkEFgAZBBZmRbksBQQWZka6LAUEFuZlyI41GN/kn9rV1VX4lcF+vy8PDw9luVx+Osflcll+/PhR9vv9oONaLq85fBz3+/fvf1uNtX9K00a5mqYp2+22rFar6K2gLbo26MirlrDrmJ6X1zpYeHVU6Tqu5fKaQ4ZuMV6dhqz7wWtcb5MvzcnwDseyxF6lOV6lGB6lLlMuM/HqNFSKbT9YXhdJIqKUMoP/EuIPr1IMj9KNKZeZeHUamgsCC4AMAguADAILgAwCC4AMAgsXie6aE/2tXyaWtVDtsJNrNpAT3TVnin/uuC/LWqh22CGwcJEhS10Wi0WpqqpsNpuzP3s4HMputyvr9Tp6CdJYr9d/T/Gfc+65WZ7FqKJPrh5x0t2+DhZe8/Xi1d1myDn07SwTtQ+zdsIxrV30BI4ILPs6WKgFlkfJj/XevEp+ovdjhhKlvijNGYFlib1Kc9RKMby621juzavkJ3pPZihR6j336AkAn8lQRqNU8uNxXxkRWABkEFgAZBBYAGQQWABkEFg4ofoN0tBUy1emNt9/5h49AeRDucsfquUrU5vvRwQWTlhKPKZMtnzlC2rz/VT0ydUjTrrb18Ei6t6zla9kYJnvarVq67pum6aJnnYKvMOCq/f391LXNUXKPT0/P/9tYQb+S4iR8LlYP3d3d9FTSIXAwiiUy0Ei8c7qXwQWABkEFgAZBBYAGQQWABkEFkaRoRwkwxws88gy30xYEYwiQzlIhjlY5pFlvpkQWHCVoRwkwxw+mlrJz6iij9ofeZXmqMlQmpOhHMRrvl6dcKLG9bqydtghsJLJEFh1XUcvg9t8vTrhRI/rdWXrsDP5rjlqMnTNaZom/IS113y9OuFEj+slW4cdPsPCieiw8pyvVyec6HG9RP/+/yKwAMggsADIILAAyCCwAMggsDArXmUx0eN6if79J/OJngAwJq+ymOhxvUT//v8isDArXmUxUeN6SVseFH1y9chywpvL96S7hVdJitd8MxhyzZqmabfbbbtardzKmTJJ87QJLM3A8ipJmXJgeazZdrs1rVmG8qs+JEtz8Ifl0VlKXSzjepWkeM03A481OxwO5fr6uvMcMpRf9cFnWLiIV0nKlHmsmTV8FMOqFAILgBACC4AMAguADAILgAwCayaiS0eyjJsBa9af7sxhEl06kmXcDFizC0QfBDvi4KjvwdHX19e2qiqXJglK42bAmvWX5uAoAJzDfwkByCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyCCwAMggsADIILAAyPgfua4A7AeOtswAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjItMDktMDZUMDE6MzM6MDErMDA6MDCmKlR4AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDIyLTA5LTA2VDAxOjMzOjAxKzAwOjAw13fsxAAAAABJRU5ErkJggg==" - ] - ); - - $boletoHtml = $boleto->renderHTML(); - + ]); $this->assertThat($boleto->toArray(), (new IsType(IsType::TYPE_ARRAY))); - $this->assertNotNull($boletoHtml); + $this->assertNotNull($boleto->renderHTML()); $this->assertNotNull($boleto->renderPDF()); } -} \ No newline at end of file +} diff --git a/tests/PessoaTest.php b/tests/PessoaTest.php index 1f1ad1fb..e7f30e51 100644 --- a/tests/PessoaTest.php +++ b/tests/PessoaTest.php @@ -2,15 +2,15 @@ namespace VinicciusGuedes\LaravelCnab\Tests; -use VinicciusGuedes\LaravelCnab\Pessoa; -use VinicciusGuedes\LaravelCnab\Util; use Exception; +use VinicciusGuedes\LaravelCnab\Util; +use VinicciusGuedes\LaravelCnab\Pessoa; use PHPUnit\Framework\Constraint\StringContains; class PessoaTest extends TestCase { - - public function testPessoaCriandoConstrutor(){ + public function testPessoaCriandoConstrutor() + { $nome = 'Cliente'; $endereco = 'Rua um, 123'; @@ -19,9 +19,9 @@ public function testPessoaCriandoConstrutor(){ $uf = 'UF'; $cidade = 'CIDADE'; $documento = '99999999999'; + $email = 'email@dominio.com'; - $pessoa = new Pessoa( - [ + $pessoa = new Pessoa([ 'nome' => $nome, 'endereco' => $endereco, 'bairro' => $bairro, @@ -29,8 +29,8 @@ public function testPessoaCriandoConstrutor(){ 'uf' => $uf, 'cidade' => $cidade, 'documento' => $documento, - ] - ); + 'email' => $email, + ]); $this->assertEquals($nome, $pessoa->getNome()); $this->assertEquals($endereco, $pessoa->getEndereco()); @@ -38,6 +38,7 @@ public function testPessoaCriandoConstrutor(){ $this->assertEquals(Util::maskString($cep, '#####-###'), $pessoa->getCep()); $this->assertEquals($uf, $pessoa->getUf()); $this->assertEquals($cidade, $pessoa->getCidade()); + $this->assertEquals($email, $pessoa->getEmail()); $this->assertEquals(Util::maskString($documento, '###.###.###-##'), $pessoa->getDocumento()); $this->assertEquals('CPF', $pessoa->getTipoDocumento()); @@ -65,18 +66,17 @@ public function testPessoaCriandoConstrutor(){ } - public function testPessoaDocumentoErrado(){ + public function testPessoaDocumentoErrado() + { $this->expectException(Exception::class); - $pessoa = new Pessoa( - [ + $pessoa = new Pessoa([ 'documento' => '99999', - ] - ); + ]); } - - public function testPessoaCriandoMetodoCreate(){ + public function testPessoaCriandoMetodoCreate() + { $nome = 'Cliente'; $endereco = 'Rua um, 123'; @@ -87,9 +87,9 @@ public function testPessoaCriandoMetodoCreate(){ $uf = 'UF'; $cidade = 'CIDADE'; $documento = '99999999999'; + $email = 'email@dominio.com'; - $pessoa = new Pessoa( - [ + $pessoa = new Pessoa([ 'nome' => $nome, 'endereco' => $endereco, 'numero' => $numero, @@ -99,10 +99,10 @@ public function testPessoaCriandoMetodoCreate(){ 'uf' => $uf, 'cidade' => $cidade, 'documento' => $documento, - ] - ); + 'email' => $email, + ]); - $pessoa2 = Pessoa::create($nome, $documento, $endereco, $numero, $complemento, $bairro, $cep, $cidade, $uf); + $pessoa2 = Pessoa::create($nome, $documento, $endereco, $numero, $complemento, $bairro, $cep, $cidade, $uf, $email); $pessoa_contrutor = new \ReflectionClass($pessoa); $pessoa_create = new \ReflectionClass($pessoa2); @@ -124,7 +124,8 @@ public function testPessoaCriandoMetodoCreate(){ } - public function testPessoaMascara(){ + public function testPessoaMascara() + { $pessoa = new Pessoa; @@ -150,4 +151,4 @@ public function testPessoaMascara(){ $this->assertEquals('99.99999.9-99', $pessoa->getDocumento()); } -} \ No newline at end of file +} diff --git a/tests/Remessa/RemessaCnab240Test.php b/tests/Remessa/RemessaCnab240Test.php index fe5c80e0..d98f1ee2 100644 --- a/tests/Remessa/RemessaCnab240Test.php +++ b/tests/Remessa/RemessaCnab240Test.php @@ -2,32 +2,29 @@ namespace VinicciusGuedes\LaravelCnab\Tests\Remessa; -use VinicciusGuedes\LaravelCnab\Boleto\Banco as Boleto; -use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab240\Cobranca\Banco as Remessa; use VinicciusGuedes\LaravelCnab\Pessoa; use VinicciusGuedes\LaravelCnab\Tests\TestCase; +use VinicciusGuedes\LaravelCnab\Boleto\Banco as Boleto; +use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab240\Cobranca\Banco as Remessa; class RemessaCnab240Test extends TestCase { - protected static $pagador; + protected static $beneficiario; public static function setUpBeforeClass() : void { - self::$beneficiario = new Pessoa( - [ + self::$beneficiario = new Pessoa([ 'nome' => 'ACME', 'endereco' => 'Rua um, 123', 'cep' => '99999-999', 'uf' => 'UF', 'cidade' => 'CIDADE', 'documento' => '99.999.999/9999-99', - ] - ); + ]); - self::$pagador = new Pessoa( - [ + self::$pagador = new Pessoa([ 'nome' => 'Cliente', 'endereco' => 'Rua um, 123', 'bairro' => 'Bairro', @@ -35,8 +32,7 @@ public static function setUpBeforeClass() : void 'uf' => 'UF', 'cidade' => 'CIDADE', 'documento' => '999.999.999-99', - ] - ); + ]); } public static function tearDownAfterClass() : void @@ -48,65 +44,65 @@ public static function tearDownAfterClass() : void ]; $files = glob(implode(DIRECTORY_SEPARATOR, $aFiles) . '/*'); // get all file names foreach($files as $file){ - if(is_file($file)) + if (is_file($file)) { @unlink($file); + } } } -// -// public function testRemessaSantanderCnab240(){ -// $boleto = new Boleto\Santander( -// [ -// 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', -// 'dataVencimento' => new \Carbon\Carbon(), -// 'valor' => 100, -// 'multa' => false, -// 'juros' => false, -// 'numero' => 1, -// 'numeroDocumento' => 1, -// 'pagador' => self::$pagador, -// 'beneficiario' => self::$beneficiario, -// 'diasBaixaAutomatica' => 15, -// 'carteira' => 101, -// 'agencia' => 1111, -// 'conta' => 99999999, -// 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], -// 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], -// 'aceite' => 'S', -// 'especieDoc' => 'DM', -// ] -// ); -// -// $remessa = new Remessa\Santander( -// [ -// 'agencia' => 1111, -// 'carteira' => 101, -// 'conta' => 99999999, -// 'codigoCliente' => 12345678, -// 'beneficiario' => self::$beneficiario, -// ] -// ); -// $remessa->addBoleto($boleto); -// -// $file = implode(DIRECTORY_SEPARATOR, [ -// __DIR__, -// 'files', -// 'cnab400', -// 'santander.txt' -// ]); -// -// $file2 = $remessa->save($file); -// -// $this->assertFileExists($file); -// $this->assertEquals($file, $file2); -// } - - public function testRemessaItauCnab240(){ + + public function testRemessaSantanderCnab240() + { + $boleto = new Boleto\Santander([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'diasBaixaAutomatica' => 15, + 'carteira' => 101, + 'agencia' => 1111, + 'conta' => 99999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + ]); + + $remessa = new Remessa\Santander([ + 'idremessa' => 1, + 'agencia' => 1111, + 'carteira' => 101, + 'conta' => 99999999, + 'codigoCliente' => 12345678, + 'beneficiario' => self::$beneficiario, + ]); + $remessa->addBoleto($boleto); + + $file = implode(DIRECTORY_SEPARATOR, [ + __DIR__, + 'files', + 'cnab400', + 'santander.txt' + ]); + + $file2 = $remessa->save($file); + + $this->assertFileExists($file); + $this->assertEquals($file, $file2); + } + + public function testRemessaItauCnab240() + { $boleto = new Boleto\Itau([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -133,7 +129,7 @@ public function testRemessaItauCnab240(){ __DIR__, 'files', 'cnab240', - 'itau.txt' + 'itau.txt', ]); $file2 = $remessa->save($file); @@ -141,4 +137,4 @@ public function testRemessaItauCnab240(){ $this->assertFileExists($file); $this->assertEquals($file, $file2); } -} \ No newline at end of file +} diff --git a/tests/Remessa/RemessaCnab400Test.php b/tests/Remessa/RemessaCnab400Test.php index f634feae..74037268 100644 --- a/tests/Remessa/RemessaCnab400Test.php +++ b/tests/Remessa/RemessaCnab400Test.php @@ -2,34 +2,31 @@ namespace VinicciusGuedes\LaravelCnab\Tests\Remessa; -use VinicciusGuedes\LaravelCnab\Boleto\Banco as Boleto; -use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco as Remessa; +use Exception; +use VinicciusGuedes\LaravelCnab\Util; use VinicciusGuedes\LaravelCnab\Pessoa; use VinicciusGuedes\LaravelCnab\Tests\TestCase; -use VinicciusGuedes\LaravelCnab\Util; -use Exception; +use VinicciusGuedes\LaravelCnab\Boleto\Banco as Boleto; +use VinicciusGuedes\LaravelCnab\Cnab\Remessa\Cnab400\Cobranca\Banco as Remessa; class RemessaCnab400Test extends TestCase { - protected static $pagador; + protected static $beneficiario; public static function setUpBeforeClass() : void { - self::$beneficiario = new Pessoa( - [ + self::$beneficiario = new Pessoa([ 'nome' => 'ACME', 'endereco' => 'Rua um, 123', 'cep' => '99999-999', 'uf' => 'UF', 'cidade' => 'CIDADE', 'documento' => '99.999.999/9999-99', - ] - ); + ]); - self::$pagador = new Pessoa( - [ + self::$pagador = new Pessoa([ 'nome' => 'Cliente', 'endereco' => 'Rua um, 123', 'bairro' => 'Bairro', @@ -37,8 +34,7 @@ public static function setUpBeforeClass() : void 'uf' => 'UF', 'cidade' => 'CIDADE', 'documento' => '999.999.999-99', - ] - ); + ]); } public static function tearDownAfterClass() : void @@ -50,12 +46,14 @@ public static function tearDownAfterClass() : void ]; $files = glob(implode(DIRECTORY_SEPARATOR, $aFiles) . '/*'); // get all file names foreach($files as $file){ - if(is_file($file)) + if (is_file($file)) { @unlink($file); + } } } - public function testRemessaCamposInvalidos(){ + public function testRemessaCamposInvalidos() + { $this->expectException(Exception::class); $remessa = new Remessa\Banrisul([ 'codigoCliente' => 11112222222, @@ -64,7 +62,8 @@ public function testRemessaCamposInvalidos(){ $remessa->gerar(); } - public function testRemessaCarteiraIndisponivel(){ + public function testRemessaCarteiraIndisponivel() + { $this->expectException(Exception::class); $remessa = new Remessa\Banrisul([ 'agencia' => 1111, @@ -76,14 +75,14 @@ public function testRemessaCarteiraIndisponivel(){ $remessa->gerar(); } - public function testRemessaAddboletosCnab400(){ - $boleto = new Boleto\Banrisul( - [ + public function testRemessaAddboletosCnab400() + { + $boleto = new Boleto\Banrisul([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 20, 'numeroDocumento' => 1, @@ -96,34 +95,30 @@ public function testRemessaAddboletosCnab400(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); $boleto2 = $boleto; $boleto2->setNumeroDocumento(2); - $remessa = new Remessa\Banrisul( - [ + $remessa = new Remessa\Banrisul([ 'agencia' => 1111, 'conta' => 22222, 'carteira' => 1, 'codigoCliente' => 11112222222, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoletos([$boleto, $boleto2]); $this->assertEquals(4, count(Util::file2array($remessa->gerar()))); } public function testRemessaBanrisulCnab400() { - $boleto = new Boleto\Banrisul( - [ + $boleto = new Boleto\Banrisul([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '041.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 20, 'numeroDocumento' => 1, @@ -136,24 +131,21 @@ public function testRemessaBanrisulCnab400() 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); - $remessa = new Remessa\Banrisul( - [ + ]); + $remessa = new Remessa\Banrisul([ 'agencia' => 1111, 'conta' => 22222, 'carteira' => 1, 'codigoCliente' => 11112222222, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'banrisul.txt' + 'banrisul.txt', ]); $file2 = $remessa->save($file); @@ -161,14 +153,14 @@ public function testRemessaBanrisulCnab400() $this->assertEquals($file, $file2); } - public function testRemessaBBCnab400(){ - $boleto = new Boleto\Bb( - [ + public function testRemessaBBCnab400() + { + $boleto = new Boleto\Bb([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -179,25 +171,22 @@ public function testRemessaBBCnab400(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Bb( - [ + $remessa = new Remessa\Bb([ 'agencia' => 1111, 'carteira' => 11, 'conta' => 999999999, 'convenio' => 1234567, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'bb.txt' + 'bb.txt', ]); $file2 = $remessa->save($file); @@ -206,14 +195,14 @@ public function testRemessaBBCnab400(){ $this->assertEquals($file, $file2); } - public function testRemessaBBCnab400Extendida(){ - $boleto = new Boleto\Bb( - [ + public function testRemessaBBCnab400Extendida() + { + $boleto = new Boleto\Bb([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '001.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -224,33 +213,30 @@ public function testRemessaBBCnab400Extendida(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - 'chaveNfe' => '12345678901234567890123456789012345678901234' - ] - ); + 'chaveNfe' => '12345678901234567890123456789012345678901234', + ]); - $remessa = new Remessa\Bb( - [ + $remessa = new Remessa\Bb([ 'agencia' => 1111, 'carteira' => 11, 'conta' => 999999999, 'convenio' => 1234567, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $cnab = explode($remessa->getFimLinha(), $remessa->gerar()); $this->assertEquals(444, strlen($cnab[1])); } - public function testRemessaBradescoCnab400(){ - $boleto = new Boleto\Bradesco( - [ + public function testRemessaBradescoCnab400() + { + $boleto = new Boleto\Bradesco([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 2, 'numeroDocumento' => 1, @@ -263,11 +249,9 @@ public function testRemessaBradescoCnab400(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Bradesco( - [ + $remessa = new Remessa\Bradesco([ 'idRemessa' => 1, 'agencia' => 1111, 'carteira' => '09', @@ -275,15 +259,14 @@ public function testRemessaBradescoCnab400(){ 'contaDv' => 9, 'codigoCliente' => 12345678901234567890, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'bradesco.txt' + 'bradesco.txt', ]); $file2 = $remessa->save($file); @@ -292,14 +275,14 @@ public function testRemessaBradescoCnab400(){ $this->assertEquals($file, $file2); } - public function testRemessaBradescoCnab400Extendida(){ - $boleto = new Boleto\Bradesco( - [ + public function testRemessaBradescoCnab400Extendida() + { + $boleto = new Boleto\Bradesco([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '237.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'diasBaixaAutomatica' => 2, 'numeroDocumento' => 1, @@ -312,12 +295,10 @@ public function testRemessaBradescoCnab400Extendida(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - 'chaveNfe' => '12345678901234567890123456789012345678901234' - ] - ); + 'chaveNfe' => '12345678901234567890123456789012345678901234', + ]); - $remessa = new Remessa\Bradesco( - [ + $remessa = new Remessa\Bradesco([ 'idRemessa' => 1, 'agencia' => 1111, 'carteira' => '09', @@ -325,22 +306,21 @@ public function testRemessaBradescoCnab400Extendida(){ 'contaDv' => 9, 'codigoCliente' => 12345678901234567890, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $cnab = explode($remessa->getFimLinha(), $remessa->gerar()); $this->assertEquals(444, strlen($cnab[1])); } - public function testRemessaCaixaCnab400(){ - $boleto = new Boleto\Caixa( - [ + public function testRemessaCaixaCnab400() + { + $boleto = new Boleto\Caixa([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '104.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100.41, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -354,26 +334,23 @@ public function testRemessaCaixaCnab400(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Caixa( - [ + $remessa = new Remessa\Caixa([ 'agencia' => 1111, 'conta' => 123456, 'idremessa' => 1, 'carteira' => 'RG', 'codigoCliente' => 999999, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'caixa.txt' + 'caixa.txt', ]); $file2 = $remessa->save($file); @@ -382,14 +359,14 @@ public function testRemessaCaixaCnab400(){ $this->assertEquals($file, $file2); } - public function testRemessaHSBCCnab400(){ - $boleto = new Boleto\Hsbc( - [ + public function testRemessaHSBCCnab400() + { + $boleto = new Boleto\Hsbc([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '399.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -403,25 +380,22 @@ public function testRemessaHSBCCnab400(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Hsbc( - [ + $remessa = new Remessa\Hsbc([ 'agencia' => 1111, 'carteira' => 'CSB', 'conta' => 999999, 'contaDv' => 9, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'hsbc.txt' + 'hsbc.txt', ]); $file2 = $remessa->save($file); @@ -430,14 +404,14 @@ public function testRemessaHSBCCnab400(){ $this->assertEquals($file, $file2); } - public function testRemessaItauCnab400(){ - $boleto = new Boleto\Itau( - [ + public function testRemessaItauCnab400() + { + $boleto = new Boleto\Itau([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '341.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -450,25 +424,22 @@ public function testRemessaItauCnab400(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Itau( - [ + $remessa = new Remessa\Itau([ 'agencia' => 1111, 'conta' => 99999, 'contaDv' => 9, 'carteira' => 112, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'itau.txt' + 'itau.txt', ]); $file2 = $remessa->save($file); @@ -477,14 +448,14 @@ public function testRemessaItauCnab400(){ $this->assertEquals($file, $file2); } - public function testRemessaSantanderCnab400(){ - $boleto = new Boleto\Santander( - [ + public function testRemessaSantanderCnab400() + { + $boleto = new Boleto\Santander([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '033.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -497,25 +468,22 @@ public function testRemessaSantanderCnab400(){ 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Santander( - [ + $remessa = new Remessa\Santander([ 'agencia' => 1111, 'carteira' => 101, 'conta' => 99999999, 'codigoCliente' => 12345678, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'santander.txt' + 'santander.txt', ]); $file2 = $remessa->save($file); @@ -526,13 +494,12 @@ public function testRemessaSantanderCnab400(){ public function testRemessaSicrediCnab400() { - $boleto = new Boleto\Sicredi( - [ + $boleto = new Boleto\Sicredi([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '748.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -546,25 +513,22 @@ public function testRemessaSicrediCnab400() 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Sicredi( - [ + $remessa = new Remessa\Sicredi([ 'agencia' => 2606, 'carteira' => '1', 'conta' => 12510, 'idremessa' => 1, 'beneficiario' => self::$beneficiario, - ] - ); + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'sicredi.txt' + 'sicredi.txt', ]); $file2 = $remessa->save($file); @@ -575,13 +539,12 @@ public function testRemessaSicrediCnab400() public function testRemessaBancoobCnab400() { - $boleto = new Boleto\Bancoob( - [ + $boleto = new Boleto\Bancoob([ 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '748.png', - 'dataVencimento' => new \Carbon\Carbon(), - 'valor' => 100, - 'multa' => false, - 'juros' => false, + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), 'numero' => 1, 'numeroDocumento' => 1, 'pagador' => self::$pagador, @@ -595,25 +558,69 @@ public function testRemessaBancoobCnab400() 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], 'aceite' => 'S', 'especieDoc' => 'DM', - ] - ); + ]); - $remessa = new Remessa\Bancoob( - [ + $remessa = new Remessa\Bancoob([ 'agencia' => 2606, 'carteira' => '1', 'conta' => 12510, 'convenio' => 123123, 'beneficiario' => self::$beneficiario, - ] - ); + ]); + $remessa->addBoleto($boleto); + + $file = implode(DIRECTORY_SEPARATOR, [ + __DIR__, + 'files', + 'cnab400', + 'bancoob.txt', + ]); + + $file2 = $remessa->save($file); + + $this->assertFileExists($file); + $this->assertEquals($file, $file2); + } + + public function testRemessaPineCnab400() + { + $boleto = new Boleto\Pine([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '643.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => '112', + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234', + 'modalidadeCarteira' => '1', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', + ]); + + $remessa = new Remessa\Pine([ + 'agencia' => '0001', + 'conta' => '1234', + 'contaDv' => 9, + 'carteira' => 112, + 'beneficiario' => self::$beneficiario, + 'codigoCliente' => '1234', + ]); $remessa->addBoleto($boleto); $file = implode(DIRECTORY_SEPARATOR, [ __DIR__, 'files', 'cnab400', - 'bancoob.txt' + 'pine.txt', ]); $file2 = $remessa->save($file); @@ -621,4 +628,179 @@ public function testRemessaBancoobCnab400() $this->assertFileExists($file); $this->assertEquals($file, $file2); } -} \ No newline at end of file + + public function testRemessaFibraCnab400() + { + $boleto = new Boleto\Fibra([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '224.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'range' => 0, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'modalidadeCarteira' => 'D', + 'carteira' => 112, + 'agencia' => '0001', + 'codigoCliente' => '12345', + 'conta' => '1234567', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', + ]); + + $remessa = new Remessa\Fibra([ + 'agencia' => '0001', + 'conta' => '1234567', + 'contaDv' => 9, + 'carteira' => 112, + 'beneficiario' => self::$beneficiario, + 'codigoCliente' => '12345', + ]); + $remessa->addBoleto($boleto); + + $file = implode(DIRECTORY_SEPARATOR, [ + __DIR__, + 'files', + 'cnab400', + 'fibra.txt', + ]); + + $file2 = $remessa->save($file); + + $this->assertFileExists($file); + $this->assertEquals($file, $file2); + } + + public function testRemessaOurinvestCnab400() + { + $boleto = new Boleto\Ourinvest([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '712.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 2, + 'numeroDocumento' => 2, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => '19', + 'agencia' => 0001, + 'conta' => 9999999, + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'S', + 'especieDoc' => 'DM', + 'chaveNfe' => '12345678901234567890123456789012345678901234', + ]); + + $remessa = new Remessa\Ourinvest([ + 'idRemessa' => 1, + 'agencia' => 1111, + 'carteira' => '19', + 'conta' => 1234567, + 'contaDv' => 9, + 'beneficiario' => self::$beneficiario, + ]); + $remessa->addBoleto($boleto); + + $file = implode(DIRECTORY_SEPARATOR, [ + __DIR__, + 'files', + 'cnab400', + 'ourinvest.txt', + ]); + + $file2 = $remessa->save($file); + + $this->assertFileExists($file2); + } + + public function testRemessaRendimentoCnab400() + { + $boleto = new Boleto\Rendimento([ + 'logo' => realpath(__DIR__ . '/../../logos/') . DIRECTORY_SEPARATOR . '633.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 2, + 'numeroDocumento' => 2, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'carteira' => '121', + 'agencia' => '0001', + 'codigoCliente' => '5447390', + 'conta' => '1234', + 'modalidadeCarteira' => '6', + 'descricaoDemonstrativo' => ['demonstrativo 1', 'demonstrativo 2', 'demonstrativo 3'], + 'instrucoes' => ['instrucao 1', 'instrucao 2', 'instrucao 3'], + 'aceite' => 'N', + 'especieDoc' => 'DM', + ]); + + $remessa = new Remessa\Rendimento([ + 'agencia' => '0001', + 'conta' => '1234', + 'contaDv' => 9, + 'carteira' => 121, + 'codigoCliente' => '5447390', + 'beneficiario' => self::$beneficiario, + ]); + $remessa->addBoleto($boleto); + + $file = implode(DIRECTORY_SEPARATOR, [ + __DIR__, + 'files', + 'cnab400', + 'rendimento.txt', + ]); + + $file2 = $remessa->save($file); + + $this->assertFileExists($file2); +} + + public function testRemessaInterCnab400() + { + $boleto = new Boleto\Inter([ + 'logo' => realpath(__DIR__ . '/../logos/') . DIRECTORY_SEPARATOR . '077.png', + 'dataVencimento' => $this->vencimento(), + 'valor' => $this->valor(), + 'multa' => $this->multa(), + 'juros' => $this->juros(), + 'numero' => 1, + 'numeroDocumento' => 1, + 'pagador' => self::$pagador, + 'beneficiario' => self::$beneficiario, + 'conta' => '123456789', + 'operacao' => '1234567', + 'aceite' => 'S', + 'especieDoc' => 'DM', + ]); + + $remessa = new Remessa\Inter([ + 'idRemessa' => 1, + 'agencia' => '0001', + 'conta' => '123456789', + 'carteira' => 112, + 'beneficiario' => self::$beneficiario, + ]); + $remessa->addBoleto($boleto); + + $file = implode(DIRECTORY_SEPARATOR, [ + __DIR__, + 'files', + 'cnab400', + 'inter.txt', + ]); + + $file2 = $remessa->save($file); + + $this->assertFileExists($file2); + } +} diff --git a/tests/Retorno/FactoryTest.php b/tests/Retorno/FactoryTest.php index c45e9ff0..9733ce6c 100644 --- a/tests/Retorno/FactoryTest.php +++ b/tests/Retorno/FactoryTest.php @@ -2,32 +2,34 @@ namespace VinicciusGuedes\LaravelCnab\Tests\Retorno; -use VinicciusGuedes\LaravelCnab\Cnab\Retorno\Cnab400\Detalhe; -use VinicciusGuedes\LaravelCnab\Tests\TestCase; use Exception; -use Illuminate\Support\Collection; +use VinicciusGuedes\LaravelCnab\Tests\TestCase; class FactoryTest extends TestCase { - public function testCriarEmBranco(){ + public function testCriarEmBranco() + { $this->expectException(Exception::class); $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(''); $retorno->processar(); } - public function testCriarComRemessa(){ + public function testCriarComRemessa() + { $this->expectException(Exception::class); $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/remessa.txt'); $retorno->processar(); } - public function testCriarComPathQueNaoExiste(){ + public function testCriarComPathQueNaoExiste() + { $this->expectException(Exception::class); $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/naoexiste.txt'); $retorno->processar(); } - public function testCriarComRetornoBancoNaoExiste(){ + public function testCriarComRetornoBancoNaoExiste() + { $this->expectException(Exception::class); $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/retorno_banco_fake.ret'); $retorno->processar(); @@ -46,4 +48,4 @@ public function testCriarComString() $retorno->processar(); $this->assertTrue(true); } -} \ No newline at end of file +} diff --git a/tests/Retorno/RetornoCnab240Test.php b/tests/Retorno/RetornoCnab240Test.php index 75729c39..9c3cf5f4 100644 --- a/tests/Retorno/RetornoCnab240Test.php +++ b/tests/Retorno/RetornoCnab240Test.php @@ -1,13 +1,10 @@ assertArrayHasKey('numeroDocumento', $detalhe->toArray()); } } - -} \ No newline at end of file +} diff --git a/tests/Retorno/RetornoCnab400Test.php b/tests/Retorno/RetornoCnab400Test.php index 2115281a..0ed3e091 100644 --- a/tests/Retorno/RetornoCnab400Test.php +++ b/tests/Retorno/RetornoCnab400Test.php @@ -1,32 +1,35 @@ expectException(Exception::class); new Bradesco([]); } - public function testRetornoBancoInvalido(){ + public function testRetornoBancoInvalido() + { $this->expectException(Exception::class); new Bradesco(__DIR__ . '/files/cnab400/retorno_banco_fake.ret'); } - public function testRetornoServicoInvalido(){ + public function testRetornoServicoInvalido() + { $this->expectException(Exception::class); new Bradesco(__DIR__ . '/files/cnab400/retorno_banco_fake_2.ret'); } - public function testRetornoSeekableIterator(){ + public function testRetornoSeekableIterator() + { $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/bradesco.ret'); $retorno->processar(); $retorno->rewind(); @@ -43,7 +46,8 @@ public function testRetornoSeekableIterator(){ $retorno->seek(100); } - public function testRetornoToArray(){ + public function testRetornoToArray() + { $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/bradesco.ret'); $retorno->processar(); @@ -54,7 +58,8 @@ public function testRetornoToArray(){ $this->assertArrayHasKey('detalhes', $array); } - public function testRetornoOcorrencia(){ + public function testRetornoOcorrencia() + { $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/bradesco.ret'); $retorno->processar(); @@ -222,4 +227,202 @@ public function testRetornoSicrediCnab400() } } -} \ No newline at end of file + public function testRetornoBanrisulCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/banrisul.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Banco do Estado do Rio Grande do Sul S.A.', $retorno->getBancoNome()); + $this->assertEquals('041', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoBbCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/bb.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Banco do Brasil S.A.', $retorno->getBancoNome()); + $this->assertEquals('001', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoBnbCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/bnb.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Banco do Nordeste do Brasil S.A.', $retorno->getBancoNome()); + $this->assertEquals('004', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoDellbankCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/delbank.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Delcred SCD S.A', $retorno->getBancoNome()); + $this->assertEquals('435', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoFibraCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/fibra.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Banco Fibra S.A.', $retorno->getBancoNome()); + $this->assertEquals('224', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoInterCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/inter.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Banco Inter S.A.', $retorno->getBancoNome()); + $this->assertEquals('077', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoPineCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/pine.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Banco Pine S.A.', $retorno->getBancoNome()); + $this->assertEquals('643', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoOurinvestCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/ourinvest.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertEquals('Banco Ourinvest', $retorno->getBancoNome()); + $this->assertEquals('712', $retorno->getCodigoBanco()); + + $this->assertInstanceOf(Collection::class, $retorno->getDetalhes()); + $this->assertInstanceOf(Detalhe::class, $retorno->getDetalhe(1)); + + foreach ($retorno->getDetalhes() as $detalhe) { + $this->assertInstanceOf(Detalhe::class, $detalhe); + $this->assertArrayHasKey('numeroDocumento', $detalhe->toArray()); + } + } + + public function testRetornoPixCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/santander_pix.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertCount(1, $retorno->getDetalhes()); + + $this->assertNotNull($retorno->current()->getId()); + $this->assertNotNull($retorno->current()->getPixLocation()); + } + + public function testRetornoSemPixCnab400() + { + $retorno = \VinicciusGuedes\LaravelCnab\Cnab\Retorno\Factory::make(__DIR__ . '/files/cnab400/santander.ret'); + $retorno->processar(); + + $this->assertNotNull($retorno->getHeader()); + $this->assertNotNull($retorno->getDetalhes()); + $this->assertNotNull($retorno->getTrailer()); + + $this->assertCount(1, $retorno->getDetalhes()); + + $this->assertNull($retorno->current()->getId()); + $this->assertNull($retorno->current()->getPixChave()); + $this->assertNull($retorno->current()->getPixChaveTipo()); + } +} diff --git a/tests/Retorno/files/cnab240/btg.ret b/tests/Retorno/files/cnab240/btg.ret new file mode 100644 index 00000000..28981d3c --- /dev/null +++ b/tests/Retorno/files/cnab240/btg.ret @@ -0,0 +1,8 @@ +20800000 230306294000145006375766049310430530000100000001100983 EMPRESA CEDENTE BANCO BTG PACTUAL 21506202113034700001410301600 +20800001T01 020 2030306294000145006375766049310430530000100000001100983 EMPRESA CEDENTE 15062021 +2080001300001T 020000100000001100783 000000000000000002681196/1-1 150620210000000000800002080000100000695800000001285 09052843212000818 EMPRESA SACADO EXEMPLO 00000000000000000000000 0000000000 +2080001300002U 020000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000 15062021 000015062021000000000000000 000 +2080001300003T 060000100000001100783 000000000000000002681196/1-1 150620210000000000800002080000100000695800000001285 09052843212000818 EMPRESA SACADO EXEMPLO 00000000000000000000000 0000000000 +2080001300004U 060000000000000000000000000000000000000000800000000000000000000000000000800000000000000800000000000000000000000000000000 1506202115062021000015062021000000000080000 000 +20800015 000001000001000000000080000 000000000000000000000 00000000000000000000000000000000000000000000 00000000 +20899999 000001000001000000 diff --git a/tests/Retorno/files/cnab400/banrisul.ret b/tests/Retorno/files/cnab400/banrisul.ret new file mode 100644 index 00000000..499e3869 --- /dev/null +++ b/tests/Retorno/files/cnab400/banrisul.ret @@ -0,0 +1,3 @@ +02RETORNO00000000000000000 00110000000 ACME041000000000000000241116000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +1000000000000000000111122222220000000 1 100000000000000000000000000000000000002241116 10000000000000000000024111600000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002 +9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003 \ No newline at end of file diff --git a/tests/Retorno/files/cnab400/bb.ret b/tests/Retorno/files/cnab400/bb.ret new file mode 100644 index 00000000..9bd16f21 --- /dev/null +++ b/tests/Retorno/files/cnab400/bb.ret @@ -0,0 +1,3 @@ +02RETORNO0000000000000000011118999999994000000000000000000000000000000000000001000000000000000201016000000000000000000000000000000000000000000000000012345670000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +70000000000000000000000000000000000000000000000000000000000000012345670000000001000000000000000000000000000002201016 10000000000000000000020101600000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002 +9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003 \ No newline at end of file diff --git a/tests/Retorno/files/cnab400/bnb.ret b/tests/Retorno/files/cnab400/bnb.ret new file mode 100644 index 00000000..d8c39276 --- /dev/null +++ b/tests/Retorno/files/cnab400/bnb.ret @@ -0,0 +1,12 @@ +02RETORNO01COBRANCA 99990000009999 ACME 004B.DO NORDESTE 07031701600BPI00194 000000 000001 +1029999999999999999990000009999 099087140000000000 40207031712530/01 09908714 28031700000000442810040044 0100000000002460000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000002 +1029999999999999999990000009999 099087060000000000 40207031712526/01 09908706 05041700000001696560040044 0100000000002460000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000003 +1029999999999999999990000009999 099087220000000000 40207031712540/01 09908722 28031700000000399110040044 0100000000002460000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000004 +1029999999999999999990000009999 099079800000000000 40607031712285/01 09907980 07031700000002345250040044 0100000000000000000000000000000000000000000000000000000000000000000000000000000000000002345250000000000000000000000000000008031700000000000000000000000000000000000000000000000000000000 000005 +1029999999999999999990000009999 099080210000000000 40607031712292/01 09908021 07031700000001234030040044 0100000000000000000000000000000000000000000000000000000000000000000000000000000000000001234030000000000000000000000000000008031700000000000000000000000000000000000000000000000000000000 000006 +1029999999999999999990000009999 099080050000000000 40607031712283/01 09908005 07031700000002370590049999 0100000000000000000000000000000000000000000000000000000000000000000000000000000000000002370590000000000000000000000000000008031700000000000000000000000000000000000000000000000000000000 000007 +1029999999999999999990000009999 099079980000000000 40607031712284/01 09907998 07031700000001423140040044 0100000000000000000000000000000000000000000000000000000000000000000000000000000000000001423140000000000000000000000000000008031700000000000000000000000000000000000000000000000000000000 000008 +1029999999999999999990000009999 099079630000000000 40607031712287/01 09907963 07031700000003951640040237 0100000000000000000000000000000000000000000000000000000000000000000000000000000000000003951640000000000000000000000000000008031700000000000000000000000000000000000000000000000000000000 000009 +1029999999999999999990000009999 099080130000000000 40607031712293/01 09908013 07031700000000506870040044 0100000000000000000000000000000000000000000000000000000000000000000000000000000000000000506870000000000000000000000000000008031700000000000000000000000000000000000000000000000000000000 000010 +1029999999999999999990000009999 099079710000000001 50607031712286/01 09907971 07031700000004723640040044 0100000000000000000000000000000000000000000000000000000000000000000000000000000000000004723640000000000000000000000000000008031700000000000000000000000000000000000000000000000000000000 000011 +9201004 000000000000021743847400000193 000012 diff --git a/tests/Retorno/files/cnab400/delbank.ret b/tests/Retorno/files/cnab400/delbank.ret new file mode 100644 index 00000000..218ff0a8 --- /dev/null +++ b/tests/Retorno/files/cnab400/delbank.ret @@ -0,0 +1,3 @@ +02RETORNO01COBRANCA 10138DELCREDFUNDOLTDDEL CRED NP FUNDO DE INVESTIME435BANCO DELCRED 24052201600BPI02526 000001 +1021146819200018110138DELCREDFUNDOLTD 00000196289 112 102240522TESTE123 100622000000010000043500019010000000000150 000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000240522000000002 +920143500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000003 diff --git a/tests/Retorno/files/cnab400/fibra.ret b/tests/Retorno/files/cnab400/fibra.ret new file mode 100644 index 00000000..5d9ff4a9 --- /dev/null +++ b/tests/Retorno/files/cnab400/fibra.ret @@ -0,0 +1,13 @@ +02RETORNO01COBRANCA 000000000000 123456 LTDA 224BANCO FIBRA S.A16012301600BPI00030160123 000001 +10226589893000146000000000000 00113365383 112 20613012311482 130123000000585900034172070010000000000000 000000000000000000000000000000000000000000000585900000000000000000000000000000 100000000160123000000002 +10226589893000146000000000000 00113365557 112 20613012311693-4 120123000000020742803307020010000000000000 000000000000000000000000000000000000000000000020777300000000003450000000000000 100000000160123000000003 +10226589893000146000000000000 00113583431 112 20613012311937-1 130123000000207067634137880010000000000000 000000000000000000000000000000000000000000000207067600000000000000000000000000 100000000160123000000004 +10226589893000146000000000000 00113583464 112 20613012311941-1 130123000000117055034137880010000000000000 000000000000000000000000000000000000000000000117055000000000000000000000000000 100000000160123000000005 +10226589893000146000000000000 00113583803 112 20613012311870-1 130123000000023544034148330010000000000000 000000000000000000000000000000000000000000000023544000000000000000000000000000 100000000160123000000006 +10226589893000146000000000000 00114045208 112 20113012312489-1 080223000000213246022400010010000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000130123000000007 +10226589893000146000000000000 00114045208 112 20213012312489-1 080223000000213246022400010010000000000450 000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000130123000000008 +10226589893000146000000000000 00114045216 112 20113012312489-2 150323000000213246022400010010000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000130123000000009 +10226589893000146000000000000 00114045216 112 20213012312489-2 150323000000213246022400010010000000000450 000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000130123000000010 +10226589893000146000000000000 00114045224 112 20113012312489-3 120423000000213246022400010010000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000130123000000011 +10226589893000146000000000000 00114045224 112 20213012312489-3 120423000000213246022400010010000000000450 000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000130123000000012 +920122400000000000000000000000000000000 0000000000000000000000 0000000000000000000000 0000000000011 000013 \ No newline at end of file diff --git a/tests/Retorno/files/cnab400/inter.ret b/tests/Retorno/files/cnab400/inter.ret new file mode 100644 index 00000000..0136e1f0 --- /dev/null +++ b/tests/Retorno/files/cnab400/inter.ret @@ -0,0 +1,3 @@ +02RETORNO01COBRANCA 000000000000000000000000000000077INTER 061221 000001 +10 11200010100000000 0 00000000000 112020612210000000001000000000000712210000000001000077000101 00000000000000 00000000000000 000002 +9201077 00000001 00001000000000000 00000 00000000000000000 000003 \ No newline at end of file diff --git a/tests/Retorno/files/cnab400/ourinvest.ret b/tests/Retorno/files/cnab400/ourinvest.ret new file mode 100644 index 00000000..25378de1 --- /dev/null +++ b/tests/Retorno/files/cnab400/ourinvest.ret @@ -0,0 +1,3 @@ +02RETORNO0000000000000000000000000000001234567000000000000000000000000000000712000000000000000300423000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +10000000000000000000000001111123456790000000000000000000000000000000000000000000280000000000000000000000000002300423 20000000000000000000030042300000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002 +9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003 \ No newline at end of file diff --git a/tests/Retorno/files/cnab400/pine.ret b/tests/Retorno/files/cnab400/pine.ret new file mode 100644 index 00000000..cb2bf3fd --- /dev/null +++ b/tests/Retorno/files/cnab400/pine.ret @@ -0,0 +1,7 @@ +02RETORNO01COBRANCA 00000000 123456 LTDA 643BANCO PINE 16012301600BPI00029 000001 +1022658989300014600000000 01044552172 112 3061301231156601 130123000000116429834189490010000000000000 000000000000000000000000000000000000000000000116429800000000000000000000000000 100000000130123000000002 +1022658989300014600000000 01044572279 112 3061301231164801 160123000000181395900134090010000000000000 000000000000000000000000000000000000000000000181395900000000000000000000000000 100000000130123000000003 +1022658989300014600000000 01044572386 112 3061301231166203 180123000000032531210437290010000000000000 000000000000000000000000000000000000000000000032531200000000000000000000000000 100000000130123000000004 +1022658989300014600000000 01044772069 112 3061301231212501 020123000000391149023733890010000000000000 000000000000000000000000000000000000000000000406142800000001499380000000000000 100000000130123000000005 +1022658989300014600000000 01044786531 112 3061301231224501 090123000000410706423733890010000000000000 000000000000000000000000000000000000000000000421658500000001095210000000000000 100000000130123000000006 +920164300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000007 diff --git a/tests/Retorno/files/cnab400/santander_pix.ret b/tests/Retorno/files/cnab400/santander_pix.ret new file mode 100644 index 00000000..00ef7a3d --- /dev/null +++ b/tests/Retorno/files/cnab400/santander_pix.ret @@ -0,0 +1,4 @@ +02RETORNO0000000000000000011110000000009999999000000000000000000000000000000033000000000000000201016000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 +10000000000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000002201016 10000000000000000000020101600000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000099000000000000002 +25 39a1178e-db6b-4407-bc7b-b674390acf5f id-da-transcao-pix 000003 +9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004 \ No newline at end of file diff --git a/tests/TestCase.php b/tests/TestCase.php index 6c0358f3..8472f5c9 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,39 @@ addDays(rand(0, 365)); +} + + protected function valor() + { + return mt_rand(100, 30000); + } + + protected function multa() + { + // sem multa, decimal entre 1 e 10 + $aValues = [false, (mt_rand(10, 10 * 10) / 10)]; + return $aValues[rand() & 1]; + } + + protected function juros() + { + // sem multa, decimal entre 1 e 10 + $aValues = [false, (mt_rand(10, 10 * 10) / 10)]; + return $aValues[rand() & 1]; + } +} diff --git a/tests/UtilTest.php b/tests/UtilTest.php index 69b08eaa..ea62c500 100644 --- a/tests/UtilTest.php +++ b/tests/UtilTest.php @@ -2,20 +2,23 @@ namespace VinicciusGuedes\LaravelCnab\Tests; +use VinicciusGuedes\LaravelCnab\Boleto\AbstractBoleto; use VinicciusGuedes\LaravelCnab\Pessoa; -use VinicciusGuedes\LaravelCnab\Util; use Exception; +use VinicciusGuedes\LaravelCnab\Util; +use Illuminate\Support\Arr; class UtilTest extends TestCase { - - public function testIsHeaderRetorno(){ + public function testIsHeaderRetorno() + { $this->assertFalse(Util::isHeaderRetorno('')); $this->assertFalse(Util::isHeaderRetorno(str_pad('', 400, ' '))); $this->assertFalse(Util::isHeaderRetorno(str_pad('', 240, ' '))); } - public function testFuncoesString(){ + public function testFuncoesString() + { $this->assertEquals('ASD', Util::upper('asd')); $this->assertEquals('asd', Util::lower('ASD')); $this->assertEquals('Asd', Util::upFirst('asd')); @@ -32,50 +35,58 @@ public function testFuncoesString(){ $this->assertEquals('AaEeIiOoUu', Util::normalizeChars('ÁáÉéÍiÓóÚú')); } - public function testModulos(){ + public function testModulos() + { $this->assertEquals(7, Util::modulo11('123456789', 2, 9)); $this->assertEquals(4, Util::modulo11('123456789', 2, 9, 1)); $this->assertEquals(7, Util::modulo10('123456789')); } - public function testAddRem() { + public function testAddRem() + { $array = array_fill(0, 400, 0); Util::adiciona($array, 1, 10, '1234567890'); $this->assertEquals(sprintf('%-0400s', '1234567890'), implode('', $array)); $this->assertEquals('1234567890', Util::remove(1, 10, $array)); } - public function testAddMaiorTamanhoCnab() { + public function testAddMaiorTamanhoCnab() + { $this->expectException(Exception::class); $array = array_fill(0, 400, 0); Util::adiciona($array, 400, 410, '1234567890'); } - public function testAddFinalMenorInicial() { + public function testAddFinalMenorInicial() + { $this->expectException(Exception::class); $array = array_fill(0, 400, 0); Util::adiciona($array, 300, 290, '1234567890'); } - public function testAddStringMaiorRange() { + public function testAddStringMaiorRange() + { $this->expectException(Exception::class); $array = array_fill(0, 400, 0); Util::adiciona($array, 300, 301, '1234567890'); } - public function testRemMaiorTamanhoCnab() { + public function testRemMaiorTamanhoCnab() + { $this->expectException(Exception::class); $array = array_fill(0, 400, 0); Util::remove(400, 410, $array); } - public function testRemFinalMenorInicial() { + public function testRemFinalMenorInicial() + { $this->expectException(Exception::class); $array = array_fill(0, 400, 0); Util::remove(310, 300, $array); } - public function testFormatCnab() { + public function testFormatCnab() + { $this->assertEquals('0000001234', Util::formatCnab('9', '1234', 10)); $this->assertEquals('0000001234', Util::formatCnab('9L', '1.2.3.4', 10)); $this->assertEquals('0000123400', Util::formatCnab('9', '1234', 10, 2)); @@ -85,19 +96,22 @@ public function testFormatCnab() { Util::formatCnab('J', '123', 10); } - public function testPercentuais() { + public function testPercentuais() + { $this->assertEquals(0, Util::percent(1000, 0)); $this->assertEquals(100, Util::percent(1000, 10)); $this->assertEquals(10, Util::percentOf(1000, 100)); } - public function testDatas() { + public function testDatas() + { $this->assertEquals('7019', Util::fatorVencimento('2016-12-25')); $this->assertEquals('2016-12-25', Util::fatorVencimentoBack('7019')); $this->assertEquals('3606', Util::dataJuliano('2016-12-25')); } - public function testNumeros() { + public function testNumeros() + { $this->assertEquals(0, Util::nFloat('ABC')); $this->assertEquals(0, Util::nFloat(null)); @@ -119,7 +133,8 @@ public function testNumeros() { $this->assertEquals('R$ 1.000,0', Util::nReal(1000, false, true, false)); } - public function testControleArray() { + public function testControleArray() + { $exemplo = [ 'P' => 123, // Pedido 123 @@ -132,13 +147,121 @@ public function testControleArray() { $this->assertEquals([123], Util::controle2array(123)); } - public function testControleArrayMaior25() { + public function testControleArrayMaior25() + { $this->expectException(Exception::class); Util::array2Controle(['ABCDEFG' => 1231231, 'EFGHIJKL' => 1231231]); } - public function testControleArrayKeyNumerica() { + public function testControleArrayKeyNumerica() + { $this->expectException(Exception::class); Util::array2Controle([0 => 1]); } + + public function testFuncaoLinhaDigitavel() + { + $this->assertEquals('75691111100101231230000000160010195360000010000', Util::codigoBarras2LinhaDigitavel('75691953600000100001111101012312300000016001')); + } + + public function testFuncaoFormatarLinhaDigitavel() + { + $this->assertEquals('75691.11110 01012.312300 00000.160010 1 95360000010000', Util::formatLinhaDigitavel('75691111100101231230000000160010195360000010000')); + } + + public function testFuncaoFormatarLinhaDigitavelErro() + { + $this->expectException(Exception::class); + Util::formatLinhaDigitavel('7569111110010123123000000016001019536000001000010'); + } + + public function testFuncaoGerarPixCopiaECola() + { + $pixCopiaECola = Util::gerarPixCopiaECola('teste@teste.com', 100.00, 'id-transacao', new Pessoa(['nome' => 'NOME_DA_PESSOA', 'cidade' => 'CIDADE'])); + $this->assertEquals('00020101021226370014br.gov.bcb.pix0115teste@teste.com52040000530398654031005802BR5914NOME_DA_PESSOA6006CIDADE62160512id-transacao6304DA67', $pixCopiaECola); + } + + public function testFuncaoGerarPixCopiaEColaErro() + { + $this->expectException(Exception::class); + Util::gerarPixCopiaECola('teste@teste.com', 100.00, 'id-transação', new Pessoa(['nome' => 'NOME_DA_PESSOA', 'cidade' => 'CIDADE'])); + } + + public function testFuncaoDecodePixCopiaECola() + { + $pixDecoded = Util::decodePixCopiaECola('00020101021226370014br.gov.bcb.pix0115teste@teste.com52040000530398654031005802BR5914NOME_DA_PESSOA6006CIDADE62160512id-transacao6304DA67'); + + $this->assertEquals('teste@teste.com', Arr::get($pixDecoded, '26.01')); + $this->assertEquals('id-transacao', Arr::get($pixDecoded, '62.05')); + $this->assertEquals(100, Arr::get($pixDecoded, '54')); + $this->assertEquals('NOME_DA_PESSOA', Arr::get($pixDecoded, '59')); + $this->assertEquals('CIDADE', Arr::get($pixDecoded, '60')); + } + + public function testFuncaoGerarPixCopiaEColaEDecodePixCopiaECola() + { + $pixDecoded = Util::decodePixCopiaECola(Util::gerarPixCopiaECola('teste@teste.com.br', 123.45, 'id-transacao-tx', new Pessoa(['nome' => 'NOME DA PESSOA', 'cidade' => 'SÃO PAULO']))); + $this->assertEquals('teste@teste.com.br', Arr::get($pixDecoded, '26.01')); + $this->assertEquals('id-transacao-tx', Arr::get($pixDecoded, '62.05')); + $this->assertEquals(123.45, Arr::get($pixDecoded, '54')); + $this->assertEquals('NOME DA PESSOA', Arr::get($pixDecoded, '59')); + $this->assertEquals('SAO PAULO', Arr::get($pixDecoded, '60')); + } + + public function testFuncaoTipoChavePix() + { + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_EMAIL, Util::tipoChavePix('teste@teste.com')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_EMAIL, Util::tipoChavePix('teste@teste.com.br')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_EMAIL, Util::tipoChavePix('teste@teste.com.br')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CNPJ, Util::tipoChavePix('00.000.000/0001-91')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CPF, Util::tipoChavePix('000.000.001-91')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99)9999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99) 9999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99) 9999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99) 9999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99)99999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99) 99999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99) 99999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('(99) 99999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('9999999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('99 99999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('99 99999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('99 99999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('9999999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('9999999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('9999999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('99999999999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+5599999999999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+559999999999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55-99-99999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55.99.99999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 99 99999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 9999999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 99 99999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 9999999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 99 99999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 9999999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55-99-9999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55.99.9999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 99 9999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 999999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 99 9999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 999999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 99 99999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 9999999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 99999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 99999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 99999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 999999999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 9999-9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 9999.9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 9999 9999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_CELULAR, Util::tipoChavePix('+55 (99) 99999999')); + $this->assertEquals(AbstractBoleto::TIPO_CHAVEPIX_ALEATORIA, Util::tipoChavePix('b527c9ac-9cb9-4fe1-a526-2f700fcf8ed7')); + + $this->assertNull(Util::tipoChavePix('b527c9ac-9cb9-4fe1-a526-2f700fcf8ed7-1234')); + $this->assertNull(Util::tipoChavePix('00.000.000/0001-00')); + $this->assertNull(Util::tipoChavePix('000.000.001-00')); + $this->assertNull(Util::tipoChavePix('texto-qualquer')); + } }