You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

281 lines
10 KiB

  1. # Copyright 2014-2017 Akretion (http://www.akretion.com).
  2. # @author Alexis de Lattre <alexis.delattre@akretion.com>
  3. # @author Sébastien BEAU <sebastien.beau@akretion.com>
  4. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  5. import logging
  6. from datetime import datetime
  7. from odoo import _, api, fields, models
  8. from odoo.exceptions import UserError
  9. import re
  10. from io import StringIO
  11. _logger = logging.getLogger(__name__)
  12. try:
  13. import csv
  14. except (ImportError, IOError) as err:
  15. _logger.debug(err)
  16. # Paypal header depend of the country the order are the same but the
  17. # value are translated. You can add you header here
  18. HEADERS = [
  19. # French
  20. '"Date","Heure","Fuseau horaire","Description","Devise","Avant commission"'
  21. ',"Commission","Net","Solde","Numéro de transaction","Adresse email de '
  22. 'l\'expéditeur","Nom","Nom de la banque","Compte bancaire","Montant des '
  23. 'frais de livraison et de traitement","TVA","Identifiant de facture",'
  24. '"Numéro de la transaction de référence"',
  25. # English
  26. '"Date","Time","Time Zone","Description","Currency","Gross ","Fee ","Net",'
  27. '"Balance","Transaction ID","From Email Address","Name","Bank Name",'
  28. '"Bank Account","Shipping and Handling Amount","Sales Tax","Invoice ID",'
  29. '"Reference Txn ID"',
  30. ]
  31. class AccountBankStatementImport(models.TransientModel):
  32. _inherit = 'account.bank.statement.import'
  33. @api.model
  34. def _get_paypal_encoding(self):
  35. return 'utf-8-sig'
  36. @api.model
  37. def _get_paypal_str_data(self, data_file):
  38. if not isinstance(data_file, str):
  39. data_file = data_file.decode(self._get_paypal_encoding())
  40. return data_file.strip()
  41. @api.model
  42. def _get_paypal_date_format(self):
  43. """ This method is designed to be inherited """
  44. return '%d/%m/%Y'
  45. @api.model
  46. def _paypal_convert_amount(self, amount_str):
  47. """ This method is designed to be inherited """
  48. valstr = re.sub(r'[^\d,.-]', '', amount_str)
  49. valstrdot = valstr.replace('.', '')
  50. valstrdot = valstrdot.replace(',', '.')
  51. return float(valstrdot)
  52. @api.model
  53. def _check_paypal(self, data_file):
  54. data_file = self._get_paypal_str_data(data_file)
  55. for header in HEADERS:
  56. if data_file.strip().startswith(header):
  57. return True
  58. return False
  59. def _convert_paypal_line_to_dict(self, idx, line):
  60. date_dt = datetime.strptime(line[0], self._get_paypal_date_format())
  61. rline = {
  62. 'date': fields.Date.to_string(date_dt),
  63. 'time': line[1],
  64. 'description': line[3],
  65. 'currency': line[4],
  66. 'amount': line[5],
  67. 'commission': line[6],
  68. 'balance': line[8],
  69. 'transaction_id': line[9],
  70. 'email': line[10],
  71. 'partner_name': line[11],
  72. # This two field are useful for bank transfer
  73. 'bank_name': line[12],
  74. 'bank_account': line[13],
  75. 'invoice_number': line[16],
  76. 'origin_transaction_id': line[17],
  77. 'idx': idx,
  78. }
  79. for field in ['commission', 'amount', 'balance']:
  80. _logger.debug('Trying to convert %s to float' % rline[field])
  81. try:
  82. rline[field] = self._paypal_convert_amount(rline[field])
  83. except Exception:
  84. raise UserError(
  85. _("Value '%s' for the field '%s' on line %d, "
  86. "cannot be converted to float")
  87. % (rline[field], field, idx))
  88. return rline
  89. def _parse_paypal_file(self, data_file):
  90. data_file = self._get_paypal_str_data(data_file)
  91. f = StringIO(data_file)
  92. f.seek(0)
  93. raw_lines = []
  94. reader = csv.reader(f)
  95. next(reader) # Drop header
  96. for idx, line in enumerate(reader):
  97. _logger.debug("Line %d: %s" % (idx, line))
  98. raw_lines.append(self._convert_paypal_line_to_dict(idx, line))
  99. return raw_lines
  100. def _prepare_paypal_currency_vals(self, cline):
  101. currencies = self.env['res.currency'].search(
  102. [('name', '=', cline['currency'])])
  103. if not currencies:
  104. raise UserError(
  105. _('currency %s on line %d cannot be found in odoo')
  106. % (cline['currency'], cline['idx']))
  107. return {
  108. 'amount_currency': cline['amount'],
  109. 'currency_id': currencies.id,
  110. 'currency': cline['currency'],
  111. 'partner_name': cline['partner_name'],
  112. 'description': cline['description'],
  113. 'email': cline['email'],
  114. 'transaction_id': cline['transaction_id'],
  115. }
  116. def _post_process_statement_line(self, raw_lines):
  117. journal_id = self.env.context.get('journal_id')
  118. if not journal_id:
  119. raise UserError(_('You must run this wizard from the journal'))
  120. journal = self.env['account.journal'].browse(journal_id)
  121. currency = journal.currency_id or journal.company_id.currency_id
  122. currency_change_lines = {}
  123. real_transactions = []
  124. for line in raw_lines:
  125. if line['currency'] != currency.name:
  126. currency_change_lines[line['transaction_id']] = line
  127. else:
  128. real_transactions.append(line)
  129. for line in real_transactions:
  130. # Check if the current transaction is linked with a
  131. # transaction of currency change if yes merge the transaction
  132. # as for odoo it's only one line
  133. cline = currency_change_lines.get(line['origin_transaction_id'])
  134. if cline:
  135. # we update the current line with currency information
  136. vals = self._prepare_paypal_currency_vals(cline)
  137. line.update(vals)
  138. return real_transactions
  139. def _prepare_paypal_statement_line(self, fline):
  140. if fline['bank_name']:
  141. name = '|'.join([
  142. fline['description'],
  143. fline['bank_name'],
  144. fline['bank_account']
  145. ])
  146. else:
  147. name = '|'.join([
  148. fline['description'],
  149. fline['partner_name'],
  150. fline['email'],
  151. fline['invoice_number'],
  152. ])
  153. return {
  154. 'date': fline['date'],
  155. 'name': name,
  156. 'ref': fline['transaction_id'],
  157. 'unique_import_id':
  158. fline['transaction_id'] + fline['date'] + fline['time'],
  159. 'amount': fline['amount'],
  160. 'bank_account_id': False,
  161. 'currency_id': fline.get('currency_id'),
  162. 'amount_currency': fline.get('amount_currency'),
  163. }
  164. def _prepare_paypal_statement(self, lines):
  165. return {
  166. 'name':
  167. _('PayPal Import %s > %s')
  168. % (lines[0]['date'], lines[-1]['date']),
  169. 'date': lines[-1]['date'],
  170. 'balance_start':
  171. lines[0]['balance'] -
  172. lines[0]['amount'] -
  173. lines[0]['commission'],
  174. 'balance_end_real': lines[-1]['balance'],
  175. }
  176. @api.model
  177. def _parse_file(self, data_file):
  178. """ Import a file in Paypal CSV format """
  179. paypal = self._check_paypal(data_file)
  180. if not paypal:
  181. return super(AccountBankStatementImport, self)._parse_file(
  182. data_file)
  183. raw_lines = self._parse_paypal_file(data_file)
  184. final_lines = self._post_process_statement_line(raw_lines)
  185. vals_bank_statement = self._prepare_paypal_statement(final_lines)
  186. transactions = []
  187. commission_total = 0
  188. for fline in final_lines:
  189. commission_total += fline['commission']
  190. vals_line = self._prepare_paypal_statement_line(fline)
  191. _logger.debug("vals_line = %s" % vals_line)
  192. transactions.append(vals_line)
  193. if commission_total:
  194. commission_line = {
  195. 'date': vals_bank_statement['date'],
  196. 'name': _('Paypal commissions'),
  197. 'ref': _('PAYPAL-COSTS'),
  198. 'amount': commission_total,
  199. 'unique_import_id': False,
  200. }
  201. transactions.append(commission_line)
  202. vals_bank_statement['transactions'] = transactions
  203. return None, None, [vals_bank_statement]
  204. @api.model
  205. def _get_paypal_partner(self, description, partner_name,
  206. partner_email, invoice_number):
  207. if invoice_number:
  208. # In most case e-commerce case invoice_number
  209. # will contain the sale order number
  210. sale = self.env['sale.order'].search([
  211. ('name', '=', invoice_number)])
  212. if sale and len(sale) == 1:
  213. return sale.partner_id.commercial_partner_id
  214. invoice = self.env['account.invoice'].search([
  215. ('number', '=', invoice_number)])
  216. if invoice and len(invoice) == 1:
  217. return invoice.partner_id.commercial_partner_id
  218. if partner_email:
  219. partner = self.env['res.partner'].search([
  220. ('email', '=', partner_email),
  221. ('parent_id', '=', False)])
  222. if partner and len(partner) == 1:
  223. return partner.commercial_partner_id
  224. if partner_name:
  225. partner = self.env['res.partner'].search([
  226. ('name', '=ilike', partner_name)])
  227. if partner and len(partner) == 1:
  228. return partner.commercial_partner_id
  229. return None
  230. @api.model
  231. def _complete_paypal_statement_line(self, line):
  232. _logger.debug('Process line %s', line['name'])
  233. info = line['name'].split('|')
  234. if len(info) == 4:
  235. partner = self._get_paypal_partner(*info)
  236. if partner:
  237. return {
  238. 'partner_id': partner.id,
  239. 'account_id': partner.property_account_receivable.id,
  240. }
  241. return None
  242. @api.model
  243. def _complete_statement(self, stmts_vals, journal_id, account_number):
  244. """ Match the partner from paypal information """
  245. stmts_vals = super(AccountBankStatementImport, self).\
  246. _complete_statement(stmts_vals, journal_id, account_number)
  247. for line in stmts_vals['transactions']:
  248. vals = self._complete_paypal_statement_line(line)
  249. if vals:
  250. line.update(vals)
  251. return stmts_vals