main.py 23 KB

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