main.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. # print("\n\n")
  73. # # accountConfig = request.env['account.config.settings']
  74. # import web_pdb; web_pdb.set_trace()
  75. # print(request.env.user)
  76. # print("\n")
  77. # if (request.env.user.in_group_7):
  78. # domain = [[('active', '=', True)], ['id', '=', user.company_id.currency_id.id]]
  79. # else:
  80. domain = [('active', '=', True)]
  81. for currency in request.env['res.currency'].search(domain):
  82. amount_currency = moveline.amount_currency
  83. if moveline.amount_currency <= 0:
  84. amount_currency = moveline.debit
  85. currencyAmount.append({
  86. 'id': currency.id,
  87. 'name': currency.name,
  88. 'displayName': currency.display_name,
  89. 'base': currency.base,
  90. 'accuracy': currency.accuracy,
  91. 'rateSilent': currency.rate_silent,
  92. 'rounding': currency.rounding,
  93. 'symbol': currency.symbol,
  94. 'position': currency.position,
  95. 'thousandsSeparator': currency.thousands_separator,
  96. 'decimalSeparator': currency.decimal_separator,
  97. 'decimalPlaces': currency.decimal_places,
  98. 'amountCurency': round(amount_currency * (currency.rate_silent/ invoice.currency_id.rate_silent), decimal_precision),
  99. 'amountCurencyResidual': round((moveline.amount_residual_currency * (currency.rate_silent / invoice.currency_id.rate_silent)), decimal_precision)
  100. })
  101. movelines.append({
  102. 'id': moveline.id,
  103. 'amountResidual': moveline.amount_residual,
  104. 'credit': moveline.credit,
  105. 'debit': moveline.debit,
  106. 'dateMaturity': moveline.date_maturity,
  107. 'invoice': invoice.id,
  108. 'amountCurrency': moveline.amount_currency if moveline.amount_currency > 0 else moveline.debit,
  109. 'amountResidualCurrency': moveline.amount_residual_currency,
  110. 'currencyAmount': currencyAmount
  111. })
  112. invoices.append({
  113. 'id': invoice.id,
  114. 'number': invoice.number,
  115. 'dateInvoice': invoice.date_invoice,
  116. 'amountTotal': invoice.amount_total,
  117. 'residual': invoice.residual,
  118. 'moveLines': movelines,
  119. 'currency' : {
  120. 'id': invoice.currency_id.id,
  121. 'name': invoice.currency_id.name,
  122. 'displayName': invoice.currency_id.display_name,
  123. 'symbol': invoice.currency_id.symbol,
  124. 'rateSilent': invoice.currency_id.rate_silent,
  125. 'thousandsSeparator': invoice.currency_id.thousands_separator,
  126. 'decimalSeparator': invoice.currency_id.decimal_separator,
  127. 'decimalPlaces': invoice.currency_id.decimal_places,
  128. 'position': invoice.currency_id.position
  129. }
  130. })
  131. partners.append({
  132. 'id': customer.id,
  133. 'name': customer.name,
  134. 'displayName': customer.display_name,
  135. 'ruc': customer.ruc,
  136. 'imageMedium': customer.image_medium,
  137. 'phone': customer.phone,
  138. 'mobile': customer.mobile,
  139. 'email': customer.email,
  140. 'credit': customer.credit,
  141. 'creditLimit': customer.credit_limit,
  142. 'invoices': invoices
  143. })
  144. return partners
  145. '''
  146. Get Journal
  147. '''
  148. def get_journals(self):
  149. # domain =[('active', '=', True),('type', 'in',['bank', 'cash']), ('default_credit_account_id.currency_id', '=', False)]
  150. domain =[('active', '=', True),('type', 'in',['bank', 'cash'])]
  151. paymentsJournals = []
  152. for journal in request.env['account.journal'].search(domain, order="id"):
  153. if not (journal.store_ids >= request.env.user.store_ids):
  154. continue
  155. paymentsJournals.append({
  156. 'id': journal.id,
  157. 'name': journal.name,
  158. 'displayName': journal.display_name,
  159. 'code': journal.code,
  160. 'cashControl': journal.cash_control,
  161. 'type': journal.type,
  162. 'currency': {
  163. 'id': journal.currency.id,
  164. 'name': journal.currency.name,
  165. 'displayName': journal.currency.display_name,
  166. 'symbol': journal.currency.symbol,
  167. 'rateSilent': journal.currency.rate_silent,
  168. 'thousandsSeparator':journal.currency.thousands_separator,
  169. 'decimalSeparator': journal.currency.decimal_separator,
  170. 'decimalPlaces': journal.currency.decimal_places,
  171. 'position': journal.currency.position
  172. },
  173. 'defaultCreditAccount':{
  174. 'id': journal.default_credit_account_id.id,
  175. 'name': journal.default_credit_account_id.name,
  176. 'displayName': journal.default_credit_account_id.display_name,
  177. 'code': journal.default_credit_account_id.code,
  178. 'exchangeRate': journal.default_credit_account_id.exchange_rate,
  179. 'foreignBalance': journal.default_credit_account_id.foreign_balance,
  180. 'reconcile': journal.default_credit_account_id.reconcile,
  181. 'debit': journal.default_credit_account_id.debit,
  182. 'credit': journal.default_credit_account_id.credit,
  183. 'currencyMode': journal.default_credit_account_id.currency_mode,
  184. 'companyCurrency':{
  185. 'id': journal.default_credit_account_id.company_currency_id.id,
  186. 'name': journal.default_credit_account_id.company_currency_id.name,
  187. 'displayName': journal.default_credit_account_id.company_currency_id.display_name,
  188. 'symbol': journal.default_credit_account_id.company_currency_id.symbol,
  189. 'rateSilent': journal.default_credit_account_id.company_currency_id.rate_silent
  190. },
  191. 'currency':{
  192. 'id': journal.default_credit_account_id.currency_id.id,
  193. 'name': journal.default_credit_account_id.currency_id.name,
  194. 'displayName': journal.default_credit_account_id.currency_id.display_name,
  195. 'symbol': journal.default_credit_account_id.currency_id.symbol,
  196. 'rateSilent': journal.default_credit_account_id.currency_id.rate_silent
  197. },
  198. }
  199. })
  200. return paymentsJournals
  201. '''
  202. Get Currency
  203. '''
  204. def get_currency(self):
  205. return [{
  206. 'id': currency.id,
  207. 'name': currency.name,
  208. 'displayName': currency.display_name,
  209. 'base': currency.base,
  210. 'accuracy': currency.accuracy,
  211. 'rateSilent': currency.rate_silent,
  212. 'rounding': currency.rounding,
  213. 'symbol': currency.symbol,
  214. 'position': currency.position,
  215. 'thousandsSeparator': currency.thousands_separator,
  216. 'decimalSeparator': currency.decimal_separator,
  217. 'decimalPlaces': currency.decimal_places
  218. } for currency in request.env['res.currency'].search([('active', '=', True)])]
  219. '''
  220. Make JSON response
  221. '''
  222. def make_json_response(self, data=None, status=200):
  223. return Response(json.dumps(data), status=status, content_type='application/json')
  224. '''
  225. Make GZIP to JSON response
  226. '''
  227. def make_gzip_response(self, data=None, status=200):
  228. gzip_buffer = IO()
  229. with GzipFile(mode='wb', compresslevel=GZIP_COMPRESSION_LEVEL, fileobj=gzip_buffer) as gzip_file:
  230. gzip_file.write(json.dumps(data))
  231. contents = gzip_buffer.getvalue()
  232. gzip_buffer.close()
  233. headers = Headers()
  234. headers.add('Content-Encoding', 'gzip')
  235. headers.add('Vary', 'Accept-Encoding')
  236. headers.add('Content-Length', len(contents))
  237. return Response(contents, status=status, headers=headers, content_type='application/json')
  238. '''
  239. Logger Info
  240. '''
  241. def make_info_log(self, log):
  242. LOGGER.info(log)
  243. '''
  244. New Payments resource router
  245. '''
  246. @http.route('/eiru_payments/init', auth='user', methods=['GET'], cors='*')
  247. def init_payments(self, **kw):
  248. self.make_info_log('Sending JSON response')
  249. return self.make_gzip_response({
  250. 'date': self.get_server_date(),
  251. 'user': self.get_user(),
  252. 'customers': self.get_customers(),
  253. 'journals': self.get_journals(),
  254. 'currencies': self.get_currency()
  255. })
  256. '''
  257. Get the current period
  258. '''
  259. def get_period(self, date_server):
  260. return request.env['account.period'].search([('date_start','<=', date_server), ('date_stop', '>=', datetime.now().strftime(DATE_FORMAT))])
  261. '''
  262. Get Invoice
  263. '''
  264. def get_invoice(self, invoice_id):
  265. return request.env['account.invoice'].search([('id', '=', invoice_id)])
  266. '''
  267. Create Voucher
  268. '''
  269. def create_voucher(self, period, invoice, company_id, amountPayments, date_server, journalId, move_line_Ids, customerId):
  270. ## Get Journal
  271. journal_id = request.env['account.journal'].browse(int(journalId))
  272. currency_id = journal_id.default_credit_account_id.currency_id.id or journal_id.default_credit_account_id.company_currency_id.id
  273. # currency_rateSilent = journal_id.default_credit_account_id.currency_id.rate_silent or journal_id.default_credit_account_id.company_currency_id.rate_silent
  274. # Get Move Lines
  275. move_line = request.env['account.move.line'].browse(move_line_Ids).sorted(key=lambda r: r.id)
  276. # get customer
  277. customerId = request.env['res.partner'].browse(customerId)
  278. decimal_precision = request.env['decimal.precision'].precision_get('Account')
  279. # Create Line Voucher
  280. line_cr_ids = []
  281. amount = round(float(amountPayments), decimal_precision)
  282. for line in move_line:
  283. line_cr_ids.append([0, False, {
  284. 'date_due': line.date_maturity,
  285. 'account_id': line.account_id.id,
  286. 'date_original': line.move_id.date,
  287. 'move_line_id': line.id,
  288. 'amount_original': abs(line.credit or line.debit or 0.0),
  289. 'amount_unreconciled': abs(line.amount_residual),
  290. 'amount': min(abs(amount), line.amount_residual),
  291. 'reconcile': True if abs(line.amount_residual) == min(abs(amount), line.amount_residual) else False,
  292. 'currency_id': currency_id
  293. }])
  294. amount -= min(abs(amount), line.amount_residual)
  295. company_currency = request.env.user.company_id.currency_id
  296. currencyVocuher = request.env['res.currency'].browse(currency_id)
  297. values = {
  298. 'reference': invoice.number,
  299. 'type': 'receipt',
  300. 'journal_id': journal_id.id,
  301. 'company_id': company_id,
  302. 'pre_line': True,
  303. 'amount': round(float(amountPayments), decimal_precision),
  304. 'period_id': period.id,
  305. 'date': date_server,
  306. 'partner_id': customerId.id,
  307. 'account_id': journal_id.default_credit_account_id.id,
  308. 'currency_id': currency_id,
  309. 'line_cr_ids': line_cr_ids,
  310. 'payment_rate_currency_id': currency_id
  311. }
  312. account_voucher = request.env['account.voucher'].create(values)
  313. account_voucher.action_move_line_create()
  314. return account_voucher
  315. '''
  316. close invoice
  317. '''
  318. def close_invoice(self, invoiceid):
  319. invoice = request.env['account.invoice'].search([('id', '=', invoiceid)])
  320. if invoice.residual <= 0:
  321. invoice.write({
  322. 'state': 'paid'
  323. })
  324. # invoice.confirm_paid()
  325. return invoice
  326. '''
  327. Create bank Statement
  328. '''
  329. def create_bank_statement(self, date_server, user_id, account_voucher):
  330. # Get bank Statamente
  331. bank_statement = request.env['account.bank.statement'].search([('journal_id', '=', account_voucher.journal_id.id), ('date', '=', date_server)])
  332. # Create line bank
  333. bank_statement_line = [[0, False, {
  334. 'name': account_voucher.reference,
  335. 'partner_id': account_voucher.partner_id.id,
  336. 'amount': account_voucher.amount,
  337. 'voucher_id': account_voucher.id,
  338. 'journal_id': account_voucher.journal_id.id,
  339. 'account_id': account_voucher.account_id.id,
  340. 'journal_entry_id': account_voucher.move_id.id,
  341. 'currency_id': account_voucher.currency_id.id,
  342. 'ref': 'NP'
  343. }]]
  344. bank = {
  345. 'journal_id': account_voucher.journal_id.id,
  346. 'period_id': account_voucher.period_id.id,
  347. 'date': date_server,
  348. 'user_id': user_id,
  349. 'state': 'open' if account_voucher.journal_id.type == 'cash' else 'draft',
  350. 'line_ids': bank_statement_line
  351. }
  352. if bank_statement:
  353. if len(bank_statement) == 1:
  354. bank_statement.write(bank)
  355. else:
  356. bank_statement[len(bank_statement) -1].write(bank)
  357. else:
  358. bank_statement = bank_statement.create(bank)
  359. return bank_statement
  360. '''
  361. Payment process
  362. '''
  363. @http.route('/eiru_payments/payment_process', type='json', auth='user', methods=['POST'], cors='*')
  364. def payment_process(self, **kw):
  365. self.make_info_log('Processing payments...')
  366. # Get Date Server
  367. date_server = datetime.now().strftime(DATE_FORMAT)
  368. #Get Periodo
  369. period = self.get_period(date_server)
  370. self.make_info_log('[OK] Getting period')
  371. # Get invoice
  372. invoice = self.get_invoice(kw.get('invoiceId'))
  373. self.make_info_log('[OK] Getting invoice')
  374. # Get User - company
  375. user_id = request.env.user.id
  376. self.make_info_log('[OK] Getting user')
  377. # Get Company
  378. company_id = request.env.user.company_id.id
  379. self.make_info_log('[OK] Getting Company')
  380. # create voucher
  381. voucher = self.create_voucher(period, invoice, company_id, kw.get('amountPayments', 0), date_server, kw.get('journalId'), kw.get('moveLines'), kw.get('customerId'))
  382. self.make_info_log('[OK] creating voucher...')
  383. # close invoice
  384. close_invoice = self.close_invoice(kw.get('invoiceId'))
  385. self.make_info_log('[OK] closing invoice...')
  386. # Create bank statement
  387. bank_statement = self.create_bank_statement(date_server, user_id, voucher)
  388. self.make_info_log('[OK] creating bank statement')
  389. return {
  390. 'process': True
  391. }