main.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. # -*- coding: utf-8 -*-
  2. from openerp import http
  3. from openerp.http import request
  4. from werkzeug.wrappers import Response
  5. from werkzeug.datastructures import Headers
  6. from datetime import datetime
  7. from gzip import GzipFile
  8. from StringIO import StringIO as IO
  9. import simplejson as json
  10. import gzip
  11. import logging
  12. LOGGER = logging.getLogger(__name__)
  13. DATE_FORMAT = '%Y-%m-%d'
  14. GZIP_COMPRESSION_LEVEL = 9
  15. class PaymentsSales(http.Controller):
  16. '''
  17. Get server date
  18. '''
  19. def get_server_date(self):
  20. return datetime.now().strftime(DATE_FORMAT)
  21. '''
  22. Get partner customer
  23. '''
  24. def get_user(self):
  25. user = request.env.user
  26. return {
  27. 'id': user.id,
  28. 'name': user.name,
  29. 'displayName': user.display_name,
  30. 'company': {
  31. 'id': user.company_id.id,
  32. 'name': user.company_id.name
  33. },
  34. 'currency': {
  35. 'id': user.company_id.currency_id.id,
  36. 'name': user.company_id.currency_id.name,
  37. 'displayName': user.company_id.currency_id.display_name,
  38. 'symbol': user.company_id.currency_id.symbol,
  39. 'rateSilent': user.company_id.currency_id.rate_silent,
  40. 'thousandsSeparator': user.company_id.currency_id.thousands_separator,
  41. 'decimalSeparator': user.company_id.currency_id.decimal_separator,
  42. 'decimalPlaces': user.company_id.currency_id.decimal_places,
  43. 'position': user.company_id.currency_id.position
  44. }
  45. }
  46. '''
  47. Get partner customer
  48. '''
  49. def get_customers(self):
  50. domain = [('customer', '=', True), ('active', '=', True), ('credit', '>', 0)]
  51. partners = []
  52. for customer in request.env['res.partner'].search(domain):
  53. invoices = []
  54. partner_invoice = []
  55. for invoice_ids in customer.invoice_ids:
  56. if invoice_ids.state == 'open':
  57. partner_invoice.append(invoice_ids.id)
  58. if customer.is_company == True:
  59. for child in customer.child_ids:
  60. for invoice_ids in child.invoice_ids:
  61. if invoice_ids.state == 'open':
  62. partner_invoice.append(invoice_ids.id)
  63. # for invoice in request.env['account.invoice'].browse(partner_invoice):
  64. for invoice in request.env['account.invoice'].search([('id', 'in', partner_invoice),('state', '=', 'open')]):
  65. movelines = []
  66. moves = []
  67. for move in invoice.move_id:
  68. for moveline in move.line_id:
  69. if moveline.amount_residual > 0 and moveline.state != "draft" and moveline.credit <= 0:
  70. currencyAmount = []
  71. decimal_precision = request.env['decimal.precision'].precision_get('Account')
  72. domain = [('active', '=', True)]
  73. for currency in request.env['res.currency'].search(domain):
  74. amount_currency = moveline.amount_currency
  75. if moveline.amount_currency <= 0:
  76. amount_currency = moveline.debit
  77. currencyAmount.append({
  78. 'id': currency.id,
  79. 'name': currency.name,
  80. 'displayName': currency.display_name,
  81. 'base': currency.base,
  82. 'accuracy': currency.accuracy,
  83. 'rateSilent': currency.rate_silent,
  84. 'rounding': currency.rounding,
  85. 'symbol': currency.symbol,
  86. 'position': currency.position,
  87. 'thousandsSeparator': currency.thousands_separator,
  88. 'decimalSeparator': currency.decimal_separator,
  89. 'decimalPlaces': currency.decimal_places,
  90. 'amountCurency': round(amount_currency * (currency.rate_silent/ invoice.currency_id.rate_silent), decimal_precision),
  91. 'amountCurencyResidual': round((moveline.amount_residual_currency * (currency.rate_silent / invoice.currency_id.rate_silent)), decimal_precision)
  92. })
  93. movelines.append({
  94. 'id': moveline.id,
  95. 'amountResidual': moveline.amount_residual,
  96. 'credit': moveline.credit,
  97. 'debit': moveline.debit,
  98. 'dateMaturity': moveline.date_maturity,
  99. 'invoice': invoice.id,
  100. 'amountCurrency': moveline.amount_currency if moveline.amount_currency > 0 else moveline.debit,
  101. 'amountResidualCurrency': moveline.amount_residual_currency,
  102. 'currencyAmount': currencyAmount
  103. })
  104. invoices.append({
  105. 'id': invoice.id,
  106. 'number': invoice.number,
  107. 'dateInvoice': invoice.date_invoice,
  108. 'amountTotal': invoice.amount_total,
  109. 'residual': invoice.residual,
  110. 'moveLines': movelines,
  111. 'currency' : {
  112. 'id': invoice.currency_id.id,
  113. 'name': invoice.currency_id.name,
  114. 'displayName': invoice.currency_id.display_name,
  115. 'symbol': invoice.currency_id.symbol,
  116. 'rateSilent': invoice.currency_id.rate_silent,
  117. 'thousandsSeparator': invoice.currency_id.thousands_separator,
  118. 'decimalSeparator': invoice.currency_id.decimal_separator,
  119. 'decimalPlaces': invoice.currency_id.decimal_places,
  120. 'position': invoice.currency_id.position
  121. }
  122. })
  123. partners.append({
  124. 'id': customer.id,
  125. 'name': customer.name,
  126. 'displayName': customer.display_name,
  127. 'ruc': customer.ruc,
  128. 'imageMedium': customer.image_medium,
  129. 'phone': customer.phone,
  130. 'mobile': customer.mobile,
  131. 'email': customer.email,
  132. 'credit': customer.credit,
  133. 'creditLimit': customer.credit_limit,
  134. 'invoices': invoices
  135. })
  136. return partners
  137. '''
  138. Get Journal
  139. '''
  140. def get_journals(self):
  141. # domain =[('active', '=', True),('type', 'in',['bank', 'cash']), ('default_credit_account_id.currency_id', '=', False)]
  142. domain =[('active', '=', True),('type', 'in',['bank', 'cash'])]
  143. paymentsJournals = []
  144. for journal in request.env['account.journal'].search(domain, order="id"):
  145. if not (journal.store_ids >= request.env.user.store_ids):
  146. continue
  147. paymentsJournals.append({
  148. 'id': journal.id,
  149. 'name': journal.name,
  150. 'displayName': journal.display_name,
  151. 'code': journal.code,
  152. 'cashControl': journal.cash_control,
  153. 'type': journal.type,
  154. 'currency': {
  155. 'id': journal.currency.id,
  156. 'name': journal.currency.name,
  157. 'displayName': journal.currency.display_name,
  158. 'symbol': journal.currency.symbol,
  159. 'rateSilent': journal.currency.rate_silent,
  160. 'thousandsSeparator':journal.currency.thousands_separator,
  161. 'decimalSeparator': journal.currency.decimal_separator,
  162. 'decimalPlaces': journal.currency.decimal_places,
  163. 'position': journal.currency.position
  164. },
  165. 'defaultCreditAccount':{
  166. 'id': journal.default_credit_account_id.id,
  167. 'name': journal.default_credit_account_id.name,
  168. 'displayName': journal.default_credit_account_id.display_name,
  169. 'code': journal.default_credit_account_id.code,
  170. 'exchangeRate': journal.default_credit_account_id.exchange_rate,
  171. 'foreignBalance': journal.default_credit_account_id.foreign_balance,
  172. 'reconcile': journal.default_credit_account_id.reconcile,
  173. 'debit': journal.default_credit_account_id.debit,
  174. 'credit': journal.default_credit_account_id.credit,
  175. 'currencyMode': journal.default_credit_account_id.currency_mode,
  176. 'companyCurrency':{
  177. 'id': journal.default_credit_account_id.company_currency_id.id,
  178. 'name': journal.default_credit_account_id.company_currency_id.name,
  179. 'displayName': journal.default_credit_account_id.company_currency_id.display_name,
  180. 'symbol': journal.default_credit_account_id.company_currency_id.symbol,
  181. 'rateSilent': journal.default_credit_account_id.company_currency_id.rate_silent
  182. },
  183. 'currency':{
  184. 'id': journal.default_credit_account_id.currency_id.id,
  185. 'name': journal.default_credit_account_id.currency_id.name,
  186. 'displayName': journal.default_credit_account_id.currency_id.display_name,
  187. 'symbol': journal.default_credit_account_id.currency_id.symbol,
  188. 'rateSilent': journal.default_credit_account_id.currency_id.rate_silent
  189. },
  190. }
  191. })
  192. return paymentsJournals
  193. '''
  194. Get Currency
  195. '''
  196. def get_currency(self):
  197. return [{
  198. 'id': currency.id,
  199. 'name': currency.name,
  200. 'displayName': currency.display_name,
  201. 'base': currency.base,
  202. 'accuracy': currency.accuracy,
  203. 'rateSilent': currency.rate_silent,
  204. 'rounding': currency.rounding,
  205. 'symbol': currency.symbol,
  206. 'position': currency.position,
  207. 'thousandsSeparator': currency.thousands_separator,
  208. 'decimalSeparator': currency.decimal_separator,
  209. 'decimalPlaces': currency.decimal_places
  210. } for currency in request.env['res.currency'].search([('active', '=', True)])]
  211. '''
  212. Get bank
  213. '''
  214. def get_bank(self):
  215. resBank = []
  216. if self.check_module('eiru_bank_payments_references'):
  217. resBank = [{
  218. 'id': bank.id,
  219. 'name': bank.name
  220. } for bank in request.env['res.bank'].search([('active', '=', True)])]
  221. return resBank
  222. '''
  223. Get Bank Payments Type
  224. '''
  225. def get_bank_payments_type(self):
  226. resBankType = []
  227. if self.check_module('eiru_bank_payments_references'):
  228. resBankType = [{
  229. 'id': bank_type.id,
  230. 'name': bank_type.name,
  231. 'code': bank_type.code,
  232. 'default_state': bank_type.default_state
  233. } for bank_type in request.env['res.bank.payments.type'].search([('is_receipt', '=', True)])]
  234. return resBankType
  235. '''
  236. GET BANK PAYMNETS
  237. '''
  238. def get_bank_Payments(self):
  239. bankPaymnets = []
  240. if self.check_module('eiru_bank_payments_references'):
  241. bankPaymnets = [{
  242. 'id': bankPayments.id,
  243. 'number': bankPayments.number,
  244. 'dateMaturity': bankPayments.date_maturity,
  245. 'state': bankPayments.state,
  246. 'numberCta': bankPayments.number_cta,
  247. 'nameHolder': bankPayments.name_holder,
  248. 'amountTotal': bankPayments.amount_total,
  249. 'amountReceipt': bankPayments.amount_receipt,
  250. 'amountPayment': bankPayments.amount_payment,
  251. 'bankId': {
  252. 'id': bankPayments.bank_id.id,
  253. 'name': bankPayments.bank_id.name
  254. },
  255. 'bankPaymentsType':{
  256. 'id': bankPayments.bank_payments_type_id.id,
  257. 'name': bankPayments.bank_payments_type_id.name,
  258. 'code': bankPayments.bank_payments_type_id.code,
  259. 'default_state': bankPayments.bank_payments_type_id.default_state
  260. },
  261. 'paymentsLine':[{
  262. 'amount': line.amount,
  263. 'date': line.date,
  264. 'typeOperation': line.type_operation
  265. } for line in request.env['res.bank.payments.line'].search([('bank_payments_id', 'in',[bankPayments.id]),('type_operation','=', 'receipt')])]
  266. } for bankPayments in request.env['res.bank.payments'].search([('bank_payments_type_id.code','=','CH')])]
  267. return bankPaymnets
  268. '''
  269. Check if module is installed
  270. '''
  271. def check_module(self, module_name):
  272. module = request.env['ir.module.module'].search([('name', '=', module_name), ('state', '=', 'installed')])
  273. return len(module) != 0
  274. '''
  275. Make JSON response
  276. '''
  277. def make_json_response(self, data=None, status=200):
  278. return Response(json.dumps(data), status=status, content_type='application/json')
  279. '''
  280. Make GZIP to JSON response
  281. '''
  282. def make_gzip_response(self, data=None, status=200):
  283. gzip_buffer = IO()
  284. with GzipFile(mode='wb', compresslevel=GZIP_COMPRESSION_LEVEL, fileobj=gzip_buffer) as gzip_file:
  285. gzip_file.write(json.dumps(data))
  286. contents = gzip_buffer.getvalue()
  287. gzip_buffer.close()
  288. headers = Headers()
  289. headers.add('Content-Encoding', 'gzip')
  290. headers.add('Vary', 'Accept-Encoding')
  291. headers.add('Content-Length', len(contents))
  292. return Response(contents, status=status, headers=headers, content_type='application/json')
  293. '''
  294. Logger Info
  295. '''
  296. def make_info_log(self, log):
  297. LOGGER.info(log)
  298. '''
  299. New Payments resource router
  300. '''
  301. @http.route('/eiru_payments/init', auth='user', methods=['GET'], cors='*')
  302. def init_payments(self, **kw):
  303. self.make_info_log('Sending JSON response')
  304. return self.make_gzip_response({
  305. 'date': self.get_server_date(),
  306. 'user': self.get_user(),
  307. 'customers': self.get_customers(),
  308. 'journals': self.get_journals(),
  309. 'currencies': self.get_currency(),
  310. 'bank': self.get_bank(),
  311. 'bankType': self.get_bank_payments_type(),
  312. 'bankPayments': self.get_bank_Payments()
  313. })
  314. '''
  315. Get the current period
  316. '''
  317. def get_period(self, date_server):
  318. return request.env['account.period'].search([('date_start','<=', date_server), ('date_stop', '>=', datetime.now().strftime(DATE_FORMAT))])
  319. '''
  320. Get Invoice
  321. '''
  322. def get_invoice(self, invoice_id):
  323. return request.env['account.invoice'].search([('id', '=', invoice_id)])
  324. '''
  325. Create Voucher
  326. '''
  327. def create_voucher(self, period, invoice, company_id, amountPayments, date_server, journalId, move_line_Ids, customerId):
  328. ## Get Journal
  329. journal_id = request.env['account.journal'].browse(int(journalId))
  330. currency_id = journal_id.default_credit_account_id.currency_id.id or journal_id.default_credit_account_id.company_currency_id.id
  331. # currency_rateSilent = journal_id.default_credit_account_id.currency_id.rate_silent or journal_id.default_credit_account_id.company_currency_id.rate_silent
  332. # Get Move Lines
  333. move_line = request.env['account.move.line'].browse(move_line_Ids).sorted(key=lambda r: r.id)
  334. # get customer
  335. customerId = request.env['res.partner'].browse(customerId)
  336. decimal_precision = request.env['decimal.precision'].precision_get('Account')
  337. # Currencies
  338. company_currency = request.env.user.company_id.currency_id
  339. currencyVocuher = request.env['res.currency'].browse(currency_id)
  340. # Create Line Voucher
  341. line_cr_ids = []
  342. amount = round(float(amountPayments), decimal_precision)
  343. for line in move_line:
  344. amount_residual = line.amount_residual
  345. if (company_currency.id != currencyVocuher.id):
  346. amount_residual = round((amount_residual * (currencyVocuher.rate / company_currency.rate)), decimal_precision)
  347. line_cr_ids.append([0, False, {
  348. 'date_due': line.date_maturity,
  349. 'account_id': line.account_id.id,
  350. 'date_original': line.move_id.date,
  351. 'move_line_id': line.id,
  352. 'amount_original': abs(line.credit or line.debit or 0.0),
  353. 'amount_unreconciled': abs(line.amount_residual),
  354. 'amount': min(abs(amount), abs(amount_residual)),
  355. 'reconcile': True if abs(amount_residual) == min(abs(amount), abs(amount_residual)) else False,
  356. 'currency_id': currency_id
  357. }])
  358. amount -= min(abs(amount), amount_residual)
  359. values = {
  360. 'reference': invoice.number,
  361. 'type': 'receipt',
  362. 'journal_id': journal_id.id,
  363. 'company_id': company_id,
  364. 'pre_line': True,
  365. 'amount': round(float(amountPayments), decimal_precision),
  366. 'period_id': period.id,
  367. 'date': date_server,
  368. 'partner_id': customerId.id,
  369. 'account_id': journal_id.default_credit_account_id.id,
  370. 'currency_id': currency_id,
  371. 'line_cr_ids': line_cr_ids,
  372. 'payment_rate_currency_id': currency_id
  373. }
  374. account_voucher = request.env['account.voucher'].create(values)
  375. account_voucher.action_move_line_create()
  376. return account_voucher
  377. '''
  378. close invoice
  379. '''
  380. def close_invoice(self, invoiceid):
  381. invoice = request.env['account.invoice'].search([('id', '=', invoiceid)])
  382. if invoice.residual <= 0:
  383. # invoice.write({
  384. # 'state': 'paid'
  385. # })
  386. invoice.confirm_paid()
  387. return invoice
  388. '''
  389. Create bank Statement
  390. '''
  391. def create_bank_statement(self, date_server, user_id, account_voucher):
  392. # Get bank Statamente
  393. bank_statement = request.env['account.bank.statement'].search([('journal_id', '=', account_voucher.journal_id.id), ('date', '=', date_server)])
  394. bank = {
  395. 'journal_id': account_voucher.journal_id.id,
  396. 'period_id': account_voucher.period_id.id,
  397. 'date': date_server,
  398. 'user_id': user_id,
  399. 'state': 'open' if account_voucher.journal_id.type == 'cash' else 'draft',
  400. }
  401. if bank_statement:
  402. if len(bank_statement) == 1:
  403. bank_statement.write(bank)
  404. else:
  405. bank_statement[len(bank_statement) -1].write(bank)
  406. else:
  407. bank_statement = bank_statement.create(bank)
  408. return bank_statement
  409. '''
  410. Create Statamente Line
  411. '''
  412. def create_bank_statement_line(self, account_voucher, statement):
  413. # Create line bank
  414. bank_statement_line = {
  415. 'name': account_voucher.reference,
  416. 'partner_id': account_voucher.partner_id.id,
  417. 'amount': account_voucher.amount,
  418. 'voucher_id': account_voucher.id,
  419. 'journal_id': account_voucher.journal_id.id,
  420. 'account_id': account_voucher.account_id.id,
  421. 'journal_entry_id': account_voucher.move_id.id,
  422. 'currency_id': account_voucher.currency_id.id,
  423. 'ref': 'NP',
  424. 'statement_id': statement.id
  425. }
  426. line_id = request.env['account.bank.statement.line'].create(bank_statement_line)
  427. return line_id
  428. '''
  429. Bank Line
  430. '''
  431. def create_bank_paymnets(self, account_voucher, date_server, bankId, bankTypeId, paymentsBankRef, paymentsBankDateMaturity, paymentsBankNumber_cta, paymentsBankName_holder, bankAmount):
  432. bank_id = request.env['res.bank'].browse(bankId)
  433. bank_type_id = request.env['res.bank.payments.type'].browse(bankTypeId)
  434. paymnets_bank = request.env['res.bank.payments'].search([('number', '=', paymentsBankRef)])
  435. bank_payments = {
  436. 'number': paymentsBankRef,
  437. 'date_maturity': paymentsBankDateMaturity if (paymentsBankDateMaturity) else date_server ,
  438. 'date': date_server,
  439. 'state': bank_type_id.default_state,
  440. 'bank_id': bank_id.id,
  441. 'bank_payments_type_id': bank_type_id.id,
  442. 'comment': 'Np ',
  443. 'number_cta': paymentsBankNumber_cta,
  444. 'name_holder': paymentsBankName_holder,
  445. 'amount_total': bankAmount,
  446. 'currency_id': account_voucher.currency_id.id,
  447. 'partner_id': account_voucher.partner_id.id
  448. }
  449. if (paymnets_bank):
  450. paymnets_bank.write(bank_payments)
  451. else:
  452. paymnets_bank=request.env['res.bank.payments'].create(bank_payments)
  453. return paymnets_bank
  454. '''
  455. Create Bnak Paymnets Line
  456. '''
  457. def create_bank_paymnets_line(self, voucher, bank_payments, bank_statement_line, bank_statement, date_server):
  458. account_voucher = request.env['account.voucher'].browse(voucher.id)
  459. res_bank_payments = request.env['res.bank.payments'].browse(bank_payments.id)
  460. statement_line = request.env['account.bank.statement.line'].browse(bank_statement_line.id)
  461. statement = request.env['account.bank.statement'].browse(bank_statement.id)
  462. bank_line = {
  463. 'amount': account_voucher.amount,
  464. 'date': date_server,
  465. 'bank_payments_id': res_bank_payments.id,
  466. 'statement_line_id': bank_statement_line.id,
  467. 'statement_id': bank_statement.id,
  468. 'type_operation': account_voucher.type
  469. }
  470. paymnets_line = request.env['res.bank.payments.line'].create(bank_line)
  471. return paymnets_line
  472. '''
  473. Payment process
  474. '''
  475. @http.route('/eiru_payments/payment_process', type='json', auth='user', methods=['POST'], cors='*')
  476. def payment_process(self, **kw):
  477. self.make_info_log('Processing payments...')
  478. # Get Date Server
  479. date_server = datetime.now().strftime(DATE_FORMAT)
  480. #Get Periodo
  481. period = self.get_period(date_server)
  482. self.make_info_log('[OK] Getting period')
  483. # Get invoice
  484. invoice = self.get_invoice(kw.get('invoiceId'))
  485. self.make_info_log('[OK] Getting invoice')
  486. # Get User - company
  487. user_id = request.env.user.id
  488. self.make_info_log('[OK] Getting user')
  489. # Get Company
  490. company_id = request.env.user.company_id.id
  491. self.make_info_log('[OK] Getting Company')
  492. # create voucher
  493. voucher = self.create_voucher(period, invoice, company_id, kw.get('amountPayments', 0), date_server, kw.get('journalId'), kw.get('moveLines'), kw.get('customerId'))
  494. self.make_info_log('[OK] creating voucher...')
  495. # close invoice
  496. close_invoice = self.close_invoice(kw.get('invoiceId'))
  497. self.make_info_log('[OK] closing invoice...')
  498. # Create bank statement
  499. bank_statement = self.create_bank_statement(date_server, user_id, voucher)
  500. self.make_info_log('[OK] creating bank statement')
  501. # Create bank statement Line
  502. bank_statement_line = self.create_bank_statement_line(voucher, bank_statement)
  503. self.make_info_log('[OK] creating bank statement Line')
  504. if ((self.check_module('eiru_bank_payments_references')) and (kw.get('journalType') == 'bank')):
  505. bank_payments = self.create_bank_paymnets( voucher, date_server, kw.get('bankId'), kw.get('bankTypeId'), kw.get('bankRef'), kw.get('bankDateMaturity'), kw.get('paymentsBankNumber_cta'), kw.get('paymentsBankName_holder'), kw.get('bankAmount'))
  506. self.make_info_log('[OK] creating bank payments')
  507. bank_payments_Line = self.create_bank_paymnets_line(voucher, bank_payments, bank_statement_line, bank_statement, date_server)
  508. self.make_info_log('[OK] creating bank payments Line')
  509. return {
  510. 'process': True
  511. }