-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathboleto_cloud.py
More file actions
199 lines (169 loc) · 6.77 KB
/
boleto_cloud.py
File metadata and controls
199 lines (169 loc) · 6.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import requests
import base64
from datetime import datetime
from odoo import fields, models
from odoo.exceptions import UserError
class BoletoCloud(models.Model):
_inherit = "payment.acquirer"
provider = fields.Selection(
selection_add=[("boleto.cloud", "Boleto Cloud")],
ondelete={"boleto.cloud": "set default"},
)
class PaymentTransaction(models.Model):
_inherit = "payment.transaction"
boleto_pdf = fields.Binary(string="Boleto PDF")
boleto_pdf_name = fields.Char(string="Nome Boleto")
def _find_attachment_ids_email(self):
atts = super(PaymentTransaction, self)._find_attachment_ids_email()
attachment_obj = self.env["ir.attachment"]
for transaction in self:
if transaction.boleto_pdf:
pdf_id = attachment_obj.create(
dict(
name=transaction.boleto_pdf_name,
datas=transaction.boleto_pdf,
mimetype="application/pdf",
res_model="account.move",
res_id=transaction.invoice_ids[0].id,
)
)
atts.append(pdf_id.id)
return atts
class CnabRemessa(models.Model):
_name = "cnab.remessa"
_description = "Remessa de CNAB"
_order = "id desc"
def _default_company(self):
return self.env.company
def _default_user(self):
return self.env.user
def _default_journal(self):
journal = self.env["account.journal"].search(
[("use_boleto_cloud", "=", True)], limit=1
)
return journal
name = fields.Char(
max_length=30, string="Nome", required=True, default="/"
)
company_id = fields.Many2one(
"res.company", string="Company", default=_default_company
)
user_id = fields.Many2one(
"res.users", string="Responsável", default=_default_user
)
journal_id = fields.Many2one(
"account.journal", string="Diário", default=_default_journal
)
cnab_file = fields.Binary("CNAB File", readonly=True)
cnab_file_name = fields.Binary("CNAB Name", readonly=True)
data_emissao_cnab = fields.Datetime(
"Data de Emissão do CNAB", readonly=True
)
cnab_location = fields.Char()
state = fields.Selection(
[("draft", "Provisorio"), ("done", "Pronto")], default="draft"
)
def action_get_remessa(self):
if self.state == "done":
raise UserError("Não é possível gerar o arquivo novamente!")
acquirer = self.env["payment.acquirer"].search(
[("provider", "=", "boleto.cloud")]
)
if acquirer.state == "enabled":
url = "https://app.boletocloud.com/api/v1/arquivos/cnab/remessas"
else:
url = "https://sandbox.boletocloud.com/api/v1/arquivos/cnab/remessas"
api_token = self.company_id.boleto_cloud_api_token
data = {
"remessa.conta.token": self.journal_id.boleto_cloud_bank_account_api_key,
}
response = requests.post(url, data=data, auth=(api_token, "token"))
if response.status_code == 204:
raise UserError("Não há remessas CNAB a serem geradas.")
elif response.status_code == 201:
arquivo = base64.b64encode(response.content)
remessa = self.write(
{
"cnab_file": arquivo,
"data_emissao_cnab": datetime.now(),
"cnab_location": response.headers["Location"],
"name": response.headers["Content-Disposition"].split(
"="
)[1],
"state": "done",
}
)
else:
jsonp = response.json()
message = "\n".join(
[x["mensagem"] for x in jsonp["erro"]["causas"]]
)
raise UserError(
"Houve um erro com a API do Boleto Cloud:\n%s" % message
)
return remessa
class WizardImportCnabRetorno(models.TransientModel):
_name = "wizard.import.cnab.retorno"
def _default_journal(self):
journal = self.env["account.journal"].search(
[("use_boleto_cloud", "=", True)], limit=1
)
return journal
cnab_file = fields.Binary("Arquivo CNAB")
journal_id = fields.Many2one(
"account.journal", string="Diário", default=_default_journal
)
def action_import_cnab_file(self):
if not self.cnab_file:
raise UserError("Arquivo CNAB não definido.")
if not (self.journal_id or self.journal_id.use_boleto_cloud):
raise UserError(
"Diário não definido ou não configurado para usar o Boleto Cloud."
)
acquirer = self.env["payment.acquirer"].search(
[("provider", "=", "boleto.cloud")]
)
if acquirer.state == "enabled":
url = "https://app.boletocloud.com/api/v1/arquivos/cnab/retornos"
else:
url = "https://sandbox.boletocloud.com/api/v1/arquivos/cnab/retornos"
api_token = self.env.company.boleto_cloud_api_token
data = {"arquivo": base64.b64decode(self.cnab_file)}
response = requests.post(url, files=data, auth=(api_token, "token"))
if response.status_code == 400:
jsonp = response.json()
message = "\n".join(
[x["mensagem"] for x in jsonp["erro"]["causas"]]
)
raise UserError(
"Houve um erro com a API do Boleto Cloud:\n%s" % message
)
last_statement = self.env["account.bank.statement"].search(
[], order="id desc", limit=1
)
statement = self.env["account.bank.statement"].create(
{
"name": response["arquivo"]["protocolo"]["numero"],
"journal_id": self.journal_id.id,
"date": datetime.now().date(),
"balance_start_real": last_statement.balance_end_real,
"balance_end_real": last_statement.balance_end_real
+ last_statement.total_entry_encoding,
}
)
for titulo in response["arquivo"]["titulos"]:
transaction = self.env["payment.transaction"].search(
[("acquirer_reference", "=", titulo["token"])]
)
self.env["account.bank.statement.line"].create(
{
"bank_statement_id": statement.id,
"date": datetime.strptime(
titulo["vencimento"], "%Y-%m-%d"
),
"name": titulo["numero"],
"partner_id": transaction.partner_id.id,
"ref": titulo["token"],
"amount": titulo["valor"],
}
)