def attach_all_docs(document, method=None): """This function attaches drawings to the purchase order based on the items being ordered""" document = json.loads(document) current_attachments = [] for file_url in frappe.db.sql( """select file_url from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", { 'doctype': document["doctype"], 'docname': document["name"] }, as_dict=True): current_attachments.append(file_url.file_url) count = 0 for item_doc in document["items"]: item = [item_doc["item_name"]] attachments = [] for file_url in frappe.db.sql( """select file_url from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", { 'doctype': ["Item"], 'docname': item }, as_dict=True): attachments.append(file_url.file_url) for attach in attachments: if not attach in current_attachments: count = count + 1 save_url(attach, document["doctype"], document["name"], "Home/Attachments") frappe.msgprint("Attached {0} files".format(count))
def foto(name, image): fecha_actual = datetime.now().isoformat()[0:19] dest = '/home/frappe/frappe-bench/sites/ccij.totall.mx/public/files/' + fecha_actual jpg = open(dest + ".jpg", "w+") jpg.write(image.decode('base64')) jpg.close() save_url("/files/" + fecha_actual + ".jpg", fecha_actual + ".jpg", "Representacion", name, "Home/Attachments", 0) return ('Imagen/archivo exitosamente guardado.')
def copy_attachments_from_amended_from(self): '''Copy attachments from `amended_from`''' from frappe.desk.form.load import get_attachments #loop through attachments for attach_item in get_attachments(self.doctype, self.amended_from): #save attachments to new doc save_url(attach_item.file_url, attach_item.file_name, self.doctype, self.name, "Home/Attachments", attach_item.is_private)
def amend_attachments(self): from frappe.desk.form.load import get_attachments #get attachments attach_list = get_attachments(self.doctype, self.amended_from) #loop through attachments for attach_item in attach_list: #save attachments to new doc save_url(attach_item.file_url,attach_item.file_name,self.doctype,self.name,"Home/Attachments",attach_item.is_private)
def validar(id, secret, docname, ciclo): c = frappe.get_doc("Certificado", docname) caracteres = string.ascii_letters + string.digits # caracteres = string.ascii_letters + string.punctuation + string.digits numeros = string.digits uuid = "".join(choice(numeros) for x in range(32)) sello = "".join(choice(caracteres) for x in range(345)) response = requests.request( "GET", "https://ciai.totall.mx/api/method/ciai.api.validar_cert?id=" + id + "&secret=" + secret + "&ciclo=" + ciclo) if response.json().get('status') == 'error': frappe.msgprint((response.json().get('message')), "ERROR ENCONTRADO AL CERTIFICAR") else: cadena = response.json().get('message') if cadena == 'Certificado Invalido': frappe.db.set_value("Certificado", docname, 'cadena', response.json().get('message')) frappe.msgprint('Certificado Invalido') return cadena frappe.db.set_value("Certificado", docname, 'cert_status', "Certificado") frappe.db.set_value("Certificado", docname, 'cadena', response.json().get('message')) frappe.db.set_value("Certificado", docname, 'uuid', uuid) frappe.db.set_value("Certificado", docname, 'sello', sello) folio = c.name fecha = c.fecha cert = c.client_id secret = c.client_secret expedido = c.expedido direccion = c.direccion xmldata = """<?xml version="1.0" encoding="UTF-8"?> <cert:Certificado xmlns:cert="https://www.ciai.totall.mx/ciai" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.ciai.totall.mx/ciai/cfdv1.xsd" Version="1.0" Folio="{folio}" Fecha="{fecha}" ID="{cert}-{secret}" NoCertificado="{cert}"> <cert:Emisor ID="CIAI-0000001" Nombre="CIAI TOTALL MX"/> <cert:Receptor ID="{cert}" Nombre="{expedido}" Direccion="{direccion}"/> <cert:Respuesta UUID="{uuid}" Sello="{sello}" Cadena="{cadena}" /> </cert:Certificado>""".format(**locals()) dest = '/home/frappe/frappe-bench/sites/cliente.totall.mx/public/files/' + uuid f = open(dest + '.xml', "w+") f.write(xmldata) f.close() save_url("/files/" + uuid + ".xml", uuid + ".xml", "Certificado", c.name, "Home/Attachments", 0) frappe.msgprint(str(c.name) + " certificado exitosamente ") c.reload() frappe.errprint(response) return response.text
def add_attachments(dn,attachments): from frappe.utils.file_manager import save_url attachments = json.loads(attachments) # loop through attachments for a in attachments: attach = frappe.db.get_value("File",{"name":a},["file_name", "file_url", "is_private"],as_dict=1) # save attachments to new doc save_url(attach.file_url, attach.file_name, "Communication", dn, "Home/Attachments", attach.is_private)
def add_attachments(name, attachments): '''Add attachments to the given Communiction''' from frappe.utils.file_manager import save_url # loop through attachments for a in attachments: attach = frappe.db.get_value("File", {"name":a}, ["file_name", "file_url", "is_private"], as_dict=1) # save attachments to new doc save_url(attach.file_url, attach.file_name, "Communication", name, "Home/Attachments", attach.is_private)
def add_attachments(name, attachments): '''Add attachments to the given Communiction''' from frappe.utils.file_manager import save_url # loop through attachments for a in attachments: if isinstance(a, basestring): attach = frappe.db.get_value("File", {"name":a}, ["file_name", "file_url", "is_private"], as_dict=1) # save attachments to new doc save_url(attach.file_url, attach.file_name, "Communication", name, "Home/Attachments", attach.is_private)
def attach_file_to_doc(doctype, docname, file_url): # check if attachment is already available # check if the attachement link is relative or not if not file_url: return if not is_valid_url(file_url): return files = frappe.db.sql( """Select name from `tabFile` where attached_to_doctype='{doctype}' and attached_to_name='{docname}' and (file_url='{file_url}' or thumbnail_url='{file_url}')""" .format(doctype=doctype, docname=docname, file_url=file_url)) if files: # file is already attached return save_url(file_url, None, doctype, docname, "Home/Attachments", 0)
def attach_all_docs(document): """This function attaches drawings to the purchase order based on the items being ordered""" document = json.loads(document) document2 = frappe._dict(document) current_attachments = [] for file_url in frappe.db.sql( """select file_url from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", { 'doctype': document2.doctype, 'docname': document2.name }, as_dict=True): current_attachments.append(file_url.file_url) # add the directly linked drawings items = [] for item in document["items"]: #frappe.msgprint(str(item)) items.append(item["item_code"]) #add the child documents (from boms) items = add_bom_items(items, item["item_code"]) count = 0 for item_doc in items: #frappe.msgprint(item_doc) item = frappe.get_doc("Item", item_doc) attachments = [] # Get the path for the attachments if item.drawing_attachment: attachments.append(item.drawing_attachment) if item.stp_attachment: attachments.append(item.stp_attachment) if item.dxf_attachment: attachments.append(item.dxf_attachment) if item.x_t_attachment: attachments.append(item.x_t_attachment) if item.electrical_attachment: attachments.append(item.electrical_attachment) for attach in attachments: # Check to see if this file is attached to the one we are looking for if not attach in current_attachments: count = count + 1 myFile = save_url(attach, attach, document2.doctype, document2.name, "Home/Attachments") myFile.file_name = attach myFile.save() current_attachments.append(attach) frappe.msgprint("Attached {0} files".format(count))
def attach_file_to_doc(doctype, docname, file_url): # check if attachment is already available # check if the attachement link is relative or not if not file_url: return if not is_valid_url(file_url): return files = frappe.db.sql("""Select name from `tabFile` where attached_to_doctype='{doctype}' and attached_to_name='{docname}' and (file_url='{file_url}' or thumbnail_url='{file_url}')""".format( doctype=doctype, docname=docname, file_url=file_url )) if files: # file is already attached return save_url(file_url, None, doctype, docname, "Home/Attachments", 0)
def attach_all_docs(document, method=None): """This function attaches drawings to the purchase order based on the items being ordered""" document = json.loads(document) current_attachments = [] print(document["items"]) print(len(document["items"])) item_list = document["items"][0] print(item_list["item_code"]) for file_url in frappe.db.sql( """select file_url,name,is_private from `tabFile` where attached_to_name = '{0}'""" .format(item_list["item_code"]), as_dict=True): print("$#$#$#") print(file_url) current_attachments.append(file_url.file_url) count = 0 for item_doc in document["items"]: #frappe.msgprint(item_doc) # Check to see if the quantity is = 1 item = frappe.get_doc("Item", item_doc["item_code"]) print(item) attachments = [] # Get the path for the attachments if item.drawing_attachment: attachments.append(item.drawing_attachment) # if item.stp_attachment: # attachments.append(item.stp_attachment) # if item.dxf_attachment: # attachments.append(item.dxf_attachment) # if item.x_t_attachment: # attachments.append(item.x_t_attachment) for attach in attachments: # Check to see if this file is attached to the one we are looking for if not attach in current_attachments: count = count + 1 print("@#----------------rge-----------ef-#") save_url(file_url.file_url, file_url.file_url, "Quotation", document["name"], "Home/Attachments", file_url.is_private) frappe.msgprint("Attached {0} files".format(count))
def crear_poliza(fecha, docname): """Traerse todos los movimientos""" movimientos = frappe.db.sql( """select no_cuenta,debit,credit,voucher_no from `tabGL Entry` where posting_date=%s""", (fecha), as_dict=1) site_name = cstr(frappe.local.site) frappe.errprint(site_name) f = open(site_name + "/public/files/" + docname + ".txt", "w") f.write( "P " + str(fecha) + " 001 " + docname + "1 01 1" + "\n") f.write("N 1" + "\n") for d in movimientos: if d.debit > 0: f.write("M " + d.no_cuenta + " " + d.voucher_no + " 1 " + str(d.debit) + "\n") else: f.write("M " + d.no_cuenta + " " + d.voucher_no + " 2 " + str(d.credit) + "\n") f.close() save_url( "/files/" + docname + ".txt", docname + ".txt", "Poliza Contpaq", docname, "Home/Attachments", 0 ) # RG-agrego el file como attachment # save_url (file_url, filename, dt, dn, folder, is_private) frappe.msgprint( " POLIZA CREADA EXITOSAMENTE . " + "\n" + "<a href='javascript:void(0)' onclick='window.location.reload()'><button> RECARGAR </button></a>" ) return movimientos
def attach_all_docs(document): """This function attaches drawings to the purchase order based on the items being ordered""" document = json.loads(document) document2 = frappe._dict(document) current_attachments = [] for file_url in frappe.db.sql("""select file_url from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", {'doctype': document2.doctype, 'docname': document2.name}, as_dict=True ): current_attachments.append(file_url.file_url) # add the directly linked drawings items = [] for item in document["items"]: #frappe.msgprint(str(item)) items.append(item["item_code"]) #add the child documents (from boms) items = add_bom_items(items, item["item_code"]) count = 0 for item_doc in items: #frappe.msgprint(item_doc) item = frappe.get_doc("Item",item_doc) attachments = [] # Get the path for the attachments if item.drawing_attachment: attachments.append(item.drawing_attachment) if item.stp_attachment: attachments.append(item.stp_attachment) if item.dxf_attachment: attachments.append(item.dxf_attachment) if item.x_t_attachment: attachments.append(item.x_t_attachment) if item.electrical_attachment: attachments.append(item.electrical_attachment) for attach in attachments: # Check to see if this file is attached to the one we are looking for if not attach in current_attachments: count = count + 1 myFile = save_url(attach, attach, document2.doctype, document2.name, "Home/Attachments") myFile.file_name = attach myFile.save() current_attachments.append(attach) frappe.msgprint("Attached {0} files".format(count))
def create_gsuite_doc(doctype, docname, gs_template=None): templ = frappe.get_doc('GSuite Templates', gs_template) doc = frappe.get_doc(doctype, docname) if not doc.has_permission("read"): raise frappe.PermissionError json_data = doc.as_dict() filename = templ.document_name.format(**json_data) r = run_gsuite_script('new', filename, templ.template_id, templ.destination_id, json_data) filedata = save_url(r['url'], filename, doctype, docname, "Home/Attachments", True) comment = frappe.get_doc(doctype, docname).add_comment( "Attachment", _("added {0}").format( "<a href='{file_url}' target='_blank'>{file_name}</a>{icon}". format( **{ "icon": ' <i class="fa fa-lock text-warning"></i>' if filedata. is_private else "", "file_url": filedata.file_url.replace("#", "%23") if filedata. file_name else filedata.file_url, "file_name": filedata.file_name or filedata.file_url }))) return { "name": filedata.name, "file_name": filedata.file_name, "file_url": filedata.file_url, "is_private": filedata.is_private, "comment": comment.as_dict() if comment else {} }
def timbrado(docname, debug=True): # si = 0 c = frappe.get_doc("CFDI", docname) # si = c.ticket # si = frappe.get_doc("Sales Invoice", si) rfc_emisor = c.rfc_emisor url_timbrado = c.url_timbrado user_id = c.user_id user_password = c.user_password cfdif = genera_layout_cfdi(docname, rfc_emisor) params = { 'emisorRFC': rfc_emisor, 'UserID': user_id, 'UserPass': user_password } options = {'generarCBB': True, 'generarPDF': True, 'generarTXT': True} cliente = Cliente(url_timbrado, params, debug) source = '/home/frappe/frappe-bench/sites/comprobantes/' webfolder = c.folder dest = '/home/frappe/frappe-bench/sites/' + webfolder + '/public/files/' # dest = '/home/frappe/frappe-bench/sites/facturas.posix.mx/public/files/' if cliente.timbrar(cfdif, options): folder = 'comprobantes' if not os.path.exists(folder): os.makedirs(folder) comprobante = os.path.join(folder, cliente.uuid) for extension in ['xml', 'pdf', 'png', 'txt']: if hasattr(cliente, extension): with open(("%s.%s" % (comprobante, extension)), 'wb' if extension in ['pdf', 'png'] else 'w') as f: f.write(getattr(cliente, extension)) uuid = comprobante[13:] shutil.move( source + uuid + ".xml", dest ) # RG-Muevo el file de donde lo deja factmoderna a donde lo quiero shutil.move(source + uuid + ".png", dest) save_url( "/files/" + uuid + ".xml", uuid + ".xml", "CFDI", c.name, "Home/Attachments", 0 ) # RG-agrego el file como attachment # save_url (file_url, filename, dt, dn, folder, is_private) frappe.db.set_value("CFDI", c.name, 'cfdi_status', 'Timbrado') #RG-asi cambio el status del timbrado for d in c.items: frappe.db.set_value("Sales Invoice", d.fuente, 'cfdi_status', 'Timbrado') frappe.db.set_value( "CFDI", c.name, 'SelloCFD', cliente.SelloCFD) #RG-Asi inserto los valores del xml frappe.db.set_value("CFDI", c.name, 'FechaTimbrado', cliente.FechaTimbrado) frappe.db.set_value("CFDI", c.name, 'uuid', cliente.uuid) frappe.db.set_value("CFDI", c.name, 'NoCertificadoSAT', cliente.NoCertificadoSAT) frappe.db.set_value("CFDI", c.name, 'SelloSAT', cliente.SelloSAT) frappe.db.set_value("CFDI", c.name, 'qr', '/files/' + uuid + ".png") # empiezo a generar el archivo para el envio with open( "/home/frappe/frappe-bench/sites/" + webfolder + "/public/files/{0}.xml".format(uuid), "rb") as fileobj: filedata = fileobj.read() out = {"fname": "{0}.xml".format(uuid), "fcontent": filedata} message = "Anexo a este correo encontrara su factura. Gracias por su preferencia." frappe.sendmail(["{0}".format(c.email)], \ subject="Factura Electronica: {0}.".format(c.name), \ attachments = [out,frappe.attach_print("CFDI", c.name, file_name="{0}".format(c.name), print_format="CFDI")], \ content=message,delayed=False) frappe.msgprint( str(c.name) + " Timbrada exitosamente " + " " + "<a href='javascript:void(0)' onclick='window.location.reload()'><button class='btn btn-primary btn-sm primary-action' > Agregar XML a Factura</button></a>" ) else: frappe.msgprint("ERROR EN TIMBRADO: " + "[%s] - %s" % (cliente.codigo_error, cliente.error))
def timbrado_pago_cfdi(docname, invoice, debug=True): c = frappe.get_doc("Payment Entry", docname) si = frappe.get_doc("CFDI", invoice) rfc_emisor = si.rfc_emisor url_timbrado = si.url_timbrado user_id = si.user_id user_password = si.user_password webfolder = si.folder cfdif = genera_layout_pago_cfdi(docname, invoice, rfc_emisor) params = { 'emisorRFC': rfc_emisor, 'UserID': user_id, 'UserPass': user_password } options = {'generarCBB': True, 'generarPDF': True, 'generarTXT': True} cliente = Cliente(url_timbrado, params, debug) source = '/home/frappe/frappe-bench/sites/comprobantes/' dest = '/home/frappe/frappe-bench/sites/' + webfolder + '/public/files/' if cliente.timbrar(cfdif, options): folder = 'comprobantes' if not os.path.exists(folder): os.makedirs(folder) comprobante = os.path.join(folder, cliente.uuid) for extension in ['xml', 'pdf', 'png', 'txt']: if hasattr(cliente, extension): with open(("%s.%s" % (comprobante, extension)), 'wb' if extension in ['pdf', 'png'] else 'w') as f: f.write(getattr(cliente, extension)) # frappe.errprint("%s almacenado correctamente en %s.%s" % (extension.upper(), comprobante, extension)) # print 'Timbrado exitoso' uuid = comprobante[13:] shutil.move( source + uuid + ".xml", dest ) # RG-Muevo el file de donde lo deja factmoderna a donde lo quiero shutil.move( source + uuid + ".png", dest ) # RG-Muevo el file de donde lo deja factmoderna a donde lo quiero save_url( "/files/" + uuid + ".xml", uuid + ".xml", "Payment Entry", c.name, "Home/Attachments", 0 ) # RG-agrego el file como attachment # save_url (file_url, filename, dt, dn, folder, is_private) frappe.db.set_value("Payment Entry", c.name, 'cfdi_status', 'Timbrado') #RG-asi cambio el status del timbrado frappe.db.set_value("Payment Entry", c.name, 'uuid_pago', uuid) frappe.db.set_value( "Payment Entry", c.name, 'SelloCFD', cliente.SelloCFD) #RG-Asi inserto los valores del xml frappe.db.set_value("Payment Entry", c.name, 'FechaTimbrado', cliente.FechaTimbrado) frappe.db.set_value("Payment Entry", c.name, 'NoCertificadoSAT', cliente.NoCertificadoSAT) frappe.db.set_value("Payment Entry", c.name, 'SelloSAT', cliente.SelloSAT) frappe.db.set_value("Payment Entry", c.name, 'qr', '/files/' + uuid + ".png") frappe.msgprint( str(c.name) + " Timbrada exitosamente " + "\n\n" + "<a href='javascript:void(0)' onclick='window.location.reload()'><button class='btn btn-primary btn-sm primary-action' > Agregar XML a Pago</button></a>" ) else: # print("[%s] - %s" % (cliente.codigo_error, cliente.error)) frappe.msgprint("ERROR EN TIMBRADO: " + "[%s] - %s" % (cliente.codigo_error, cliente.error))
def td_attach_all_docs_from_item(document, strURL): from frappe import _, throw from frappe.utils import flt from frappe.utils.file_manager import save_url, save_file, get_file_name, remove_all, remove_file from frappe.utils import get_site_path, get_files_path, random_string, encode import json #Dokuman icin dosya eklerini ayarlayalim document = json.loads(document) document2 = frappe._dict(document) current_attachments = [ ] #Icinde oldugumuz dokumanda ki ek dosya bilgilerini tutar items = [] #Dokumanda ki malzeme bilgilerini tutar item_attachments = [] #Malzemede ki ek dosya bilgilerini tutar current_attachments_file_name = [] #Dosya adini saklar item_attachments_file_name = [] #Dosya adi #Once bulundugumuz dokumanda ki butun ek dosyalari bir dizi icinde (current_attachments) saklayalaim for file_info in frappe.db.sql( """select file_url, file_name from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", { 'doctype': document2.doctype, 'docname': document2.name }, as_dict=True): current_attachments.append(file_info.file_url) current_attachments_file_name.append(file_info.file_name) #frappe.msgprint("Found " + file_info.file_name + " file in this document", "Document Files") #Dokumanda ki butun malzeme kartlari icin ek dosya var mi kontrol edelim for item in document["items"]: #Malzeme kayidina ulasalim item_doc = frappe.get_doc( 'Item', item["item_code"]) #frappe.get_doc("Item",item) #frappe.msgprint(str(item_doc["attachments"][0]["file_url"])) #frappe.msgprint("Getting " + item_doc.name + " files", "Items") #Malzemeye bagli ek dosyalari alalim for file_info in frappe.db.sql( """select file_url, file_name from `tabFile` where attached_to_doctype = %(doctype)s and attached_to_name = %(docname)s""", { 'doctype': item_doc.doctype, 'docname': item_doc.name }, as_dict=True): item_attachments.append(file_info.file_url) item_attachments_file_name.append(file_info.file_name) #frappe.msgprint("Found " + file_info.file_name + " file in item " + item_doc.name, "Item Files") count = 0 dIndex = 0 #frappe.msgprint("Starting to add attachments") for attachment in item_attachments: # Check to see if this file is attached to the one we are looking for if not attachment in current_attachments: count = count + 1 #frappe.msgprint(attachment) myFile = save_url(attachment, item_attachments_file_name[dIndex], document2.doctype, document2.name, "Home/Attachments", 0) myFile.file_name = item_attachments_file_name[dIndex] #attachment myFile.save() current_attachments.append(attachment) dIndex = dIndex + 1 frappe.msgprint("{0} adet dosya eklendi".format(count))