123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527 |
- # -*- coding: utf-8 -*-
- from openerp import models, fields, tools, api
- from datetime import datetime
- from pytz import timezone
- import simplejson
- DATE_FORMAT = '%Y-%m-%d'
- class AccountInvoice(models.Model):
- _inherit = 'account.invoice'
- '''
- Get Move Line Customer
- '''
- def get_move_line_credit(self, invoice):
- decimal_precision = self.env['decimal.precision'].precision_get('Account')
- if (not invoice):
- return false
- return [{
- 'id': line.id,
- 'amountResidual': line.amount_residual,
- 'credit': line.credit,
- 'debit': line.debit,
- 'dateMaturity': line.date_maturity,
- 'invoice': invoice.id,
- 'amountCurrency': line.amount_currency if line.amount_currency > 0 else line.debit,
- 'amountResidualCurrency': line.amount_residual_currency,
- 'currencyAmount': [{
- 'id': currency.id,
- 'displayName': currency.display_name,
- 'symbol': currency.symbol,
- 'rateSilent': currency.rate_silent,
- 'rate': currency.rate,
- 'thousandsSeparator': currency.thousands_separator,
- 'decimalSeparator': currency.decimal_separator,
- 'decimalPlaces': currency.decimal_places,
- 'position': currency.position,
- 'base': currency.base,
- 'accuracy': currency.accuracy,
- 'rounding': currency.rounding,
- 'amountCurencyResidual': round((line.amount_residual_currency * (currency.rate_silent / invoice.currency_id.rate_silent)), decimal_precision)
- } for currency in self.env['res.currency'].search([('active', '=', True)])]
- } for line in invoice.move_id.line_id.sorted(key=lambda r: r.id) if (line.amount_residual > 0 and line.state != "draft" and line.credit <= 0)]
- '''
- Get Currency paymsntes
- '''
- @api.model
- def get_currency_payments_invoices(self):
- return [{
- 'id': currency.id,
- 'name': currency.name,
- 'symbol': currency.symbol,
- 'rate_silent': currency.rate_silent,
- 'base': currency.base,
- 'decimalSeparator': currency.decimal_separator,
- 'decimalPlaces': currency.decimal_places,
- 'thousandsSeparator': currency.thousands_separator,
- 'symbolPosition': currency.symbol_position,
- 'rate': currency.rate
- } for currency in self.env['res.currency'].search([('active','=', True)])]
- '''
- Get Move Line supplier
- '''
- def get_move_line_debit(self, invoice):
- decimal_precision = self.env['decimal.precision'].precision_get('Account')
- if (not invoice):
- return false
- return [{
- 'id': line.id,
- 'amountResidual': line.amount_residual,
- 'credit': line.credit,
- 'debit': line.debit,
- 'dateMaturity': line.date_maturity,
- 'invoice': invoice.id,
- 'amountCurrency': abs(line.amount_currency) if (abs(line.amount_currency) > 0) else line.credit,
- 'amountResidualCurrency': line.amount_residual_currency,
- 'currencyAmount': [{
- 'id': currency.id,
- 'displayName': currency.display_name,
- 'symbol': currency.symbol,
- 'rateSilent': currency.rate_silent,
- 'rate': currency.rate,
- 'thousandsSeparator': currency.thousands_separator,
- 'decimalSeparator': currency.decimal_separator,
- 'decimalPlaces': currency.decimal_places,
- 'position': currency.position,
- 'base': currency.base,
- 'accuracy': currency.accuracy,
- 'rounding': currency.rounding,
- 'amountCurencyResidual': round((line.amount_residual_currency * (currency.rate / invoice.currency_id.rate)), decimal_precision)
- } for currency in self.env['res.currency'].search([('active', '=', True)])]
- } for line in invoice.move_id.line_id.sorted(key=lambda r: r.id) if (line.amount_residual > 0 and line.state != "draft" and line.debit <= 0)]
- '''
- Get Move Line
- '''
- @api.model
- def get_moveline_invoice(self, id):
- accountInvoice = self.env['account.invoice'].browse(id)
- if (not accountInvoice):
- return False
- if (accountInvoice.type in ('out_invoice', 'in_refund')):
- return self.get_move_line_credit(accountInvoice)
- if (accountInvoice.type in ('out_refund', 'in_invoice')):
- return self.get_move_line_debit(accountInvoice)
- @api.model
- def get_bank_payments(self):
- resBankPayments = []
- for bankPayments in self.env['res.bank.payments'].search([('bank_payments_type_id.code', '!=', 'TJ')], order='id'):
- amountReceipt = 0
- amountPayment = 0
- amountBalance = 0
- amountCashed = 0
- amountRenegotiated = 0
- for line in bankPayments.payments_line:
- amountReceipt += line.type_operation in ('receipt') and line.amount or 0
- amountPayment += line.type_operation in ('payment') and line.amount or 0
- amountBalance += line.type_operation in ('balance') and line.amount or 0
- amountCashed += line.type_operation in ('cashed') and line.amount or 0
- amountRenegotiated += line.type_operation in ('renegotiated') and line.amount or 0
- resBankPayments.append({
- 'id': bankPayments.id,
- 'number': bankPayments.number,
- 'amountTotal': bankPayments.amount_total,
- 'dateMaturity': bankPayments.date_maturity,
- 'bankId': bankPayments.bank_id.id,
- 'bankPaymentsTypeId': bankPayments.bank_payments_type_id.id,
- 'numberCta': bankPayments.number_cta,
- 'nameHolder': bankPayments.name_holder,
- 'state': bankPayments.state,
- 'amountReceipt': amountReceipt,
- 'amountPayment': amountPayment,
- 'amountBalance': amountBalance,
- 'amountCashed': amountCashed,
- 'amountRenegotiated': amountRenegotiated,
- 'chequeTypeId': bankPayments.cheque_type_id.id
- });
- return resBankPayments
- '''
- Get User
- '''
- @api.model
- def get_user_login(self):
- return [{
- 'id': user.id,
- 'name': user.name
- } for user in self.env.user]
- '''
- get Statement
- '''
- @api.model
- def get_statement(self):
- BankStatement = []
- for statement in self.env['account.bank.statement'].search([('state','!=','confirm'),('user_id','=',self.env.user.id)]):
- if (statement.journal_id.type == 'cash' and statement.state =='draft'):
- continue
- BankStatement.append({
- 'id': statement.id,
- 'name': statement.name,
- 'journalID': statement.journal_id.id,
- 'userId': statement.user_id.id,
- 'date': statement.date,
- 'createDate': statement.create_date,
- 'periodId': statement.period_id.id,
- 'state': statement.state,
- 'journalType': statement.journal_id.type
- })
- return BankStatement
- '''
- Get All res_bank_payments_type.
- '''
- @api.model
- def get_bank_payment_type(self):
- self.env.cr.execute("SELECT id FROM res_bank_payments_type")
- return [{
- 'id': line.id,
- 'name': line.name,
- 'code': line.code,
- 'journal_ids': map(lambda x: x.id, line.journal_ids),
- 'allow_duplicate_operation': line.allow_duplicate_operation,
- 'fields_allowed': simplejson.loads(line.fields_allowed)
- }for line in self.env['res.bank.payments.type'].browse(map(lambda x: x['id'], self.env.cr.dictfetchall()))]
- '''
- GET account interest line
- '''
- @api.model
- def eiru_payments_account_interest_line(self,moveLine):
- return [{
- 'id': line.id,
- 'amountInterest': line.amount_interest,
- 'expiredDays': line.expired_days,
- 'state': line.state,
- 'moveLineId': line.move_line_id.id,
- 'invoice': [{
- 'id': accountInvoice.id,
- 'number': accountInvoice.number,
- 'state': accountInvoice.state,
- } for accountInvoice in self.env['account.invoice'].browse(line.invoice.id)],
- 'interest': [{
- 'id': line.interest_id.id,
- 'name': line.interest_id.name,
- 'state': line.interest_id.state,
- } for interest in self.env['account.interest'].browse(line.interest_id.id)],
- } for line in self.env['account.interest.line'].search([('move_line_id.id', 'in', moveLine)])]
- '''
- ____ ____ _
- / ___| __ ___ _____ | _ \ __ _ _ _ _ __ ___ ___ _ __ | |_ ___
- \___ \ / _` \ \ / / _ \ | |_) / _` | | | | '_ ` _ \ / _ \ '_ \| __/ __|
- ___) | (_| |\ V / __/ | __/ (_| | |_| | | | | | | __/ | | | |_\__ \
- |____/ \__,_| \_/ \___| |_| \__,_|\__, |_| |_| |_|\___|_| |_|\__|___/
- |___/
- '''
- '''
- check_module Installed
- '''
- def check_module(self, module_name):
- '''
- Método para verificar si los modulo están instalado
- :param module_name : Nombre del moduloself.
- :return: True 'Modulo instalado', False 'no instalado'
- '''
- module = self.env['ir.module.module'].search([('name', '=', module_name), ('state', '=', 'installed')])
- return len(module) != 0
- '''
- Get invoice
- '''
- def get_invoice(self, invoiceId):
- return self.env['account.invoice'].browse(invoiceId)
- '''
- Get Period
- '''
- def get_period(self, date_server):
- return self.env['account.period'].search([('date_start','<=', date_server), ('date_stop', '>=', date_server)])
- '''
- Get timezone
- '''
- def get_timezone(self):
- tz_name = self._context.get('tz') or self.env.user.tz
- return timezone(tz_name)
- '''
- Get server date
- '''
- def get_server_datetime(self):
- return datetime.now(self.get_timezone()).strftime(DATE_FORMAT)
- '''
- get Statement Config
- '''
- def getStatementConfig(self, id):
- return self.env['account.bank.statement.config'].browse(id)
- '''
- Create Voucher
- '''
- def create_voucher_invoice(self, period, invoice, company_id, amountPayments, date_server, journalId, move_line_Ids, customerId, voucherName, voucherObs, voucherSeq):
- ## Get Journal
- journal_id = self.env['account.journal'].browse(int(journalId))
- currency_id = journal_id.default_credit_account_id.currency_id.id or journal_id.default_credit_account_id.company_currency_id.id
- # Get Move Lines
- move_line = self.env['account.move.line'].browse(move_line_Ids).sorted(key=lambda r: r.id)
- ### res.partner
- customerId = self.env['res.partner']._find_accounting_partner(invoice.partner_id)
- ### decimal.precision
- decimal_precision = self.env['decimal.precision'].precision_get('Account')
- ### Currencies (company/ Journal)
- company_currency = self.env.user.company_id.currency_id
- currencyVocuher = self.env['res.currency'].browse(currency_id)
- ### Create Line Voucher 'seq_invoice': invoice.seq_invoice
- line_ids = []
- amount = round(float(amountPayments), decimal_precision)
- for line in move_line:
- amount_residual = line.amount_residual
- if (company_currency.id != currencyVocuher.id):
- amount_residual = round((amount_residual * (currencyVocuher.rate / company_currency.rate)), decimal_precision)
- line_ids.append([0, False, {
- 'date_due': line.date_maturity,
- 'account_id': line.account_id.id,
- 'date_original': line.move_id.date,
- 'move_line_id': line.id,
- 'amount_original': abs(line.credit or line.debit or 0.0),
- 'amount_unreconciled': abs(line.amount_residual),
- 'amount': min(abs(amount), abs(amount_residual)),
- 'reconcile': True if abs(amount_residual) == min(abs(amount), abs(amount_residual)) else False,
- 'currency_id': currency_id
- }])
- amount -= min(abs(amount), amount_residual)
- amountResidual = round(float(amountPayments), decimal_precision)
- values = {
- 'name': voucherName,
- 'reference': invoice.number,
- 'type': invoice.type in ('out_invoice','out_refund') and 'receipt' or 'payment',
- 'journal_id': journal_id.id,
- 'company_id': company_id,
- 'pre_line': True,
- 'amount': invoice.type in ('out_refund', 'in_refund') and -amountResidual or amountResidual,
- 'period_id': period.id,
- 'date': date_server,
- 'partner_id': customerId.id,
- 'account_id': journal_id.default_credit_account_id.id,
- 'currency_id': currency_id,
- 'line_cr_ids': invoice.type in ('out_invoice', 'in_refund') and line_ids or [],
- 'line_dr_ids': invoice.type in ('out_refund', 'in_invoice') and line_ids or [],
- 'payment_rate_currency_id': currency_id,
- 'comment_obs': voucherObs,
- 'seq_invoice': voucherSeq
- }
- account_voucher = self.env['account.voucher'].create(values)
- account_voucher.action_move_line_create()
- if (not account_voucher.name):
- account_voucher.write({'name': account_voucher.number})
- return account_voucher
- '''
- Change State invoice
- '''
- def close_status_invoice(self, invoiceid):
- invoice = self.env['account.invoice'].search([('id', '=', invoiceid)])
- if invoice.residual <= 0:
- invoice.confirm_paid()
- return invoice
- '''
- Create bank Statement
- '''
- def create_bank_statement(self, date_server, user_id, account_voucher, statementId):
- domain = [('journal_id', '=', account_voucher.journal_id.id),('user_id', '=', user_id)]
- if (statementId):
- domain.append(('id', '=', statementId))
- else:
- domain.append(('date', '=', date_server))
- bank_statement = self.env['account.bank.statement'].search(domain)
- bank = {
- 'journal_id': account_voucher.journal_id.id,
- 'period_id': account_voucher.period_id.id,
- 'date': date_server,
- 'user_id': user_id,
- 'state': 'open' if account_voucher.journal_id.type == 'cash' else 'draft',
- }
- bankStatement = bank_statement
- if bank_statement:
- if len(bank_statement) != 1:
- bankStatement = bank_statement[len(bank_statement) -1]
- bankStatement.button_open()
- else:
- bankStatement = bank_statement.create(bank)
- return bankStatement
- '''
- Create Statamente Line
- '''
- def create_bank_statement_line(self, account_voucher, statement):
- ### Create line bank
- bank_statement_line = {
- 'name': account_voucher.reference,
- 'partner_id': account_voucher.partner_id.id,
- 'amount': account_voucher.type in ('payment') and -account_voucher.amount or account_voucher.amount,
- 'voucher_id': account_voucher.id,
- 'journal_id': account_voucher.journal_id.id,
- 'account_id': account_voucher.account_id.id,
- 'journal_entry_id': account_voucher.move_id.id,
- 'currency_id': account_voucher.currency_id.id,
- 'ref': 'NP',
- 'statement_id': statement.id
- }
- line_id = self.env['account.bank.statement.line'].create(bank_statement_line)
- return line_id
- '''
- Bank Line
- '''
- def create_bank_paymnets(self, account_voucher, date_server, invoice, bankPayments):
- bankId = []
- bankPaymentsType = []
- bankChequeType = []
- amountTotal = 0
- for valor in bankPayments:
- if (valor == 'bank_id'):
- bankId = self.env['res.bank'].browse(bankPayments[valor])
- if (valor == 'bank_payments_type_id'):
- bankPaymentsType = self.env['res.bank.payments.type'].browse(bankPayments[valor])
- if (valor == 'cheque_type_id'):
- bankChequeType = self.env['res.bank.cheque.type'].browse(bankPayments[valor])
- if(valor == 'amount_total'):
- amountTotal = bankPayments[valor]
- bankPayments['date'] = date_server
- bankPayments['state'] = bankPaymentsType.default_state
- bankPayments['comment'] = 'Np'
- bankPayments['currency_id'] = account_voucher.currency_id.id
- bankPayments['customer_id'] = invoice.type in ('out_invoice','in_refund') and account_voucher.partner_id.id or ''
- bankPayments['supplier_id'] = invoice.type in ('in_invoice','out_refund') and account_voucher.partner_id.id or ''
- bankPayments['amount_total'] = amountTotal if (amountTotal > 0) else account_voucher.amount
- paymnets_bank = []
- if (not bankPaymentsType.allow_duplicate_operation):
- try:
- number = bankPayments['number']
- numberCta = bankPayments['number_cta']
- except Exception as e:
- number = None
- numberCta = None
- paymnets_bank = self.env['res.bank.payments'].search([ ('number', '=', number), ('bank_id', '=', bankId.id), ('number_cta', '=', numberCta)])
- if (paymnets_bank):
- bankPayments = []
- # ventas/rectific. compras/gastos
- if (invoice.type in ('out_invoice','in_refund')):
- bankPayments = {
- 'partner_id': invoice.type in ('out_invoice','in_refund') and account_voucher.partner_id.id or ''
- }
- ## Compras/gastos/rectific. ventas
- if (invoice.type in ('in_invoice','out_refund')):
- bankPayments = {
- 'supplier_id': invoice.type in ('in_invoice','out_refund') and account_voucher.partner_id.id or ''
- }
- if (bankPayments):
- paymnets_bank.write(bankPayments)
- else:
- paymnets_bank = self.env['res.bank.payments'].create(bankPayments)
- return paymnets_bank
- '''
- Create Bnak Paymnets Line
- '''
- def create_bank_paymnets_line(self, voucher, bank_payments, bank_statement_line, bank_statement, date_server, invoice):
- account_voucher = self.env['account.voucher'].browse(voucher.id)
- res_bank_payments = self.env['res.bank.payments'].browse(bank_payments.id)
- statement_line = self.env['account.bank.statement.line'].browse(bank_statement_line.id)
- statement = self.env['account.bank.statement'].browse(bank_statement.id)
- bank_line = {
- 'amount': abs(account_voucher.amount) ,
- 'date': date_server,
- 'bank_payments_id': res_bank_payments.id,
- 'statement_line_id': bank_statement_line.id,
- 'statement_id': bank_statement.id,
- 'type_operation': invoice.type in ('out_invoice','in_refund') and 'receipt' or 'payment',
- 'amount_currency' : 0.00,
- 'currency_id' : account_voucher.currency_id.id
- }
- paymnets_line = self.env['res.bank.payments.line'].create(bank_line)
- return paymnets_line
- '''
- Save payments
- '''
- @api.model
- def save_payments_invoice(self, values):
- ## Date Server
- date_server = self.get_server_datetime()
- ### Usuer
- resUser = self.env.user.id
- ### Compania
- resCompany = self.env.user.company_id.id
- ### Invoice
- accountInvoice = self.get_invoice(values['invoiceId'])
- if (not accountInvoice):
- return False
- ### Period
- accountPeriod = self.get_period(date_server)
- if (not accountPeriod):
- return False
- ### Create.
- ##### Vocuher.
- voucher = self.create_voucher_invoice(accountPeriod, accountInvoice, resCompany, values['amountPayments'], values['datePayments'], values['JournalId'], values['moveLines'], values['partnerId'], values['voucherName'], values['voucherObs'], values['voucherSeq'])
- ### Close invoice.
- closeInvoice = self.close_status_invoice(values['invoiceId'])
- ### Create bank Statement
- bank_statement = self.create_bank_statement(date_server, resUser, voucher, values['statementId'])
- ### Create bank statement Line
- bank_statement_line = self.create_bank_statement_line(voucher, bank_statement)
- ### Verify Type Operations 'journal_ids'
- if ((self.check_module('eiru_bank_payments_references')) and (values['JournalType'] == 'bank') and (values['bankPayments'])):
- typeOperation = self.env['res.bank.payments.type'].search(([('journal_ids', 'in', values['JournalId'])]))
- if (typeOperation):
- bank_payments = self.create_bank_paymnets(voucher, date_server, accountInvoice, values['bankPayments'])
- bank_payments_Line = self.create_bank_paymnets_line(voucher, bank_payments, bank_statement_line, bank_statement, date_server, accountInvoice)
- return {
- 'process': True
- }
|