예제 #1
0
    def create_qr_image(self, amount_total):
        url = "https://verificacfdi.facturaelectronica.sat.gob.mx/default.aspx"
        UUID = self.cfdi_folio_fiscal

        qr_emisor = self.partner_id.vat_split
        qr_receptor = self.company_id.vat_split
        total = "%.6f" % (amount_total or 0.0)
        total_qr = ""
        qr_total_split = total.split('.')
        decimales = qr_total_split[1]
        index_zero = self.return_index_floats(decimales)
        decimales_res = decimales[0:index_zero + 1]
        if decimales_res == '0':
            total_qr = qr_total_split[0]
        else:
            total_qr = qr_total_split[0] + "." + decimales_res

        last_8_digits_sello = ""


        cfdi_sello = self.cfdi_sello

        last_8_digits_sello = cfdi_sello[len(cfdi_sello) - 8:]

        qr_string = '%s&id=%s&re=%s&rr=%s&tt=%s&fe=%s' % (
        url, UUID, qr_emisor, qr_receptor, total_qr, last_8_digits_sello)

        qr_code = QR(data=qr_string.encode('utf-8'))
        try:
            qr_code.encode()
        except Exception, e:
            raise UserError(_('Advertencia !!!\nNo se pudo crear el Código Bidimensional. Error %s') % e)
예제 #2
0
파일: qr.py 프로젝트: d3m0n-r00t/qrcoder
def qr_encode(option, opt_str, value, parser):
    text = sys.argv[2]
    img = QR(data=text, pixel_size=10)
    img.encode()
    os.system("mv " + img.filename + " ~/Desktop/qr_" +
              datetime.datetime.now().strftime("%d%m%Y_%H%M%S") + ".png")
    print("File is saved in Desktop")
예제 #3
0
def generate(codes = range(20), width=2.0, cols = 5):
  width_str = '%fcm' % width

  tex_figs = ''

  c_strs = []
  f_strs = []

  for c in codes:
    c_str = '%06d' % c
    qr = QR(data = url_fmt % c)
    img_filename = img_dir + '/%s.png' % c_str 
    qr.encode(img_filename)
    c_strs.append(c_str)
    f_strs.append(figure_fmt % (width_str, img_filename))

  elts = []
  for i in range(0,len(codes),cols):
    elts.append(c_strs[i:i+cols])
    elts.append(f_strs[i:i+cols])

  tex_file = open(tex_filename, 'w')
  tex_file.write(tex_fmt % list_to_table(elts))
  tex_file.close()

  subprocess.check_call(['pdflatex',tex_filename],cwd=tex_dir)
예제 #4
0
파일: qtqr.py 프로젝트: BenjaminHae/qtqr
    def qrencode(self, fileName=None):
        #Functions to get the correct data
        data_fields = {
            "text": unicode(self.textEdit.toPlainText()),
            "url": unicode(self.urlEdit.text()),
            "bookmark": ( unicode(self.bookmarkTitleEdit.text()), unicode(self.bookmarkUrlEdit.text()) ),
            "email": unicode(self.emailEdit.text()),
            "emailmessage": ( unicode(self.emailEdit.text()), unicode(self.emailSubjectEdit.text()), unicode(self.emailBodyEdit.toPlainText()) ),
            "telephone": unicode(self.telephoneEdit.text()),
            "phonebook": (('N',unicode(self.phonebookNameEdit.text())),
                          ('TEL', unicode(self.phonebookTelEdit.text())),
                          ('EMAIL',unicode(self.phonebookEMailEdit.text())),
                          ('NOTE', unicode(self.phonebookNoteEdit.text())),
                          ('BDAY', unicode(self.phonebookBirthdayEdit.date().toString("yyyyMMdd")) if self.phonebookBirthdayLabel.isChecked() else ""), #YYYYMMDD
                          ('ADR', unicode(self.phonebookAddressEdit.text())),  #The fields divided by commas (,) denote PO box, room number, house number, city, prefecture, zip code and country, in order.
                          ('URL', unicode(self.phonebookUrlEdit.text())),
                          # ('NICKNAME', ''),
                        ),
            "sms": ( unicode(self.smsNumberEdit.text()), unicode(self.smsBodyEdit.toPlainText()) ),
            "mms": ( unicode(self.mmsNumberEdit.text()), unicode(self.mmsBodyEdit.toPlainText()) ),
            "geo": ( unicode(self.geoLatEdit.text()), unicode(self.geoLongEdit.text()) ),
            "wifi": ( unicode(self.wifiSSIDEdit.text()), (u"WEP",u"WPA",u"nopass")[self.wifiEncriptionType.currentIndex()], unicode(self.wifiPasswordEdit.text()))
        }

        data_type = unicode(self.templates[unicode(self.selector.currentText())])
        data = data_fields[data_type]
        
        level = (u'L',u'M',u'Q',u'H')

        if data:
            if data_type == 'emailmessage' and data[1] == '' and data[2] == '':
                data_type = 'email'
                data = data_fields[data_type]
            qr = QR(pixel_size = unicode(self.pixelSize.value()),
                    data = data,
                    level = unicode(level[self.ecLevel.currentIndex()]),
                    margin_size = unicode(self.marginSize.value()),
                    data_type = data_type,
                    )
            error = 1
            if type(fileName) is not unicode:
                error = qr.encode()
            else:
                error = qr.encode(fileName)
            if error == 0:
                self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
                self.saveButton.setEnabled(True)
            else:
                if NOTIFY:
                    n = pynotify.Notification(
                        "QtQR",
                        unicode(self.trUtf8("ERROR: Something went wrong while trying to generate the QR Code.")),
                        "qtqr"
                        )
                    n.show()
                else:
                    print "Something went wrong while trying to generate the QR Code"
            qr.destroy()
        else:
            self.saveButton.setEnabled(False)
예제 #5
0
	def get(self, path):
		home_url = options.home_url
		if home_url.startswith("http://"):
			home_url = home_url[7:]
		q=QR(u""+home_url+"/auth/"+path)
		q.encode()
		self.set_header("Content-Type", "image/gif")
		self.write(open(q.filename).read())
예제 #6
0
def allocate_qrcode(tag, prefix):
    qr = QR(data=tag, pixel_size=4)
    qr.encode()

    path = qr.filename
    f = get_qrcode_filename(tag, prefix)
    os.system("mkdir -p qrcodes; cp {} qrcodes/{}".format(path, f))
    return (f)
def write(building, washer):
    string = building + " : " + washer
    u = unicode(string, "utf-8")

    my_QR = QR(data=u, pixel_size=10)
    my_QR.encode()

    # command to move the QR code to the desktop
    os.system("sudo mv " + my_QR.filename + " ~/Desktop")
예제 #8
0
def __init__(
self, data=u'NULL', pixel_size=3, level='L', margin_size=4, data_type=u'text', filename=None
):

	from qrtools import QR
	myCode = QR(data=u"Simpledata", pixel_size=10)
	myCode.encode()
	print myCode.filename
	print myCode
예제 #9
0
def encodeKey(key):
    if isinstance(key, str):
        int_key = hexToKey(key)
        myCode = QR(data="/".join(map(str, int_key)), data_type="text")
        myCode.encode()
        return myCode.filename
    elif isinstance(key, list):
        str_key = "/".join(map(str, key))
        myIntCode = QR(data=str_key, data_type="text")
        myIntCode.encode()
        return myIntCode.filename
예제 #10
0
def encodeKey(key):
	if isinstance(key, str):
		int_key = hexToKey(key)
		myCode = QR(data="/".join(map(str, int_key)),data_type="text")
		myCode.encode()
		return myCode.filename
	elif isinstance(key, list):
		str_key = "/".join(map(str, key))
		myIntCode = QR(data=str_key,data_type="text")
		myIntCode.encode()
		return myIntCode.filename
예제 #11
0
	def get(self, path):
		try:
			if(str(int(path))!=path):
				self.write("Incorect ID")
				return
		except:
			self.write("Incorect ID")
			return
		home_url = options.home_url
		if home_url.startswith("http://"):
			home_url = home_url[7:]
		q=QR(u""+home_url+"/o/"+path)
		q.encode()
		self.set_header("Content-Type", "image/gif")
		self.write(open(q.filename).read())
예제 #12
0
파일: qtqr.py 프로젝트: prashantyahide/qtqr
    def qrencode(self):
        text = [
            unicode(self.textEdit.toPlainText()),
            unicode(self.urlEdit.text()),
            ( unicode(self.emailEdit.text()), unicode(self.emailSubjectEdit.text()), unicode(self.emailBodyEdit.toPlainText()) ),
            ( unicode(self.smsNumberEdit.text()), unicode(self.smsBodyEdit.toPlainText()) ),
            unicode(self.telephoneEdit.text()),
        ]
        level = (u'L',u'M',u'Q',u'H')
        data_type = (u'text',u'url',u'emailmessage',u'sms',u'telephone')

        if text[self.tabs.currentIndex()]:
            qr = QR(pixel_size = unicode(self.pixelSize.value()),
                    data=text[self.tabs.currentIndex()],
                    level=unicode(level[self.ecLevel.currentIndex()]),
                    margin_size=unicode(self.marginSize.value()),
                    data_type=unicode(data_type[self.tabs.currentIndex()]),
                    )
            if qr.encode() == 0:
                self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
                self.saveButton.setEnabled(True)
            else:
                print >>sys.stderr, u"ERROR: Something went wrong while trying to generate de qrcode."
        else:
            self.saveButton.setEnabled(False)
예제 #13
0
    def qrencode(self):
        text = [
            unicode(self.textEdit.toPlainText()),
            unicode(self.urlEdit.text()),
            (unicode(self.emailEdit.text()),
             unicode(self.emailSubjectEdit.text()),
             unicode(self.emailBodyEdit.toPlainText())),
            (unicode(self.smsNumberEdit.text()),
             unicode(self.smsBodyEdit.toPlainText())),
            unicode(self.telephoneEdit.text()),
        ]
        level = (u'L', u'M', u'Q', u'H')
        data_type = (u'text', u'url', u'emailmessage', u'sms', u'telephone')

        if text[self.tabs.currentIndex()]:
            qr = QR(
                pixel_size=unicode(self.pixelSize.value()),
                data=text[self.tabs.currentIndex()],
                level=unicode(level[self.ecLevel.currentIndex()]),
                margin_size=unicode(self.marginSize.value()),
                data_type=unicode(data_type[self.tabs.currentIndex()]),
            )
            if qr.encode() == 0:
                self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
                self.saveButton.setEnabled(True)
            else:
                print >> sys.stderr, u"ERROR: Something went wrong while trying to generate de qrcode."
        else:
            self.saveButton.setEnabled(False)
예제 #14
0
def _qr_code(qr_code_data):
    """
        Create QR code.
        @type qr_code_data: string
        @param qr_code_data: Data to encode in the qr code
    """
    if not qr_code_data:
        return "/static/images/default.png"

    qr_code_data = "\n".join(qr_code_data)
    qr_code_data = "mecard:" + qr_code_data
    qr_code = QR(qr_code_data)
    qr_code.encode()
    with open(qr_code.filename) as filename:
        data = filename.read()
        return "data:image/png;base64," + data.encode('base64')
    qr_code.destroy()
예제 #15
0
def generateimg(campaign, adSet, ad, adv, name, address):
    import uuid
    from django.conf import settings
    address_img_path = generateaddressimage(name, address)
    unique = format(str(uuid.uuid4().hex))
    print "unique " + unique
    name = "/static/images/" + unique + ".png"
    filename = os.path.join(settings.BASE_DIR, 'macaw{0}'.format(name))
    print "file " + filename
    my_QR = QR(data=u'campaign=' + campaign + ' adSet=' + adSet + ' ad=' + ad +
               ' adv=' + adv + ' uuid=' + unique,
               pixel_size=20,
               filename=filename)
    my_QR.encode()
    image_data = open(my_QR.filename, mode='r').read()
    os.rename(my_QR.filename, filename)
    final_display_img = mergeImages(name, address_img_path)
    os.remove("macaw/" + name)
    os.remove(address_img_path)
    return final_display_img
예제 #16
0
def qr_generate(request):
    msg=""
    error=True
    data=""
    if 'HTTP_COOKIE' in request.META:
        if request.GET:
            data=request.GET
            route=data['route']
            amt=data['amount'].split(',')
            tid=data['tid'].split(',')
            vid=request.session['VIN']
            print(data)
            typ=int(data['type'])
            fd=datetime.datetime.today()

            for i in range(0,len(tid)):
                qry_id=Users.objects.filter(vehicle_no=vid).values('id')
                s=str(amt[i])+'#'+vid+'#'+str(qry_id[0]['id'])
                qry_ins=Orders.objects.create(route=route,amount=amt[i],tollid=tid[i],status='PENDING',fdate=fd,user_id=vid,type=typ,orderid=s)
            my_QR = QR(data = s,pixel_size=3)
            my_QR.encode()
            name=my_QR.filename.split('/')
            qry_ins=Orders.objects.filter(orderid=s).update(filename=my_QR.filename)
            msg="Success"
            error=False
            data=name[3]
            os.system("sudo mv " + my_QR.filename + " /opt/lampp/htdocs/qrcodes/")
            url="http://192.168.31.111/qrcodes/"+name[3]
            print(url)
        else:
            msg="Parameter problem"
    else:
        msg="Wrong Parameters"
    # with open(my_QR.filename, "rb") as f:
    #   return HttpResponse(f.read(), content_type="image/jpeg")
    return JsonResponse({'msg':msg,'error':error,'url':url},safe=False)
예제 #17
0
def encodeAES(key, plain, level='L'):
    if isinstance(key, str):
        int_key = hexToKey(key)
    elif isinstance(key, list):
        int_key = key[:]
    ciphertext = dAES.encrypt(plain, int_key)
    if len(ciphertext) > 2952:
        print(
            colors.FAIL + "resulting cipher text is too long (" +
            str(len(ciphertext)) +
            " characters) to fit in QR code (Even at error correction level L, max length: 2952)"
            + colors.ENDC)
        exit(0)
    if not level == 'L':
        if level == 'M' and len(ciphertext) > 2330:
            print(
                colors.FAIL + "resulting cipher text is too long (" +
                str(len(ciphertext)) +
                " characters) to fit in QR code at error correction level M (max length: 2330)"
                + colors.ENDC)
            exit(0)
        elif level == 'Q' and len(ciphertext) > 1662:
            print(
                colors.FAIL + "resulting cipher text is too long (" +
                str(len(ciphertext)) +
                " characters) to fit in QR code at error correction level Q (max length: 1662)"
                + colors.ENDC)
            exit(0)
        elif level == 'H' and len(ciphertext) > 1272:
            print(
                colors.FAIL + "resulting cipher text is too long (" +
                str(len(ciphertext)) +
                " characters) to fit in QR code at error correction level Q (max length: 1662)"
                + colors.ENDC)
            exit(0)
    AESqr = QR(data=ciphertext, data_type="text", level=level)
    if AESqr.encode() == 0:
        return AESqr.filename
    else:
        print(colors.FAIL + "um..." + colors.ENDC)
예제 #18
0
def encodeAES(key, plain, level='L'):
	if isinstance(key, str):
		int_key = hexToKey(key)
	elif isinstance(key, list):
		int_key = key[:]
	ciphertext = dAES.encrypt(plain, int_key)
	if len(ciphertext) > 2952:
		print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code (Even at error correction level L, max length: 2952)"+colors.ENDC)
		exit(0)
	if not level == 'L':
		if level == 'M' and len(ciphertext) > 2330:
			print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code at error correction level M (max length: 2330)"+colors.ENDC)
			exit(0)
		elif level == 'Q' and len(ciphertext) > 1662:
			print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code at error correction level Q (max length: 1662)"+colors.ENDC)
			exit(0)
		elif level == 'H' and len(ciphertext) > 1272:
			print(colors.FAIL+"resulting cipher text is too long ("+str(len(ciphertext))+" characters) to fit in QR code at error correction level Q (max length: 1662)"+colors.ENDC)
			exit(0)
	AESqr = QR(data=ciphertext, data_type="text", level=level)
	if AESqr.encode() == 0:
		return AESqr.filename
	else:
		print(colors.FAIL+"um..."+colors.ENDC)
예제 #19
0
    def makeQR(self, _data ):
	myCode = QR(data=_data, pixel_size=12, level='L')
	myCode.encode(QR_IMAGE_FILE)
예제 #20
0
파일: newqr.py 프로젝트: Shlok347/qrtools
# Python 2.x program to generate QR code
from qrtools import QR

# creates the QR object
my_QR = QR(data=u"Example")

# encodes to a QR code
my_QR.encode()
예제 #21
0
        if code not in ['QR', 'qrcode']:
            try:
                ret_val = createBarcodeDrawing(code,
                                               value=str(value),
                                               **options)
            except Exception, e:
                raise osv.except_osv('Error', e)
            ret_val.save(formats=['svg'], fnRoot='barcode', outDir='/tmp/')
            os.system('rsvg-convert %s -o %s' %
                      ('/tmp/barcode.svg', '/tmp/barcode.png'))
            return base64.encodestring(open("/tmp/barcode.png", "rb").read())
        else:
            ret_val = False
            from qrtools import QR
            qrCode = QR(data=value)
            qrCode.encode()
            return base64.encodestring(open(qrCode.filename, "rb").read())

    def generate_image(self, cr, uid, ids, context=None):
        "button function for genrating image " ""
        if not context:
            context = {}

        for self_obj in self.browse(cr, uid, ids, context=context):
            image = self.get_image(self_obj.code,
                                   code=self_obj.barcode_type or 'qrcode',
                                   width=self_obj.width,
                                   hight=self_obj.hight,
                                   hr=self_obj.hr_form)
            self.write(cr, uid, self_obj.id, {'image': image}, context=context)
        return True
예제 #22
0
    def Submit(self):
        #Set Progress bar to 0
        self.progressBar.setValue(0)

        #Setting variables to the text input from the text edit
        number = 1
        first_name = str(self.lineEdit.text())
        last_name = str(self.lineEdit_2.text())
        toaddr = str(self.lineEdit_3.text())
        new_ID = str.upper("".join([last_name[:4], "00", str(number)]))
        unique = False
        #Updating progress baar
        self.progressBar.setValue(10)

        #Open "EmployeeList.csv" for reading to create a unique ID
        with open('EmployeeList.csv', 'rb') as f:
            reader = csv.reader(f)
            while unique == False:
                for row in reader:
                    #If ID is not unique change last digit by 1
                    if row[0] == new_ID:
                        number = number + 1
                        new_ID = str.upper("".join(
                            [last_name[:4], "00",
                             str(number)]))
                unique = True

        #Update Progress bar
        self.progressBar.setValue(20)

        #Create unique QR code for employee and finding filepath for it
        myCode = QR(data=new_ID, pixel_size=10)
        myCode.encode()
        filepath = myCode.filename
        #Update progress bar
        self.progressBar.setValue(30)

        #Moving QR file from temp folder into directory folder
        QRfile = filepath.split("/")
        shutil.move(filepath, os.getcwd() + "/" + new_ID + ".png")
        #Update Progress Bar
        self.progressBar.setValue(40)

        #Email QR code file to employee's email address
        fromaddr = "*****@*****.**"
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = 'Employee QR Code'
        body = 'Attached is your QR code'
        self.progressBar.setValue(50)

        msg.attach(MIMEText(body, 'plain'))
        filename = new_ID + ".png"
        attachment = open(new_ID + ".png", "rb")
        self.progressBar.setValue(60)

        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        "attachment; filename= %s" % filename)
        self.progressBar.setValue(70)

        msg.attach(part)
        server = smtplib.SMTP('smtp.live.com', 587)
        server.starttls()
        self.progressBar.setValue(80)

        server.login(fromaddr, "lala05")
        text = msg.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()
        self.progressBar.setValue(90)

        #Open "EmployeeList.csv" apending their information to it
        with open('EmployeeList.csv', 'ab') as f:
            writer = csv.writer(f)
            writer.writerow(
                [new_ID, (" ".join([first_name, last_name])), manager_status])
            f.close()
        #Remove newly created QR file
        os.remove(new_ID + ".png")

        #Clear all text edit lines for easy input of new employee
        self.lineEdit.clear()
        self.lineEdit_2.clear()
        self.lineEdit_3.clear()
        self.radioNo.setChecked(True)
        #Finish progress bar
        self.progressBar.setValue(100)
예제 #23
0
파일: qrcode_gen.py 프로젝트: biz2013/xwjy
    def generate_qrcode(self, data, filename):
        my_QR = QR(data=data)
        my_QR.encode()

        # command to move the QR code to the desktop
        os.system("sudo mv " + my_QR.filename + " " + filename)
    def _upload_ws_file(self, cr, uid, ids, fdata=None, context=None):
        
            """
            @params fdata : File.xml codification in base64
            """
           
            if context is None:
                context = {}
            invoice_obj = self.pool.get('account.invoice')

            pac_params_obj = invoice_obj.pool.get('params.pac')

            for ir_attachment_facturae_mx_id in self.browse(cr, uid, ids, context=context):
                invoice = ir_attachment_facturae_mx_id.invoice_id
                comprobante = invoice_obj._get_type_sequence(
                    cr, uid, [invoice.id], context=context)
                cfd_data = base64.decodestring(fdata or invoice_obj.fdata)
                xml_res_str = xml.dom.minidom.parseString(cfd_data)
                xml_res_addenda = invoice_obj.add_addenta_xml(
                    cr, uid, xml_res_str, comprobante, context=context)
                xml_res_str_addenda = xml_res_addenda.toxml('UTF-8')
                xml_res_str_addenda = xml_res_str_addenda.replace(codecs.BOM_UTF8, '')
                
                if tools.config['test_report_directory']:#TODO: Add if test-enabled:
                    ir_attach_facturae_mx_file_input = ir_attachment_facturae_mx_id.file_input and ir_attachment_facturae_mx_id.file_input or False
                    fname_suffix = ir_attach_facturae_mx_file_input and ir_attach_facturae_mx_file_input.datas_fname or ''
                    open( os.path.join(tools.config['test_report_directory'], 'l10n_mx_facturae_pac_finkok' + '_' + \
                      'before_upload' + '-' + fname_suffix), 'wb+').write( xml_res_str_addenda )

                compr = xml_res_addenda.getElementsByTagName(comprobante)[0]
                date = compr.attributes['fecha'].value
                date_format = datetime.strptime(
                    date, '%Y-%m-%dT%H:%M:%S').strftime('%Y-%m-%d')
                context['date'] = date_format
                invoice_ids = [invoice.id]
                file = False
                msg = ''
                cfdi_xml = False

                pac_params_ids = pac_params_obj.search(cr, uid, [
                    ('method_type', '=', 'stamp'), (
                        'company_id', '=', invoice.company_emitter_id.id), (
                            'active', '=', True)], limit=1, context=context)
                
                if pac_params_ids:
                    pac_params = pac_params_obj.browse(
                        cr, uid, pac_params_ids, context)[0]
                    user = pac_params.user
                    password = pac_params.password
                    wsdl_url = pac_params.url_webservice
                    namespace = pac_params.namespace

                    ## Establece el url del PAC Puede ser demo o producción
                    url = 'https://facturacion.finkok.com/servicios/soap/stamp.wsdl'
                    testing_url = 'http://demo-facturacion.finkok.com/servicios/soap/stamp.wsdl'

                    ## Compara si el url establecido es el mismo que el de la configuración del módulo.
                    if (wsdl_url == url):
                        url = url
                    elif (wsdl_url == testing_url):
                        url = testing_url
                        
                    else:
                        raise osv.except_osv(_('Aviso'), _('URL  o PAC incorrecto'))
                        
                    ## Verifica si se esta timbrando en webservice Demo    
                    if 'demo' in wsdl_url:
                        msg += _('¡AVISO, FIRMADO EN MODO PRUEBA!<br/>')
                   
                    
                    ## Conexión
                    client = Client(url,cache=None)
                    
                    if True:  # if wsdl_client:
                        file_globals = invoice_obj._get_file_globals(
                            cr, uid, invoice_ids, context=context)
                        fname_cer_no_pem = file_globals['fname_cer']
                        cerCSD = fname_cer_no_pem and base64.encodestring(
                            open(fname_cer_no_pem, "r").read()) or ''
                        fname_key_no_pem = file_globals['fname_key']
                        keyCSD = fname_key_no_pem and base64.encodestring(
                            open(fname_key_no_pem, "r").read()) or ''
                        cfdi = base64.encodestring(xml_res_str_addenda)
                        cfdi = cfdi.replace('\n', '')
                                                
                        ## Respuesta del webservice
                        resultado = client.service.stamp(cfdi,user,password)

                        htz = int(invoice_obj._get_time_zone(
                            cr, uid, [ir_attachment_facturae_mx_id.invoice_id.id], context=context))
            

                        if resultado['Incidencias']:
                            # ERROR
                            codigo_incidencia = resultado['Incidencias'] and \
                                resultado['Incidencias']['Incidencia'] and \
                                resultado['Incidencias']['Incidencia'][0]['CodigoError'] or ''

                            mensaje_incidencia = resultado['Incidencias'] and \
                                resultado['Incidencias']['Incidencia'] and \
                                resultado['Incidencias']['Incidencia'][0]['MensajeIncidencia'] or ''

                            
                            
                            msg_error = 'Error al intentar timbrar. ' + 'Codigo error: ' + codigo_incidencia + "." + ' Descripcion: ' + mensaje_incidencia + '.' 
                            raise orm.except_orm('Aviso', msg_error)


                            ## Tiene q retornar esto para que pase a firmado              
                            #return {'file': ' ', 'msg': msg_error, 'cfdi_xml': ' '}
                            

                        else:
                            # EXITO
                            mensaje = _(tools.ustr(resultado['CodEstatus']))  ## Comprobante timbrado satisfactoriamente                 
                            folio_fiscal= resultado['UUID'] or ''
                            fecha_timbrado_cfdi = resultado['Fecha'] or False
                            fecha_timbrado = resultado[
                                'Fecha'] or False
                            fecha_timbrado = fecha_timbrado and time.strftime(
                                '%Y-%m-%d %H:%M:%S', time.strptime(
                                    fecha_timbrado[:19], '%Y-%m-%dT%H:%M:%S')) or False
                            fecha_timbrado = fecha_timbrado and datetime.strptime(
                                fecha_timbrado, '%Y-%m-%d %H:%M:%S') + timedelta(
                                    hours=htz) or False


                            ## Generar Cadena Original
                            version='1.0'
                            ## folio_fiscal lo saca arriba de la respuesta del webservice
                            ## fecha_timbrado_cfdi la saca de arriba de la respuesta del webservice

                            ## Extraer datos del xml
                            xml_string = resultado['xml']
                            xml_string = xml_string.encode('UTF-8')


                            ## Extraer los rfc's de los nodos hijos
                            xml_etree = etree.fromstring(xml_string)
                            xml_etree.getchildren()
                            xml_childrens = xml_etree.getchildren()
                            ## Obtener rfc emisor
                            re=xml_childrens[0].get('rfc')
                            ## Obtener rfc receptor
                            rr=xml_childrens[1].get('rfc')
                           

                            ##Extraer selloCSD
                            selloCFD = xml_etree.get('sello')

                            ## Extraer total
                            total_factura= xml_etree.get('total') 

                            ## Pasar el total a 17 caracteres como lo especifica el anexo 20

                            ## Convertir el total a float para sacarle los decimales
                            total_factura=float(total_factura)
                           
                            ## Sacarle 6 decimales
                            total_factura = format(total_factura, '.6f')

                            ## Convertir a string
                            total_factura=str(total_factura)
                            
                            ## Sacar la logitud de la cadena
                            total=len(total_factura)

                            ## Agregar los ceros a la izquiera hasta completar 17 caracteres
                            while total < 17:
                                i=''
                                i+='0'
                                total += 1
                                total_factura=i+total_factura
                                
                            NoCertificadoSAT='20001000000100005761'
                            cadena_original='||' + version + '|' + folio_fiscal + '|' + fecha_timbrado_cfdi + '|' + selloCFD + '|' + NoCertificadoSAT + '||'

                            ## Generar CBB                                                               
                            qr_string = "?re="+re+"&rr="+rr+"&tt="+total_factura+"&id="+folio_fiscal ## Cadena de Texto
                            qr_code = QR(data=qr_string) 
                            qr_code.encode() ##Encodeamos la Cadena
                            qr_file = open(qr_code.filename, "rb") ## Escribimos la Imagen
                            temp_bytes = qr_file.read() ## Leemos la Imagen
                            qr_bytes = base64.encodestring(temp_bytes) ## Convertimos la Imagen para Escribirla en Base64
                            qr_file.close() ## Cerramos la lectura del archivo con la imagen QR
                           

                            cfdi_data = {     
                                'cfdi_cbb': qr_bytes, 
                                'cfdi_sello': resultado['SatSeal'] or False,
                                'cfdi_no_certificado': resultado['NoCertificadoSAT'] or False,
                                'cfdi_cadena_original': cadena_original,                            
                                'cfdi_fecha_timbrado': fecha_timbrado,
                                'cfdi_xml': resultado['xml'] or '',  # este se necesita en uno que no es base64
                                'cfdi_folio_fiscal': resultado['UUID'] or '',
                                'pac_id': pac_params.id,
                            }

                            ## Comprobante timbrado satisfactoriamente. Folio Fiscal: Folio
                            msg += mensaje + "." + \
                                " Folio Fiscal: " + folio_fiscal
                            msg += (". Asegurese que el archivo fue generado correctamente en el SAT https://www.consulta.sat.gob.mx/sicofi_web/moduloECFD_plus/ValidadorCFDI/Validador%20cfdi.html")
                            
                            if cfdi_data.get('cfdi_xml', False):
                                url_pac = '</"%s"><!--Para validar el XML CFDI puede descargar el certificado del PAC desde la siguiente liga: la liga de los certificados del PAC-->' % (
                                    comprobante)
                                cfdi_data['cfdi_xml'] = cfdi_data[
                                    'cfdi_xml'].replace('</"%s">' % (comprobante), url_pac)
                                file = base64.encodestring(
                                    cfdi_data['cfdi_xml'] or '')
                                cfdi_xml = cfdi_data.pop('cfdi_xml')

                            if cfdi_xml:
                                invoice_obj.write(cr, uid, [invoice.id], cfdi_data)
                                cfdi_data['cfdi_xml'] = cfdi_xml

                            else:
                                msg = 'No se pudo extraer el XML del PAC'

                            

                else:
                    msg = 'No se encontro informacion del web services del PAC, verifique que la configuracion sea correcta'
                    raise osv.except_osv('Aviso', msg)
                
                
            return {'file': file, 'msg': msg, 'cfdi_xml': cfdi_xml}
