Advertisement
Guest User

modificado

a guest
Jun 22nd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 28.52 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from openerp import api, fields, models, _
  4. import logging
  5. from BeautifulSoup import BeautifulSoup
  6. import subprocess
  7. import urllib, urllib2
  8. from urllib import urlencode
  9. import openerp.addons.decimal_precision as dp
  10. import re
  11. from openerp.tools import DEFAULT_SERVER_DATE_FORMAT
  12. from httplib2 import Http
  13. import logging
  14. import sys
  15.  
  16. #Generacion del QR
  17. import qrcode
  18. import tempfile
  19. import base64
  20.  
  21. #Convertir numeros en texto
  22. import rm_amount_to_text_es
  23.  
  24. import time
  25. from time import mktime
  26. from datetime import date
  27. from datetime import datetime, timedelta
  28. from openerp import SUPERUSER_ID
  29. from openerp.exceptions import UserError
  30. _logger = logging.getLogger(__name__)
  31. class account_invoice(models.Model):
  32.     _inherit = 'account.invoice'
  33.  
  34.     # Al momento de Validar la factura, se realiza la generacion del Numero de Factura y el codigo de control.
  35.     @api.multi
  36.     def invoice_validate(self):
  37.         if self.type == "out_invoice": # solo calcular codigo de control cuando sean facturas de cliente
  38.             for invoice in self:
  39.                 #refuse to validate a vendor bill/refund if there already exists one with the same reference for the same partner,
  40.                 #because it's probably a double encoding of the same bill/refund
  41.                 if invoice.type in ('in_invoice', 'in_refund') and invoice.reference:
  42.                     if self.search([('type', '=', invoice.type), ('reference', '=', invoice.reference), ('company_id', '=', invoice.company_id.id), ('commercial_partner_id', '=', invoice.commercial_partner_id.id), ('id', '!=', invoice.id)]):
  43.                         raise UserError(_("Duplicated vendor reference detected. You probably encoded twice the same vendor bill/refund."))
  44.             tax_flag = 0
  45.             for invoice in self:
  46.                 import time
  47.                 from datetime import datetime, timedelta,date
  48.                 from time import mktime
  49.                 # fecha limite de emision
  50.                 qr = self.env['pos.order'].search([('invoice_id', '=', invoice.id)])
  51.                 if not qr.session_id.config_id.qr_code_id:
  52.                     raise UserError(_('Asigne una dosificacion al punto de venta' + qr.session_id.config_id.name))
  53.                 pos_config = qr.session_id.config_id
  54.                 qr = qr.session_id.config_id.qr_code_id
  55.                 if not qr.activo:
  56.                     raise UserError(_('Active una dosificacion para habilitar facturacion'))
  57.                 if (qr.fecha_limite_emision):
  58.                     fecha_actual = datetime.strptime((datetime.now() - timedelta(hours = 4)).strftime('%d%m%Y'), "%d%m%Y").date()
  59.                     fecha_actual2 = datetime.strptime(qr.fecha_limite_emision, '%Y-%m-%d').strftime('%d%m%Y')
  60.                     fecha_actual2 = datetime.strptime(fecha_actual2, "%d%m%Y").date()
  61.                     if fecha_actual > fecha_actual2:
  62.                         raise UserError(_('La fecha limite de EMISION a caducado, notifique a su contador'))
  63.  
  64.                     # Obtener la dosificacion asignada para el POS y grabarla en la factura
  65.                     if invoice.origin:
  66.  
  67.                         pos_order = self.env['pos.order'].search([('invoice_id','=',invoice.id)], limit=1)
  68.                         numero_comanda = ((pos_order.pos_reference).replace('-', ' ')).split()
  69.                         numero_comanda = int(numero_comanda[len(numero_comanda)-1])
  70.                         if numero_comanda:
  71.                             self.env.cr.execute("UPDATE account_invoice SET numero_autorizacion="+str(qr.numero_autorizacion)+", qr_code_id=" + str(qr.id) + ", razon_social='"+ str((invoice.partner_id.razon_social or 'SN').encode("utf-8") or 'S/N')+ "', nit='"+str(invoice.partner_id.nit or '0') + "', numero_comanda='"+str(numero_comanda)+"' WHERE id="+str(invoice.id))
  72.  
  73.                     # Valida si la factura no es rectificada, tiene impuestos, si ha sido pagada o Validada.
  74.                     for inv_line in invoice.invoice_line_ids:
  75.                         if inv_line.invoice_line_tax_ids:
  76.                             tax_flag = 1
  77.                         else:
  78.                             tax_flag = 0
  79.                             # raise UserError(_('Error.\n Registre impuestos al producto '+str(inv_line.product_id.name)))
  80.                             invoice.write({'order_status': 'no_utilizada'})
  81.                             # raise osv.except_osv(_('Warning'),_('Entered Quantity is greater than quantity on source.'))
  82.                             # sys.exit("Configure los impuestos por defecto, en categorias o directamente en los productos.")
  83.                     if (tax_flag == 1) & (invoice.type != 'out_refund'):
  84.                         invoice_search = self.env['account.invoice'].search(
  85.                                         [('qr_code_id.numero_autorizacion','=',qr.numero_autorizacion),
  86.                                         ('qr_code_id','=',qr.id),
  87.                                         ('id','!=',invoice.id),
  88.                                         ('invoice_number','!=','')
  89.                                         ])
  90.                         # Genera un nuevo numero de factura
  91.                         numero_duplicado = self.env['account.invoice'].search([('qr_code_id','=',qr.id),('invoice_number','=',invoice.invoice_number or -1)])
  92.                         if not numero_duplicado:
  93.                             invoice.write({'invoice_number': len(invoice_search) + 1})
  94.                         else:
  95.                             raise UserError(_("El numero de factura intenta duplicarse, por favor comuniquece con su Administrador de Sistemas"))
  96.                         # Generando Codigo de Control
  97.                         fecha_actual = invoice.create_date
  98.                         struct_time_convert = time.strptime(fecha_actual, '%Y-%m-%d %H:%M:%S')
  99.                         date_time_convert = datetime.fromtimestamp(mktime(struct_time_convert))
  100.                         date_time_convert = date_time_convert - timedelta(hours = 4)
  101.                         fecha = date_time_convert.strftime('%Y%m%d')
  102.                         # date = datetime.datetime.strptime(invoice.date_invoice, DEFAULT_SERVER_DATE_FORMAT).strftime('%Y%m%d')
  103.                         h = Http()
  104.  
  105.                         # Verificar si el NIT es texto o invalido y asignar 0
  106.                         # if (isinstance(invoice.nit, basestring)):
  107.                         if (invoice.nit == ''):
  108.                             invoice.write({'nit': '0'})
  109.  
  110.                         url_data = dict(AUTH_NUMBER=int(qr.numero_autorizacion),INVOICE_NUMBER=int(invoice.invoice_number),NIT_CODE_CUSTOMER=str(invoice.nit),DATE=int(fecha),AMOUNT=invoice.amount_total,KEYGEN=str(qr.llave_dosificacion))
  111.                         url= urlencode(url_data)
  112.                         # resp = urllib2.urlopen('http://odoo.romilax.com/cc/codigo_control.php?'+url)
  113.                         resp = urllib2.urlopen('http://'+pos_config.rm_url_bd+'/cc/codigo_control.php?'+url)
  114.                         soup = BeautifulSoup(resp)
  115.                         if len(str(soup)) <= 20:
  116.                             invoice.write({'control_code': str(soup) or '', 'state': 'open'})
  117.                         else:
  118.                             raise UserError(_('El codigo de control no fue generado correctamente, Contacte con su Administrador de Sistemas'))
  119.                     else:
  120.                         # raise UserError(_('Error.\nPor favor registre impuestos a los productos'))
  121.                         invoice.write({'invoice_number': 0})
  122.  
  123.     @api.multi
  124.     def action_move_create(self):
  125.         """ Creates invoice related analytics and financial move lines """
  126.         # account_move = self.env['account.move']
  127.  
  128.         for inv in self:
  129.             # if not inv.journal_id.sequence_id:
  130.             #     raise UserError(_('Please define sequence on the journal related to this invoice.'))
  131.             if not inv.invoice_line_ids:
  132.                 raise UserError(_('Please create some invoice lines.'))
  133.             if inv.move_id:
  134.                 continue
  135.  
  136.             ctx = dict(self._context, lang=inv.partner_id.lang)
  137.  
  138.             if not inv.date_invoice:
  139.                 inv.with_context(ctx).write({'date_invoice': fields.Date.context_today(self)})
  140.             date_invoice = inv.date_invoice
  141.             company_currency = inv.company_id.currency_id
  142.  
  143.             # create move lines (one per invoice line + eventual taxes and analytic lines)
  144.             iml = inv.invoice_line_move_line_get()
  145.             iml += inv.tax_line_move_line_get()
  146.  
  147.             # diff_currency = inv.currency_id != company_currency
  148.             # create one move line for the total and possibly adjust the other lines amount
  149.             total, total_currency, iml = inv.with_context(ctx).compute_invoice_totals(company_currency, iml)
  150.  
  151.             # name = inv.name or '/'
  152.             # if inv.payment_term_id:
  153.             #     totlines = inv.with_context(ctx).payment_term_id.with_context(currency_id=company_currency.id).compute(total, date_invoice)[0]
  154.             #     res_amount_currency = total_currency
  155.             #     ctx['date'] = date_invoice
  156.             #     for i, t in enumerate(totlines):
  157.             #         if inv.currency_id != company_currency:
  158.             #             amount_currency = company_currency.with_context(ctx).compute(t[1], inv.currency_id)
  159.             #         else:
  160.             #             amount_currency = False
  161.  
  162.             #         # last line: add the diff
  163.             #         res_amount_currency -= amount_currency or 0
  164.             #         if i + 1 == len(totlines):
  165.             #             amount_currency += res_amount_currency
  166.  
  167.             #         iml.append({
  168.             #             'type': 'dest',
  169.             #             'name': name,
  170.             #             'price': t[1],
  171.             #             'account_id': inv.account_id.id,
  172.             #             'date_maturity': t[0],
  173.             #             'amount_currency': diff_currency and amount_currency,
  174.             #             'currency_id': diff_currency and inv.currency_id.id,
  175.             #             'invoice_id': inv.id
  176.             #         })
  177.             # else:
  178.             #     iml.append({
  179.             #         'type': 'dest',
  180.             #         'name': name,
  181.             #         'price': total,
  182.             #         'account_id': inv.account_id.id,
  183.             #         'date_maturity': inv.date_due,
  184.             #         'amount_currency': diff_currency and total_currency,
  185.             #         'currency_id': diff_currency and inv.currency_id.id,
  186.             #         'invoice_id': inv.id
  187.             #     })
  188.             # part = self.env['res.partner']._find_accounting_partner(inv.partner_id)
  189.             # line = [(0, 0, self.line_get_convert(l, part.id)) for l in iml]
  190.             # line = inv.group_lines(iml, line)
  191.  
  192.             # journal = inv.journal_id.with_context(ctx)
  193.             # line = inv.finalize_invoice_move_lines(line)
  194.  
  195.             date = inv.date or date_invoice
  196.             # move_vals = {
  197.             #     'ref': inv.reference,
  198.             #     'line_ids': line,
  199.             #     'journal_id': journal.id,
  200.             #     'date': date,
  201.             #     'narration': inv.comment,
  202.             # }
  203.             # ctx['company_id'] = inv.company_id.id
  204.             # ctx['dont_create_taxes'] = True
  205.             # ctx['invoice'] = inv
  206.             # ctx_nolang = ctx.copy()
  207.             # ctx_nolang.pop('lang', None)
  208.             # move = account_move.with_context(ctx_nolang).create(move_vals)
  209.             # Pass invoice in context in method post: used if you want to get the same
  210.             # account move reference when creating the same invoice after a cancelled one:
  211.             # move.post()
  212.             # make the invoice point to that move
  213.             vals = {
  214.                 # 'move_id': move.id,
  215.                 'date': date,
  216.                 # 'move_name': move.name,
  217.             }
  218.             inv.with_context(ctx).write(vals)
  219.         return True
  220.  
  221.     # Generar el QR
  222.     def _cambiar_mes(self,mes):
  223.         mes_traducido = ''
  224.         if mes == '01': mes_traducido = 'Enero'
  225.         if mes == '02': mes_traducido = 'Febrero'
  226.         if mes == '03': mes_traducido = 'Marzo'
  227.         if mes == '04': mes_traducido = 'Abril'
  228.         if mes == '05': mes_traducido = 'Mayo'
  229.         if mes == '06': mes_traducido = 'Junio'
  230.         if mes == '07': mes_traducido = 'Julio'
  231.         if mes == '08': mes_traducido = 'Agosto'
  232.         if mes == '09': mes_traducido = 'Septiembre'
  233.         if mes == '10': mes_traducido = 'Octubre'
  234.         if mes == '11': mes_traducido = 'Noviembre'
  235.         if mes == '12': mes_traducido = 'Diciembre'
  236.         return mes_traducido
  237.  
  238.     # Funcion para Obtener la fecha con mes textual
  239.     def convertir_mes_fecha(self, fecha):
  240.         fecha_actual = fecha
  241.         struct_time_convert = time.strptime(fecha_actual, '%Y-%m-%d')
  242.         date_time_convert = datetime.fromtimestamp(mktime(struct_time_convert))
  243.         fecha_actual = date_time_convert.strftime('%d') + " de " + self._cambiar_mes(date_time_convert.strftime('%m')) + " del " + date_time_convert.strftime('%Y')
  244.         return fecha_actual
  245.  
  246.     @api.multi
  247.     def _get_qr_code(self):
  248.         if self:
  249.             qr_code_ids = self.env['account.invoice'].search([('qr_code_id', 'in', self.ids)])
  250.             return qr_code_ids.ids
  251.  
  252.     # Obtener las lineas de la factura
  253.     def _get_invoice_line(self, cr, uid, ids, context=None):
  254.         result = {}
  255.         for line in self.pool.get('account.invoice.line').browse(cr, uid, ids, context=context):
  256.             result[line.invoice_id.id] = True
  257.         return result.keys()
  258.  
  259.     # Funcion para Factura QR
  260.     def convertir_numero_a_literal(self, amount):
  261.         amt_en = rm_amount_to_text_es.amount_to_text(amount, 'BOB')
  262.         return amt_en
  263.     # Detalle de productos con Tipo de Venta y comentario desde pos.order
  264.     # obtener detalle pedido
  265.     def get_habilidar_numero_pedido(self):
  266.         pos_config = self.pool.get('pos.config')
  267.         pos_config_search = pos_config.search(self.env.cr, self.env.uid, [('create_uid','=',SUPERUSER_ID)])
  268.         pos_config_browse =  pos_config.browse(self.env.cr, self.env.uid, pos_config_search)[0]
  269.         return pos_config_browse.habilitar_numero_pedido
  270.  
  271.     def get_detalle_pedido(self,cr, order_id):
  272.         variable = int(order_id.id)
  273.         detalle_pedido=[]
  274.         sql = """ SELECT
  275.                    pos_order_line.qty,
  276.                    product_product.name_template,
  277.                    pos_order_line.tipo_venta,
  278.                    pos_order_line.note,
  279.                    pos_order.invoice_id
  280.                    FROM
  281.                    pos_order
  282.                    INNER JOIN pos_order_line ON pos_order_line.order_id = pos_order.id
  283.                    INNER JOIN product_product ON pos_order_line.product_id = product_product.id
  284.                    WHERE pos_order_line.qty > 0
  285.                    AND pos_order.invoice_id ='%s' ORDER by pos_order_line.id  """%(variable)
  286.         cr.execute(sql)
  287.         res = cr.dictfetchall()
  288.         for r in res:
  289.             detalle_pedido.append(r)
  290.         return detalle_pedido
  291.  
  292.     # Tipo de comanda
  293.     def get_tipo_comanda(self,cr, order_id):
  294.         variable = int(order_id.id)
  295.         tipo_comanda=[]
  296.         sql = """ SELECT
  297.                    pos_config.tipo_comanda
  298.                    FROM
  299.                    pos_order
  300.                    INNER JOIN pos_session ON pos_order.session_id = pos_session.id
  301.                    INNER JOIN pos_config ON pos_session.config_id = pos_config.id
  302.                    WHERE
  303.                    pos_order.invoice_id ='%s' """%(variable)
  304.         cr.execute(sql)
  305.         res = cr.dictfetchall()
  306.         for r in res:
  307.             tipo_comanda.append(r)
  308.         if tipo_comanda:
  309.             return tipo_comanda[0]['tipo_comanda']
  310.         else:
  311.             return 'sin_comanda'
  312.  
  313.     # Solo comanda en recibo
  314.     def get_solo_comanda_en_recibo(self,cr, order_id):
  315.         variable = int(order_id.id)
  316.  
  317.         solo_comanda_en_recibo=[]
  318.         sql = """ SELECT
  319.                    pos_config.solo_comanda_en_recibo
  320.                    FROM
  321.                    pos_order
  322.                    INNER JOIN pos_session ON pos_order.session_id = pos_session.id
  323.                    INNER JOIN pos_config ON pos_session.config_id = pos_config.id
  324.                    WHERE
  325.                    pos_order.invoice_id ='%s' """%(variable)
  326.         cr.execute(sql)
  327.         res = cr.dictfetchall()
  328.         for r in res:
  329.             solo_comanda_en_recibo.append(r)
  330.         if solo_comanda_en_recibo:
  331.             return solo_comanda_en_recibo[0]['solo_comanda_en_recibo']
  332.         else:
  333.             return False
  334.  
  335.     # Factura con pedido
  336.     def get_factura_con_pedido(self,cr, order_id):
  337.         variable = int(order_id.id)
  338.         factura_con_pedido=[]
  339.         sql = """ SELECT
  340.                    pos_config.factura_con_pedido
  341.                    FROM
  342.                    pos_order
  343.                    INNER JOIN pos_session ON pos_order.session_id = pos_session.id
  344.                    INNER JOIN pos_config ON pos_session.config_id = pos_config.id
  345.                    WHERE
  346.                    pos_order.invoice_id ='%s' """%(variable)
  347.         cr.execute(sql)
  348.         res = cr.dictfetchall()
  349.         for r in res:
  350.             factura_con_pedido.append(r)
  351.         if factura_con_pedido:
  352.             return factura_con_pedido[0]['factura_con_pedido']
  353.         else:
  354.             return False
  355.  
  356.     # Numero de pedido o factura impreso en la comanda de factura
  357.     def get_numero_comanda(self,cr, order_id):
  358.         variable = int(order_id.id)
  359.         tipo_comanda=[]
  360.         sql = """ SELECT
  361.                    pos_config.numero_comanda_factura
  362.                    FROM
  363.                    pos_order
  364.                    INNER JOIN pos_session ON pos_order.session_id = pos_session.id
  365.                    INNER JOIN pos_config ON pos_session.config_id = pos_config.id
  366.                    WHERE
  367.                    pos_order.invoice_id ='%s' """%(variable)
  368.         cr.execute(sql)
  369.         res = cr.dictfetchall()
  370.         for r in res:
  371.             tipo_comanda.append(r)
  372.         if tipo_comanda:
  373.             return tipo_comanda[0]['numero_comanda_factura']
  374.         else:
  375.             return 'sin_comanda'
  376.  
  377.     def get_omitir_categoria_producto(self,cr,order_id):
  378.         variable = int(order_id.id)
  379.         tipo_comanda=[]
  380.         sql = """ SELECT
  381.                    pos_config.omitir_categoria_factura
  382.                    FROM
  383.                    pos_order
  384.                    INNER JOIN pos_session ON pos_order.session_id = pos_session.id
  385.                    INNER JOIN pos_config ON pos_session.config_id = pos_config.id
  386.                    WHERE
  387.                    pos_order.invoice_id ='%s' """%(variable)
  388.         cr.execute(sql)
  389.         res = [x[0] for x in cr.fetchall()]
  390.         if res: return False
  391.         else: return True
  392.  
  393.     # Categorias de la Factura
  394.     def get_categorias(self, order_id):
  395.         variable = int(order_id.id)
  396.         categorias=[]
  397.         sql = """ SELECT
  398.                    pos_category.id
  399.                    ,pos_category.name
  400.                    ,SUM(pos_order_line.qty) as qty
  401.                    ,product_product.name_template
  402.                    ,pos_order_line.tipo_venta
  403.                    ,pos_order_line.note
  404.                    FROM
  405.                    pos_order
  406.                    INNER JOIN pos_order_line ON pos_order_line.order_id = pos_order.id
  407.                    INNER JOIN product_product ON pos_order_line.product_id = product_product.id
  408.                    INNER JOIN product_template ON product_product.product_tmpl_id = product_template.id
  409.                    INNER JOIN pos_category ON product_template.pos_categ_id = pos_category.id
  410.                    WHERE
  411.                    pos_order.invoice_id = %s
  412.                    GROUP BY 1,2,4,5,6
  413.                    ORDER BY 1;"""%(variable)
  414.         self.env.cr.execute(sql)
  415.         res = self.env.cr.dictfetchall()
  416.         codigo = 0
  417.         cont = x = 0
  418.         nomrbe = ''
  419.         datos = []
  420.         for r in res:
  421.             if int(r['qty']) > 0:
  422.                 if r['id'] == codigo:
  423.                     vals = {
  424.                     'qty' : r['qty'],
  425.                     'name_template' : r['name_template'],
  426.                     'tipo_venta' : r['tipo_venta'],
  427.                     'note' : r['note']
  428.                     }
  429.                     datos.append(vals)
  430.                 else:
  431.                     if x != 0:
  432.                         categorias.append((codigo,nombre,datos))
  433.                     x = 1
  434.                     datos = []
  435.                     vals = {
  436.                     'qty' : r['qty'],
  437.                     'name_template' : r['name_template'],
  438.                     'tipo_venta' : r['tipo_venta'],
  439.                     'note' : r['note']
  440.                     }
  441.                     datos.append(vals)
  442.                 codigo = r['id']
  443.                 nombre = r['name']
  444.  
  445.             cont += 1
  446.             if len(res) == cont:
  447.                 categorias.append((r['id'],r['name'],datos))
  448.         return categorias
  449.  
  450.     # Funcion para Factura QR, cambio del efectivo
  451.     def obtener_pago_pos(self, cr, order_id):
  452.         data={}
  453.         sql = """ select aj.name,absl.amount as amt from account_bank_statement as abs
  454.                        LEFT JOIN account_bank_statement_line as absl ON abs.id = absl.statement_id
  455.                        LEFT JOIN account_journal as aj ON aj.id = abs.journal_id
  456.                        WHERE absl.pos_statement_id =%d ORDER by absl.amount DESC"""%(order_id)
  457.         cr.execute(sql)
  458.         data = cr.dictfetchall()
  459.         return data
  460.  
  461.     def numero_impresion(self,cr,invoice):
  462.         cr.execute("SELECT rm_numero_impresion FROM account_invoice WHERE id = "+str(invoice.id))
  463.         numero = cr.fetchone()[0]
  464.         cr.execute("UPDATE account_invoice SET rm_numero_impresion=%s WHERE id=%s",([numero+1,invoice.id]))
  465.         cr.execute("SELECT rm_numero_impresion FROM account_invoice WHERE id = "+str(invoice.id))
  466.         numero = cr.fetchone()[0]
  467.         return numero
  468.  
  469.     @api.multi
  470.     def invoice_print(self):
  471.         """ Print the invoice and mark it as sent, so that we can see more
  472.            easily the next step of the workflow
  473.        """
  474.         self.ensure_one()
  475.         self.sent = True
  476.         invoice = self.env['account.invoice'].browse(0)
  477.         invoice += self
  478.         config = self.env['pos.config'].search([('iface_invoicing','=',True),('state','=','active')],limit=1)
  479.         if config.factura_con_copia:
  480.             invoice += self
  481.         return self.env['report'].get_action(invoice, 'account.report_invoice')
  482.  
  483.     # Obtener el pedido de venta
  484.     def obtener_pedido_id(self, cr, origen):
  485.         pedido=[]
  486.         sql = """ SELECT
  487.                    pos_order.id
  488.                    FROM
  489.                    pos_order
  490.                    WHERE
  491.                    pos_order.name ='%s' """%(origen)
  492.         cr.execute(sql)
  493.         res = cr.dictfetchall()
  494.         for r in res:
  495.             pedido.append(r)
  496.         if pedido:
  497.             return pedido[0]['id']
  498.         else:
  499.             return 0
  500.  
  501.     def get_mesero(self,cr, order_id):
  502.         detalle_pedido=[]
  503.         sql = """ SELECT
  504.                    rp1.name
  505.                    FROM
  506.                    pos_order
  507.                    LEFT JOIN res_users ru1 ON ru1.id=pos_order.mesero
  508.                    LEFT JOIN res_partner rp1 ON rp1.id=ru1.partner_id
  509.                    WHERE pos_order.invoice_id = """ + str(order_id.id)
  510.         cr.execute(sql)
  511.         res = [i for i in cr.fetchall()]
  512.         if res[0] in ['None',None,False,'']:
  513.             return False
  514.         return res[0][0]
  515.  
  516.  
  517.     # Obtener Imagen QR para la Factura
  518.     def get_qrcode(self, nit_empresa, invoice_number, numero_autorizacion, fecha_factura, amount_total, impuestos, control_code, nit_cliente):
  519.         fecha_actual = fecha_factura
  520.         struct_time_convert = time.strptime(fecha_actual, '%Y-%m-%d %H:%M:%S')
  521.         date_time_convert = datetime.fromtimestamp(mktime(struct_time_convert))
  522.         date_time_convert = date_time_convert - timedelta(hours = 4)
  523.         fecha_convertida = date_time_convert.strftime('%d/%m/%Y')
  524.         # cadena_qr = str(nit_empresa or '') + '|' + str(invoice_number or '') + '|' + str(numero_autorizacion or '') + '|' + str(fecha_convertida or '') + '|' + str(format(amount_total, '.2f') or '') + '|' + str(format(amount_total*.13, '.2f') or '') + '|' + str(control_code or '') + '|' + str(nit_cliente or '') + '|0|0|0|0'
  525.  
  526.         monto_factura = amount_total
  527.  
  528.         fecha_convertida = ((datetime.strptime(fecha_factura, '%Y-%m-%d %H:%M:%S')) - timedelta(hours = 4)).strftime('%d/%m/%Y')
  529.         cadena_qr = ""
  530.         cadena_qr = cadena_qr +str(nit_empresa or '0') + '|' # NIT emisor
  531.         cadena_qr = cadena_qr + str(invoice_number or '0') + '|' # Numero factura
  532.         cadena_qr = cadena_qr + str(numero_autorizacion or '0') + '|' # Numero autorizacion
  533.         cadena_qr = cadena_qr + str(fecha_convertida or '0') + '|' # fecha de emision (DD/MM/AAAA)
  534.         cadena_qr = cadena_qr + str(format(monto_factura, '.2f') or '0') + '|' # Total
  535.         cadena_qr = cadena_qr + str(format(monto_factura, '.2f') or '0') + '|' # Importe credito fiscal
  536.         cadena_qr = cadena_qr + str(control_code or '0') + '|' # Codigo de control
  537.         cadena_qr = cadena_qr + str(nit_cliente or '0') + '|' # NIT/CI/CEX comprador
  538.         cadena_qr = cadena_qr + str(0) + '|' # Importe ICE /IEHD /TASAS
  539.         cadena_qr = cadena_qr + str(0) + '|' # Importe por ventas gravadas o Gravadas a tasa cero
  540.         cadena_qr = cadena_qr + str(0) + '|' # Importe no sujeto a credito fiscal
  541.         cadena_qr = cadena_qr + str(0) # Descuentos, bonificaciones y rebajas obtenidas
  542.  
  543.         qr_img = qrcode.make(cadena_qr)
  544.         filename = str(tempfile.gettempdir()) + '/qrtest.png'
  545.         # filename2 = '/static/src/img/qrtemp.png'
  546.         qr_img.save(filename)
  547.         # qr_img.save(filename2)
  548.         return base64.encodestring(file(filename, 'rb').read())
  549.         # return (file(filename, 'rb').read())
  550.  
  551.     # Computar Fecha Boliviana -4GM
  552.     @api.depends('create_date')
  553.     def _fecha_boliviana(self):
  554.         for record in self:
  555.             fecha_actual = record.create_date
  556.             struct_time_convert = time.strptime(fecha_actual, '%Y-%m-%d %H:%M:%S')
  557.             date_time_convert = datetime.fromtimestamp(mktime(struct_time_convert))
  558.             date_time_convert = date_time_convert - timedelta(hours = 4)
  559.             # fecha_actual = date_time_convert.strftime('%d/%m/%Y')
  560.             fecha_actual = date_time_convert.strftime('%Y-%m-%d')
  561.             record.fecha_boliviana = fecha_actual
  562.    
  563.      #se ha modificado esta  función (ronald terceros)
  564.     @api.depends('create_date')
  565.     def _hora_boliviana(self):
  566.         for record in self:
  567.             hora_actual = (datetime.strptime(record.create_date,'%Y-%m-%d %H:%M:%S') - timedelta(hours = 4)).time().strftime('%H:%M:%S')
  568.             record.hora_boliviana = hora_actual
  569.  
  570.     # Campos adicionales para la Factura
  571.     qr_code_id = fields.Many2one('qr.code', 'Dosificacion', domain="[('activo', '=', True)]")
  572.     nit = fields.Char('NIT', required=True, default='0')
  573.     razon_social = fields.Char('Razon Social', required=True, help="Nombre o Razón Social para la Factura.", default='SN')
  574.     invoice_number = fields.Integer('Numero Factura', required=True, readonly=True, default=0)
  575.     control_code = fields.Char('Codigo Control', size=50, readonly=True)
  576.     order_status = fields.Selection([('anulada', 'ANULADA'), ('extraviada', 'EXTRAVIADA'), ('valida','VALIDA'),('no_utilizada','NO UTILIZADA'),('emitida_por_contingencia','EMITIDA POR CONTINGENCIA')], 'Estado de Factura', default='valida')
  577.     # numero_autorizacion = fields.Char(string='Numero Autorizacion', related="qr_code_id.numero_autorizacion", store=True, readonly=True)
  578.     numero_autorizacion = fields.Char(string='Numero Autorizacion', store=True)
  579.     motivo_anulacion = fields.Text('Motivo de Anulacion')
  580.     fecha_boliviana = fields.Date(compute='_fecha_boliviana', store=True)
  581.     hora_boliviana = fields.Text(compute='_hora_boliviana', store=True) #se ha modificado este campo(ronald terceros)
  582.     numero_comanda = fields.Char('Comanda', size=20, readonly=True, help=u"Numeracion de Comanda.")
  583.     rm_numero_impresion = fields.Integer(string='Numero de impresion', default=0)
  584.  
  585.     _defaults = {
  586.         'date_invoice': (datetime.now() - timedelta(hours = 4)).strftime('%Y-%m-%d'),
  587.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement