def after_insert(self): if self.ms_certificate: if get_attachments(self.doctype,self.name): for item in get_attachments(self.doctype,self.name): frappe.errprint(item) else: url = "http://"+frappe.request.host+"/api/method/frappe.utils.print_format.download_pdf?doctype=Certificate&name="+self.name+\ "&format=New Horizons Certificate&no_letterhead=0" add_attachments(self.name,url,_("New Horizons Certificate"))
def get_full_path(self): """Returns file path from given file name""" att = get_attachments(self.doctype, self.name) if att: file_path = att[0].file_url or att[0].file_name else: frappe.throw("No Attachment found") if "/" not in file_path: file_path = "/files/" + file_path if file_path.startswith("/private/files/"): file_path = get_files_path(*file_path.split("/private/files/", 1)[1].split("/"), is_private=1) elif file_path.startswith("/files/"): file_path = get_files_path( *file_path.split("/files/", 1)[1].split("/")) else: frappe.throw( _("There is some problem with the file url: {0}").format( file_path)) return file_path
def download_attachment(dn): attachment = get_attachments("Prepared Report", dn)[0] frappe.local.response.filename = attachment.file_name[:-2] attached_file = frappe.get_doc("File", attachment.name) frappe.local.response.filecontent = gzip_decompress( attached_file.get_content()) frappe.local.response.type = "binary"
def get_attachments(self): attachments = [ d.name for d in get_attachments(self.doctype, self.name) ] attachments.append( frappe.attach_print(self.doctype, self.name, doc=self)) return attachments
def append_mail_to_doc(self, doctype, docname): related_content = """From: %(sender)s <br> To: %(recipients)s <br> Subject: %(subject)s <br> tag: %(tag)s""" % { "sender": self.sender, "recipients": self.recipients, "subject": self.subject, "tag": self.tag } comm = frappe.get_doc({ "doctype": "Communication", "subject": self.subject, "content_full": self.content, "content": related_content, "sender": self.sender, "communication_medium": "Email", "sent_or_received": "Received", "reference_doctype": doctype, "reference_name": docname }) comm.insert(ignore_permissions=True) attachments = get_attachments(self.doctype, self.name) for attachment in attachments: file_data = {} file_data.update({ "doctype": "File Data", "attached_to_doctype": "Communication", "attached_to_name": comm.name, "file_url": attachment["file_url"], "file_name": attachment["file_name"] }) f = frappe.get_doc(file_data) f.flags.ignore_permissions = True f.insert()
def test_incoming_with_attach(self): cleanup("*****@*****.**") existing_file = frappe.get_doc({ 'doctype': 'File', 'file_name': 'erpnext-conf-14.png' }) frappe.delete_doc("File", existing_file.name) with open( os.path.join(os.path.dirname(__file__), "test_mails", "incoming-2.raw"), "r") as testfile: test_mails = [testfile.read()] email_account = frappe.get_doc("Email Account", "_Test Email Account 1") email_account.receive(test_mails=test_mails) comm = frappe.get_doc("Communication", {"sender": "*****@*****.**"}) self.assertTrue("*****@*****.**" in comm.recipients) # check attachment attachments = get_attachments(comm.doctype, comm.name) self.assertTrue( "erpnext-conf-14.png" in [f.file_name for f in attachments]) # cleanup existing_file = frappe.get_doc({ 'doctype': 'File', 'file_name': 'erpnext-conf-14.png' }) frappe.delete_doc("File", existing_file.name)
def download_zip_files(filters): """Download selected files as zip. Args: filters (string): Stringified JSON objects doctype and docnames """ if isinstance(filters, string_types): filters = json.loads(filters) doctype = filters.get('doctype') docnames = filters.get('docnames') output_filename = "{0}.zip".format(doctype) output_path = frappe.get_site_path('private', 'files', output_filename) if not frappe.db.exists("File", output_filename): input_files = [] for docname in docnames: attachments = get_attachments(doctype, docname['name']) for d in attachments: doc = frappe.get_doc("File", d.name) input_files.append(doc.get_full_path()) #Creates a zip file containing all attachments with zipfile.ZipFile(output_path, 'w') as output_zip: for input_file in input_files: output_zip.write(input_file, arcname=os.path.basename(input_file)) with open(output_path, 'rb') as fileobj: filedata = fileobj.read() frappe.local.response.filename = output_filename frappe.local.response.filecontent = filedata frappe.local.response.type = "download"
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 get_e_invoice_attachments(invoice): out = [] attachments = get_attachments(invoice.doctype, invoice.name) company_tax_id = invoice.company_tax_id if invoice.company_tax_id.startswith("IT") else "IT" + invoice.company_tax_id for attachment in attachments: if attachment.file_name and attachment.file_name.startswith(company_tax_id) and attachment.file_name.endswith(".xml"): out.append(attachment) return out
def make(doctype=None, name=None, content=None, subject=None, sent_or_received = "Sent", sender=None, recipients=None, communication_medium="Email", send_email=False, attachments='[]',email_account=None,doc=None,action=None,cc=None,bcc=None,form_values=None,ref_no=None, sender_full_name=None,recipients_name=None): """ called from composer These Method manages craeting new mailbox document for reply/Forwarded and compose calls respective Methods """ import json if doc: doc = json.loads(doc) mailbox_doc = { "doctype":doctype, "name":name, "content":content, "subject":subject, "sender":sender, "recipients":recipients, "attachments":attachments, "email_account":email_account, "doc":doc, "action":action, "cc":cc, "bcc":bcc, "form_values":json.loads(form_values), } return_dic = {} if not validated_email_addrs(mailbox_doc,return_dic): return return_dic # add frappe.session.user != "Administrator" to condition if action and action != 'compose': mailbox_doc["sender"] = frappe.db.get_value("Email Account Config", {"name":email_account},"email_id") mailbox_doc["sender"] if mailbox_doc['action'] == 'compose': attachments = get_attachments(ref_no) else: attachments = prepare_attachments(attachments) mailbox = append_to_mailbox(mailbox_doc) added_attachments = add_attachments(attachments,mailbox.name,mailbox_doc["action"]) recipients = send_mail(mailbox_doc,attachments) return { "name": mailbox.name, "recipients": ", ".join(recipients) if recipients else None }
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 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 _file = frappe.get_doc({ "doctype": "File", "file_url": attach_item.file_url, "file_name": attach_item.file_name, "attached_to_name": self.name, "attached_to_doctype": self.doctype, "folder": "Home/Attachments"}) _file.save()
def import_package(self): attachment = get_attachments(self.doctype, self.name) if not attachment: frappe.throw(frappe._('Please attach the package')) attachment = attachment[0] # get package_name from file (package_name-0.0.0.tar.gz) package_name = attachment.file_name.split('.')[0].rsplit('-', 1)[0] if not os.path.exists(frappe.get_site_path('packages')): os.makedirs(frappe.get_site_path('packages')) # extract subprocess.check_output([ 'tar', 'xzf', frappe.get_site_path(attachment.file_url.strip('/')), '-C', frappe.get_site_path('packages') ]) package_path = frappe.get_site_path('packages', package_name) # import Package with open(os.path.join(package_path, package_name + '.json'), 'r') as packagefile: doc_dict = json.loads(packagefile.read()) frappe.flags.package = import_doc(doc_dict) # collect modules files = [] log = [] for module in os.listdir(package_path): module_path = os.path.join(package_path, module) if os.path.isdir(module_path): get_doc_files(files, module_path) # import files for file in files: import_file_by_path(file, force=self.force, ignore_version=True, for_sync=True) log.append('Imported {}'.format(file)) self.log = '\n'.join(log)
def test_incoming_with_attach(self): frappe.db.sql("delete from tabCommunication where sender='*****@*****.**'") existing_file = frappe.get_doc({'doctype': 'File Data', 'file_name': 'erpnext-conf-14.png'}) frappe.delete_doc("File Data", existing_file.name) delete_file_from_filesystem(existing_file) with open(os.path.join(os.path.dirname(__file__), "test_mails", "incoming-2.raw"), "r") as f: test_mails = [f.read()] email_account = frappe.get_doc("Email Account", "_Test Email Account 1") email_account.receive(test_mails=test_mails) comm = frappe.get_doc("Communication", {"sender": "*****@*****.**"}) self.assertTrue("*****@*****.**" in comm.recipients) # check attachment attachments = get_attachments(comm.doctype, comm.name) self.assertTrue("erpnext-conf-14.png" in [f.file_name for f in attachments])
def validate(self): self.title = self.product_development + " - " + str( datetime.date.today().year) + str( datetime.date.today().month).zfill(2) + str( datetime.date.today().day).zfill(2) # Validate frequency if int(self.test_frequency) > 30: frappe.throw(_("The Test Frequency can not be more than 30")) # Set photos attached field attachments = [ d.name for d in get_attachments(self.doctype, self.name) ] if len(attachments) > 0 and self.photos_attached == 0: self.photos_attached = 1 elif len(attachments) == 0 and self.photos_attached == 1: self.photos_attached = 0
def send_quotation(name,mail_id,subject,message,cc=None): qtn = frappe.get_doc("Quotation",name) attachments = frappe.attach_print("Quotation", name, file_name="Quotation", print_format="Quotation New") attachments = [d.name for d in get_attachments("Quotation",name)] attachments.append(frappe.attach_print(qtn.doctype, qtn.name, doc=qtn)) # attachments.append(qtn.attachment) # attach = [d.name for d in get_attachments("Quotation",name)] # frappe.errprint(attach) email_args = { "recipients": mail_id, "subject": subject, "message": message, "attachments":attachments, "sender":frappe.get_doc('User', frappe.session.user).email, "now": True, } if cc: cc = { "cc":cc } email_args.update(cc) frappe.enqueue(method=frappe.sendmail, queue='short', timeout=300, async=True, **email_args)
def append_mail_to_doc(self,doctype,docname): related_content = """From: %(sender)s <br> To: %(recipients)s <br> Subject: %(subject)s <br> tag: %(tag)s"""%{ "sender":self.sender, "recipients":self.recipients, "subject":self.subject, "tag":self.tag } comm = frappe.get_doc({ "doctype":"Communication", "subject": self.subject, "content_full": self.content, "content":related_content, "sender": self.sender, "communication_medium": "Email", "sent_or_received": "Received", "reference_doctype":doctype, "reference_name": docname }) comm.insert(ignore_permissions=True) attachments = get_attachments(self.doctype, self.name) for attachment in attachments: file_data = {} file_data.update({ "doctype": "File Data", "attached_to_doctype":"Communication", "attached_to_name":comm.name, "file_url":attachment["file_url"], "file_name":attachment["file_name"] }) f = frappe.get_doc(file_data) f.flags.ignore_permissions = True f.insert();
def split_pages(args): self = frappe.get_doc("Project Document", args) this_args = frappe.get_all("Project Document Pages", filters={'parent': args}) for doc in this_args: print(doc.name) print(type(doc)) try: frappe.delete_doc("Project Document Pages", doc.name) except Exception: frappe.throw(""" Not permitted. Do Not Know Why. """) ### ### Find the right public/private folder for attachments ### files = get_attachments(self.doctype, self.name) path = frappe.get_app_path('techflow').split('/') folders = [] for folder in path: if (folder != 'apps'): folders.append(folder) else: folders.append('sites') break fp_url = get_files_path(files[0]['file_name']) file_path = '/'.join(folders) + fp_url[1:] ## ## PyPDF2 at Work ## pdf_file = PdfFileReader(file_path) print('Number of Pages: ', pdf_file.getNumPages()) print(self.get_value('project')) prj_folder = "ProjectDocuments" print( 'Folder Project Document Exists:', bool( frappe.db.exists('File', { 'name': r"Home/ProjectDocuments", 'is_folder': 1 }))) if frappe.db.exists('File', { 'name': r"Home/ProjectDocuments", 'is_folder': 1 }): print('the folder exists') else: print('try to create folder...........') home = frappe.get_doc("File", "Home") print(home.name) prj_doc_folder = frappe.get_doc({ "doctype": "File", "is_folder": 1, "folder": home.name, "file_name": "ProjectDocuments" }) prj_doc_folder.save() ## ## Create the Project Folder ## prj_path = r"/" + self.get_value('project') if frappe.db.exists('File', { 'name': r"Home/ProjectDocuments" + prj_path, 'is_folder': 1 }): print('the Project folder exists') else: print('try to create Project folder...........') parent_folder = frappe.get_doc("File", r"Home/ProjectDocuments") print(parent_folder.name) prj_folder = frappe.get_doc({ "doctype": "File", "is_folder": 1, "folder": parent_folder.name, "file_name": self.get_value('project') }) prj_folder.save() ## ## Create the Document Folder ## doc_path = r"/" + self.name if frappe.db.exists('File', { 'name': r"Home/ProjectDocuments" + prj_path + doc_path, 'is_folder': 1 }): print('the Document folder exists') else: print('try to create Document folder...........') parent_folder = frappe.get_doc("File", r"Home/ProjectDocuments" + prj_path) print(parent_folder.name) doc_folder = frappe.get_doc({ "doctype": "File", "is_folder": 1, "folder": parent_folder.name, "file_name": self.name }) doc_folder.save() ## ## PDF Split and Save Single PDF Pages ## #folder_path = r"Home/ProjectDocuments"+prj_path+doc_path #print(folder_path) page_count = 0 for page in range(pdf_file.getNumPages()): page_count += 1 page_file = pdf_file.getPage(page) output = PdfFileWriter() output.addPage(page_file) public_files = frappe.get_site_path('public', 'files') #public_files = r"/files/" abs_path = os.path.abspath(public_files) + r"/" file_path = r"/" + self.name + "_page_" + str(page) + ".pdf" output_path = abs_path + file_path output_stream = open(output_path, 'wb') output.write(output_stream) output_stream.close() ## ## Create New Document Page for every PDF page ## print('inside the loop', page) p_document_page = frappe.get_doc({ "doctype": "Project Document Pages", "parenttype": "Project Document", "parentfield": "document_pages", "parent": self.name, "idx": page, "page_name": str(page) + " " + self.get_title(), #"file_url": output_path }) p_document_page.insert() ## ## Create New File Doc for every PDF page ## print('The cached key for Project Document Pages') frappe.get_document_cache_key("Project Document Pages", p_document_page.name) #print(type(p_document_page_name)) #print(p_document_page_name) last = frappe.get_last_doc("Project Document Pages") print('cache:', p_document_page.name) print('last:', last.name) frappe.get_doc({ "doctype": "File", "attached_to_doctype": "Project Document Pages", "attached_to_name": p_document_page.name, "file_url": r"/files" + file_path, "file_name": file_path[1:], "folder": r"Home/ProjectDocuments" + prj_path + doc_path }).save() frappe.msgprint( "The document has been splitted in {} pages.".format(page_count)) return args
def write_production_order(sales_order_name): sales_order = frappe.get_doc("Sales Order", sales_order_name) settings = frappe.get_doc("Trumpf Settings") target_path = settings.physical_path # collect items items = [] for i in sales_order.items: item_record = frappe.get_doc("Item", i.item_code) if item_record.trumpf_fab_opened == 1 and item_record.trumpf_item_code: if item_record.material: material = cgi.escape(item_record.material) else: material = None if item_record.drawing_no: drawing_no = cgi.escape(item_record.drawing_no) else: drawing_no = None items.append({ 'item_code': item_record.item_code, 'item_name': cgi.escape(item_record.item_name), 'trumpf_item_code': item_record.trumpf_item_code, 'qty': i.qty, 'drawing_no': drawing_no, 'material': material, 'order_code': "{0}/{1}".format(sales_order_name, i.idx), 'delivery_date': "{day:02d}.{month:02d}.{year:04d} 00:00".format( day=i.delivery_date.day, month=i.delivery_date.month, year=i.delivery_date.year) }) attachments = get_attachments(dt="Sales Order", dn=sales_order_name) if attachments and len(attachments) > 0: documents = [] for attachment in attachments: documents.append({ 'url': get_url(attachment['file_url']), 'name': attachment['name'], 'filename': attachment['file_name'] }) else: documents = None data = { 'po_no': sales_order.po_no, 'customer': sales_order.customer, 'customer_name': cgi.escape(sales_order.customer_name), 'sales_order': sales_order.name, 'items': items, 'delivery_date': "{day:02d}.{month:02d}.{year:04d} 00:00".format( day=sales_order.delivery_date.day, month=sales_order.delivery_date.month, year=sales_order.delivery_date.year) } # only create transfer file if there are items if len(items) > 0: content = frappe.render_template('kuchelmeister/trumpf/production_order.html', data) file = codecs.open("{path}ProdOrderImp{sales_order}.xml".format(path=target_path, sales_order=sales_order_name), "w", "utf-8") file.write(content) file.close() # add log add_log(title="Sales Order sent to FAB", message="Sales Order: {sales_order_name}".format( sales_order_name=sales_order_name)) return
def write_item(item_code): item = frappe.get_doc("Item", item_code) settings = frappe.get_doc("Trumpf Settings") target_path = settings.physical_path # create a unique item code, limited to 21 characters based on md5 hash trumpf_item_code = hashlib.md5(item_code.encode('utf-8')).hexdigest()[:21] if item.material: material = cgi.escape(item.material) else: material = None attachments = get_attachments(dt="Item", dn=item_code) cad_file_name = None if attachments and len(attachments) > 0: documents = [] for attachment in attachments: if attachment['is_private'] == 0: documents.append({ 'url': "{0}{1}".format(settings.smb_path, attachment['file_name']), 'name': attachment['name'], 'filename': attachment['file_name'] }) # GEO files override other drawing types if attachment['file_name'].endswith(".geo"): cad_file_name = "{0}{1}".format(settings.smb_path, attachment['file_name']) # attach other drawing types if empty if (attachment['file_name'].endswith(".dxf") or attachment['file_name'].endswith(".dxg") or attachment['file_name'].endswith(".step")) and cad_file_name == None: cad_file_name = "{0}{1}".format(settings.smb_path, attachment['file_name']) else: documents = None # prepare description: no html, only 50 characters soup = BeautifulSoup(item.description) short_description = soup.get_text()[:50] if item.drawing_no: drawing_no = cgi.escape(item.drawing_no) else: drawing_no = None data = { 'item_code': cgi.escape(item_code[:50]), 'trumpf_item_code': trumpf_item_code, 'description': cgi.escape(short_description), 'drawing_no': cgi.escape(drawing_no), 'item_group': cgi.escape(item.item_group), 'material': material, 'default_uom': item.stock_uom, 'documents': documents, 'prices': None, 'cad_file_name': cad_file_name } # check if there is an active BOM active_bom = frappe.get_all("BOM", filters={'item': item_code, 'is_active': 1, 'is_default': 1, 'docstatus': 1}, fields=['name']) if active_bom and len(active_bom) > 0: bom = frappe.get_doc("BOM", active_bom[0]['name']) bom_parts = [] for item in bom.items: item_data = frappe.get_doc("Item", item.item_code) if item_data.trumpf_item_code: bom_parts.append({ 'part_no': item_data.trumpf_item_code, 'qty': item.qty, 'uom': item.uom }) if len(bom_parts) > 0: data['bom_parts'] = bom_parts content = frappe.render_template('kuchelmeister/trumpf/item.html', data) file = codecs.open("{path}MasterDataImp{item_code}.xml".format(path=target_path, item_code=trumpf_item_code), "w", "utf-8") file.write(content) file.close() # update item item.trumpf_fab_opened = 1 # mark as exported item.trumpf_item_code = trumpf_item_code # store Trumpf item code item.save() # add log add_log(title="Item sent to FAB", message="Item: {item_code}".format(item_code=item_code)) return
def prepare_item(item): item.source_type = "local" item.attachments = get_attachments('Item', item.item_code) return item
def get_attachments(self): attachments = [d.name for d in get_attachments(self.doctype, self.name)] attachments.append(frappe.attach_print(self.doctype, self.name, doc=self)) return attachments
def download_attachment(dn): attachment = get_attachments("Prepared Report", dn)[0] frappe.local.response.filename = attachment.file_name[:-2] frappe.local.response.filecontent = gzip_decompress(get_file(attachment.name)[1]) frappe.local.response.type = "binary"
def certificate_creation(**kwargs): name_of_certificate = [] data = json.loads(kwargs.get('args')) email_id_of_cc = [] if kwargs['print_format'] in [ "New Horizons Certificate", "New Horizons Zertifikat" ]: if data.get('send_by_mail') == 1 and data.get('cc'): email_id_of_cc = (data.get('cc').encode('utf-8')).split(",") if data.get('send_by_mail') == 1: predefined_text_content = data.get('predefined_text').encode( 'utf-8') predefined_text_value = frappe.db.get_value( "Predefined Text Container", predefined_text_content, "predefined_text_container".encode('utf-8')) student_data = json.loads(kwargs['student_data']) student_not_have_certficate = [] if data.get('instructor'): instructor_employee_name = frappe.db.get_values( "Instructor", {"name": data.get('instructor')}, ["instructor_name", "employee"], as_dict=True) for student_name in student_data.keys(): name = check_student_for_certificate(kwargs['project_name'], student_name, data.get('instructor')) if name: certificate_doc = frappe.get_doc("Certificate", name) attachments_list = [] if get_attachments("Certificate", name): for item in get_attachments("Certificate", name): attachments_list.append(item['file_name']) if kwargs['print_format'] not in attachments_list: attach_pdf_as_certificate(name, kwargs['print_format']) if data.get('send_by_mail') == 1 and certificate_doc: check_student_email_id_and_send_mail( student_data[student_name][0], student_data[student_name][1], kwargs['print_format'], name, predefined_text_content, predefined_text_value, email_id_of_cc) frappe.db.set_value("Certificate", certificate_doc.name, "send_by_mail", 1) name_of_certificate.append(name) else: student_not_have_certficate.append(student_name) if student_not_have_certficate: for student in student_not_have_certficate: certificate = frappe.new_doc("Certificate") certificate.student = student certificate.student_email_id = student_data[student][0] certificate.student_name = student_data[student][1] certificate.project = kwargs['project_name'] certificate.item = kwargs['item'] certificate.item_name = kwargs['item_name'] certificate.training_center = kwargs['training_center'] certificate.instructor = data.get('instructor') if data.get('instructor'): certificate.employee = instructor_employee_name[0]['employee'] certificate.instructor_name = instructor_employee_name[0][ 'instructor_name'] if kwargs['print_format'] in [ "New Horizons Certificate", "New Horizons Zertifikat" ]: if data.get('send_by_mail') == 1: certificate.predefined_text_container = predefined_text_content certificate.predefined_text_container_value = predefined_text_value certificate.make_certificate_from = "From Project" certificate.save(ignore_permissions=True) attach_pdf_as_certificate(certificate.name, kwargs['print_format']) if data.get('send_by_mail') == 1: check_student_email_id_and_send_mail( student_data[student][0], student_data[student][1], kwargs['print_format'], certificate.name, predefined_text_content, predefined_text_value, email_id_of_cc) frappe.db.set_value("Certificate", certificate.name, "send_by_mail", 1) name_of_certificate.append(certificate.name) return name_of_certificate
def download_attachment(dn): attachment = get_attachments("Prepared Report", dn)[0] download_file(attachment.file_url)