예제 #25
0
        #        options['isoScale'] = 1
        if code not in ['QR', 'qrcode']:
            try:
                ret_val = createBarcodeDrawing(code,
                                               value=str(value),
                                               **options)
            except Exception, e:
                raise osv.except_osv('Error', e)
            image_data = ret_val.asString('png')
            return base64.encodestring(image_data)
        else:
            ret_val = False
            from qrtools import QR
            fd, temp_path = mkstemp(suffix='.png')
            qrCode = QR(data=value)
            qrCode.encode(temp_path)
            fdesc = open(qrCode.filename, "rb")
            data = base64.encodestring(fdesc.read())
            fdesc.close()
            os.close(fd)
            os.remove(temp_path)
            return data

    def generate_image(self, cr, uid, ids, context=None):
        "button function for genrating image " ""
        if not context:
            context = {}

        for self_obj in self.browse(cr, uid, ids, context=context):
            image = self.get_image(self_obj.code,
                                   code=self_obj.barcode_type or 'qrcode',
예제 #26
0
# -*- coding: utf8 -*-
#!/usr/bin/env python
import os
import shutil
import base64
from qrtools import QR
cedula=raw_input("Cedula del profesor para generar el QR: ")
nombre=cedula
for i in range(1,10):
    cedula=base64.b64encode(cedula)
code = QR(data=cedula, pixel_size=10)
code.encode()
src = code.get_tmp_file()
dst = '%s/qr/%s.png'%(os.getcwd(),nombre)
shutil.copy(src, dst)
예제 #27
0
파일: qtqr.py 프로젝트: primetang/qrtools
    def qrencode(self):
        # Functions to get the correct data
        data_fields = {
            "text": unicode(self.textEdit.toPlainText()),
            "url": unicode(self.urlEdit.text()),
            "bookmark": (unicode(self.bookmarkTitleEdit.text()), unicode(self.bookmarkUrlEdit.text())),
            "email": unicode(self.emailEdit.text()),
            "emailmessage": (
                unicode(self.emailEdit.text()),
                unicode(self.emailSubjectEdit.text()),
                unicode(self.emailBodyEdit.toPlainText()),
            ),
            "telephone": unicode(self.telephoneEdit.text()),
            "phonebook": (
                ("N", unicode(self.phonebookNameEdit.text())),
                ("TEL", unicode(self.phonebookTelEdit.text())),
                ("EMAIL", unicode(self.phonebookEMailEdit.text())),
                ("NOTE", unicode(self.phonebookNoteEdit.text())),
                ("BDAY", unicode(self.phonebookBirthdayEdit.date().toString("yyyyMMdd"))),  # YYYYMMDD
                (
                    "ADR",
                    unicode(self.phonebookAddressEdit.text()),
                ),  # The fields divided by commas (,) denote PO box, room number, house number, city, prefecture, zip code and country, in order.
                ("URL", unicode(self.phonebookUrlEdit.text())),
                # ('NICKNAME', ''),
            ),
            "sms": (unicode(self.smsNumberEdit.text()), unicode(self.smsBodyEdit.toPlainText())),
            "mms": (unicode(self.mmsNumberEdit.text()), unicode(self.mmsBodyEdit.toPlainText())),
            "geo": (unicode(self.geoLatEdit.text()), unicode(self.geoLongEdit.text())),
        }

        data_type = unicode(self.templates[unicode(self.selector.currentText())])
        data = data_fields[data_type]

        level = (u"L", u"M", u"Q", u"H")

        if data:
            if data_type == "emailmessage" and data[1] == "" and data[2] == "":
                data_type = "email"
                data = data_fields[data_type]
            qr = QR(
                pixel_size=unicode(self.pixelSize.value()),
                data=data,
                level=unicode(level[self.ecLevel.currentIndex()]),
                margin_size=unicode(self.marginSize.value()),
                data_type=data_type,
            )
            if qr.encode() == 0:
                self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
                self.saveButton.setEnabled(True)
            else:
                if NOTIFY:
                    n = pynotify.Notification(
                        "QtQR",
                        unicode(self.trUtf8("ERROR: Something went wrong while trying to generate the QR Code.")),
                        "qtqr",
                    )
                    n.show()
                else:
                    print "Something went worng while trying to generate the QR Code"
        else:
            self.saveButton.setEnabled(False)
예제 #28
0
        options['quiet'] = False
        options['barWidth'] = 2
#        options['isoScale'] = 1
        if code not in ('QR', 'qrcode'):
            try:
                ret_val = createBarcodeDrawing(code, value=str(value), **options)
            except Exception, e:
                raise osv.except_osv('Error', e)
            image_data = ret_val.asString('png')
            return base64.encodestring(image_data)
        else:
            ret_val = False
            from qrtools import QR
            fd, temp_path = mkstemp(suffix='.png')
            qrCode = QR(data=value)
            qrCode.encode(temp_path)
            fdesc = open(qrCode.filename, "rb")
            data = base64.encodestring(fdesc.read())
            fdesc.close()
            os.close(fd)
            os.remove(temp_path)
            return data

    def generate_image(self, cr, uid, ids, context=None):
        "button function for genrating image """
        if not context:
            context = {}

        for self_obj in self.browse(cr, uid, ids, context=context):
            image = self.get_image(self_obj.code,
                                   code=self_obj.barcode_type or 'qrcode',
예제 #29
0
        options['quiet'] = False
        options['barWidth'] = 2
#        options['isoScale'] = 1
        if code not in ['QR','qrcode']:
            try:
                ret_val = createBarcodeDrawing(code, value=str(value), **options)
            except Exception, e:
                raise osv.except_osv('Error', e)
            ret_val.save(formats=['svg'], fnRoot='barcode', outDir='/tmp/')
            os.system('rsvg-convert %s -o %s' % ('/tmp/barcode.svg', '/tmp/barcode.png'))
            return base64.encodestring(open("/tmp/barcode.png","rb").read())
        else:
            ret_val = False
            from qrtools import QR
            qrCode = QR(data=value)
            qrCode.encode()
            return base64.encodestring(open(qrCode.filename,"rb").read())
    
    def generate_image(self, cr, uid, ids, context=None):
        "button function for genrating image """
        if not context:
            context = {}

        for self_obj in self.browse(cr, uid, ids, context=context):
            image = self.get_image(self_obj.code,
                        code=self_obj.barcode_type or 'qrcode',
                        width=self_obj.width, hight=self_obj.hight,
                        hr=self_obj.hr_form)
            self.write(cr, uid, self_obj.id,
                {'image':image},context=context)
        return True
예제 #30
0
파일: QRfuncs.py 프로젝트: Jacobmose/ITROB
 def create_qr_image(self, brickcolor, debug = False):
     qr_creator = QR(data=u"pattern" + brickcolor + "", pixel_size=10)
     qr_creator.encode("pattern" + brickcolor + ".png")
     if debug: print(qr_creator.filename)
     
     return qr_creator.filename
                    if row[0] == new_ID:
                        number = number + 1
                        new_ID = str.upper("".join(
                            [last_name[:4], "00",
                             str(number)]))
                unique = True
        manager_status = raw_input("Manager? (Y/N):")
        role = 0
        if manager_status == "Y" or manager_status == "y":
            role = 1

        if manager_status == "N" or manager_status == "n":
            role = 0

        myCode = QR(data=new_ID, pixel_size=10)
        myCode.encode()
        filepath = myCode.filename
        QRfile = filepath.split("/")
        shutil.move(filepath, os.getcwd() + "/" + new_ID + ".png")
        fromaddr = "*****@*****.**"

        e_mail = False
        while e_mail == False:
            toaddr = raw_input("Input Email Address (Case Sensitive):")
            answer = 0
            answer = raw_input('Are you sure you want to send the email to "' +
                               toaddr + '"' + ' (Y/N):')
            if answer == "Y" or answer == "y":
                e_mail = True

        msg = MIMEMultipart()
    if album['thumbnail'] != "":
        thum = urllib.quote_plus(album['thumbnail'])
        thumburl = "%s/image/%s"%(baseurl,thum)
        r = requests.get(thumburl, stream=True)
        r.raw.decode_content = True # Content-Encoding
        try:
            im = Image.open(r.raw) #NOTE: it requires pillow 2.8+
            
            basewidth = imgsize[0]
            wpercent = (basewidth/float(im.size[0]))
            hsize = int((float(im.size[1])*float(wpercent)))
            im = im.resize((basewidth,hsize), Image.ANTIALIAS)
            
            background.paste(im, (0,0))
            nothumb = False
        except:
            print "Error opening %s"%thumburl
    if nothumb:
        font = ImageFont.truetype("Arial.ttf",14)
        background=Image.new("RGBA", (500,250),(255,255,255))
        draw = ImageDraw.Draw(background)
        draw.text((10, 10),album['label'],(0,0,0),font=font)
        draw.text((10, 50),', '.join(album['artist']),(0,0,0),font=font)
        draw = ImageDraw.Draw(background)
    
    qr = QR(data="%s"%album['albumid'], pixel_size=5)
    qr.encode(filename="/tmp/qr.png")
    img = Image.open("/tmp/qr.png")

    background.paste(img, (background.size[0]-img.size[0],background.size[1]-img.size[1]))
    background.save("/tmp/%s.png"%album['albumid'])
예제 #33
0
    def qrencode(self):
        #Functions to get the correct data
        data_fields = {
            "text":
            unicode(self.textEdit.toPlainText()),
            "url":
            unicode(self.urlEdit.text()),
            "bookmark": (unicode(self.bookmarkTitleEdit.text()),
                         unicode(self.bookmarkUrlEdit.text())),
            "email":
            unicode(self.emailEdit.text()),
            "emailmessage": (unicode(self.emailEdit.text()),
                             unicode(self.emailSubjectEdit.text()),
                             unicode(self.emailBodyEdit.toPlainText())),
            "telephone":
            unicode(self.telephoneEdit.text()),
            "phonebook": (
                ('N', unicode(self.phonebookNameEdit.text())),
                ('TEL', unicode(self.phonebookTelEdit.text())),
                ('EMAIL', unicode(self.phonebookEMailEdit.text())),
                ('NOTE', unicode(self.phonebookNoteEdit.text())),
                ('BDAY',
                 unicode(
                     self.phonebookBirthdayEdit.date().toString("yyyyMMdd"))
                 ),  #YYYYMMDD
                (
                    'ADR', unicode(self.phonebookAddressEdit.text())
                ),  #The fields divided by commas (,) denote PO box, room number, house number, city, prefecture, zip code and country, in order.
                ('URL', unicode(self.phonebookUrlEdit.text())),
                # ('NICKNAME', ''),
            ),
            "sms": (unicode(self.smsNumberEdit.text()),
                    unicode(self.smsBodyEdit.toPlainText())),
            "mms": (unicode(self.mmsNumberEdit.text()),
                    unicode(self.mmsBodyEdit.toPlainText())),
            "geo": (unicode(self.geoLatEdit.text()),
                    unicode(self.geoLongEdit.text())),
        }

        data_type = unicode(self.templates[unicode(
            self.selector.currentText())])
        data = data_fields[data_type]

        level = (u'L', u'M', u'Q', u'H')

        if data:
            if data_type == 'emailmessage' and data[1] == '' and data[2] == '':
                data_type = 'email'
                data = data_fields[data_type]
            qr = QR(
                pixel_size=unicode(self.pixelSize.value()),
                data=data,
                level=unicode(level[self.ecLevel.currentIndex()]),
                margin_size=unicode(self.marginSize.value()),
                data_type=data_type,
            )
            if qr.encode() == 0:
                self.qrcode.setPixmap(QtGui.QPixmap(qr.filename))
                self.saveButton.setEnabled(True)
            else:
                if NOTIFY:
                    n = pynotify.Notification(
                        "QtQR",
                        unicode(
                            self.trUtf8(
                                "ERROR: Something went wrong while trying to generate the QR Code."
                            )), "qtqr")
                    n.show()
                else:
                    print "Something went worng while trying to generate the QR Code"
        else:
            self.saveButton.setEnabled(False)