Advertisement
Guest User

Untitled

a guest
Jul 7th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.77 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. #  CRON PARA CALCULAR STOCK EN INVENTARIO
  5. #  (c) Juan Rúa - 2016
  6. #  jruacastro@gmail.com.pe
  7.  
  8. #Modulos y Librerias que se requieren para esta tarea programada
  9.  
  10. #LIBRERIA PARA CONECTAR A LA BASE DE DATOS
  11. import psycopg2
  12.  
  13. #LIBRERIA PARA EXPORTACION A EXCEL
  14. import xlsxwriter
  15.  
  16. #LIBRERIAS PARA ENVIO DE CORREOS
  17. import sys, smtplib, MimeWriter, base64, StringIO
  18. import gettext; _ = gettext.gettext
  19. import time
  20.  
  21. ###QUERYS A CONSULTAR
  22.  
  23. query_Stock="""select inv_cod_producto,tp.prod_descripcion, inv_cantidad
  24. from tb_inventario ti inner join tb_producto tp on ti.inv_cod_producto = tp.prod_codigo
  25. where tp.prod_tipo = 1 and inv_cantidad < 20"""
  26.  
  27. ###FUNCION DE EXPORTACION QUERY A EXCEL
  28. def exportar_query_excel(r):
  29.    
  30.         wb = xlsxwriter.Workbook('Stock.xlsx')
  31.         ws = wb.add_worksheet('Stock')
  32.  
  33.         style0 = wb.add_format()
  34.         style0.set_font_color('black')
  35.         style0.set_bold()
  36.         style0.set_align('center')
  37.        
  38.         style0.set_left()
  39.         style0.set_top()
  40.         style0.set_right()
  41.         style0.set_bottom()
  42.        
  43.         #CONTENIDO
  44.         style4 = wb.add_format()
  45.         style4.set_font_color('black')
  46.         style4.set_left()
  47.         style4.set_top()
  48.         style4.set_right()
  49.         style4.set_bottom()
  50.        
  51.         data = []
  52.         i = 0
  53.                
  54.         ws.write(1, 0, "Codigo".encode('ascii', 'replace'),style0)
  55.         ws.write(1, 1, "Nombre".encode('ascii', 'replace'),style0)
  56.         ws.write(1, 2, "Stock".encode('ascii', 'replace'),style0)
  57.  
  58.  
  59.                                    
  60.         #ws.merge_range(0,0,0,12, 'Lista de Productos', style0)
  61.      
  62.         ws.set_column(0,0,10)
  63.         ws.set_column(1,1,20)
  64.         ws.set_column(2,2,8)
  65.  
  66.         e = 2
  67.          
  68.         for i in r:
  69.             i = map(str, i)
  70.             ws.write(e, 0, str(i[0]).encode('ascii', 'replace'),style4)
  71.             ws.write(e, 1, str(i[1]).encode('ascii', 'replace'),style4)
  72.             ws.write(e, 2, str(i[2]).encode('ascii', 'replace'),style4)
  73.  
  74.             e = e + 1    
  75.            
  76.         wb.close()
  77.         print "workbook"
  78.  
  79. ###FUNCION MAIL
  80. class mail:
  81.     def __init__(self,subject="",body="", tipo="text/plain"):
  82.         self.message = StringIO.StringIO()
  83.         self.writer = MimeWriter.MimeWriter(self.message)
  84.         self.writer.addheader('Subject',subject)
  85.         self.writer.startmultipartbody('mixed')
  86.  
  87.         # start off with a text/plain part
  88.         part = self.writer.nextpart()
  89.         self.body = part.startbody(tipo)
  90.         self.body.write(body)
  91.     def add_attachment(self, arch = ""):
  92.         # now add an image part
  93.         part = self.writer.nextpart()
  94.         part.addheader('Content-Transfer-Encoding', 'base64')
  95.         self.body = part.startbody('application/pdf')
  96.         base64.encode(open(arch, 'rb'), self.body)
  97.    
  98.     def add_attachment_xls(self, arch = ""):
  99.         # now add an image part
  100.         part = self.writer.nextpart()
  101.         part.addheader('Content-Transfer-Encoding', 'base64')
  102.         self.body = part.startbody('application/vnd.ms-excel')
  103.         #self.body = part.startbody('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  104.         base64.encode(open(arch, 'rb'), self.body)
  105.    
  106.     def add_attachment_xlsx(self, arch = ""):
  107.         # now add an image part
  108.         part = self.writer.nextpart()
  109.         part.addheader('Content-Transfer-Encoding', 'base64')
  110.         #self.body = part.startbody('application/vnd.ms-excel')
  111.         self.body = part.startbody('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;name=%s'%(arch))
  112.         base64.encode(open(arch, 'rb'), self.body)
  113.    
  114.     def add_attachment_doc(self, arch = ""):
  115.         # now add an image part
  116.         part = self.writer.nextpart()
  117.         part.addheader('Content-Transfer-Encoding', 'base64')
  118.         #self.body = part.startbody('application/vnd.ms-excel')
  119.         self.body = part.startbody('application/msword')
  120.         base64.encode(open(arch, 'rb'), self.body)
  121.    
  122.     def add_attachment_docx(self, arch = ""):
  123.         # now add an image part
  124.         part = self.writer.nextpart()
  125.         part.addheader('Content-Transfer-Encoding', 'base64')
  126.         #self.body = part.startbody('application/vnd.ms-excel')
  127.         self.body = part.startbody('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  128.         base64.encode(open(arch, 'rb'), self.body)
  129.    
  130.     def send(self,desde="", para =""):
  131.         # finish off
  132.         if desde  in('', None):
  133.             desde='jruacastro@gmail.com'
  134.         self.writer.lastpart()
  135.         para = para.replace(",",";").split(";")
  136.         para.append(desde)
  137.         # send the mail
  138.         correo_sistema = "jruacastro@gmail.com"
  139.         clave_sistema = '**********'
  140.         smtp = smtplib.SMTP('smtp.gmail.com', 587)
  141.         smtp.ehlo()
  142.         smtp.starttls()
  143.         smtp.ehlo()
  144.         smtp.login(correo_sistema, clave_sistema)
  145.         smtp.sendmail(desde, para, self.message.getvalue())        
  146.         smtp.quit()
  147.  
  148. print "Empezó la secuencia..."
  149. print "..."    
  150.  
  151. try:  
  152.     conexion = psycopg2.connect(database="spsac6",user="postgres",password="postgres",host="localhost",port="5432")
  153.     cursor = conexion.cursor()
  154.     cursor.execute(query_Stock)
  155.     record = cursor.fetchall()
  156.     if len(record)==0:
  157.         print "la consulta no contiene datos"
  158.         pass
  159.     else:
  160.         print "consulta con datos"
  161.         # Mostrar la fecha en formato DIA/MES/AÑO
  162.         print (time.strftime("%d/%m/%y"))
  163.        
  164.         exportar_query_excel(record)
  165.         ###
  166.         #cursor.execute(query_fechas)
  167.         r = cursor.fetchall()
  168.        
  169.         for j in r:
  170.             tabla_fechas = """<tr>
  171.                                        <td align=center width=20>%s</td>
  172.                                        <td align=center width=50>%s</td>
  173.                                        <td align=center width=20>%s</td>
  174.  
  175.                                </tr>""" %(j[0], j[1], j[2])
  176.        
  177.        
  178.         a = mail('Productos con Stock Minimo', "Lista de productos con stock menor a 20 unidades <br>Documento generado para la Fecha: %s" %time.strftime("%d/%m/%y"), "text/html")
  179.         a.add_attachment_xlsx("Stock.xlsx")
  180.  
  181.         #cursor.execute("select comun.fn_tt(6,0)")
  182.         correo = cursor.fetchall()
  183.         a.send("jruacastro@gmail.com", "juan_32_36@hotmail.com")
  184.        
  185.         ###ACTUALIZAMOS LA TABLA OPR.CIERREDIA
  186.         #cursor.execute("update opr.cierredia set fecha_cierre_enviado=fecha_cierre")
  187.         conexion.commit()
  188.        
  189.     cursor.close()
  190.     conexion.close()
  191. except RuntimeError:
  192.     conexion.rollback()
  193.     print "Se presentaron errores en la ejecucion de las sentencias", sys.exc_info()[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement